character encoding conversion

2004-12-11 Thread Dylan

Here's what I'm trying to do:

- scrape some html content from various sources

The issue I'm running to:

- some of the sources have incorrectly encoded characters... for
example, cp1252 curly quotes that were likely the result of the author
copying and pasting content from Word

I've searched and read for many hours, but have not found a solution
for handling the case where the page author does not use the character
encoding that they have specified.

Things I have tried include encode()/decode(), and replacement lookup
tables (i.e. something like
http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/116158ad706dc7c1/11991de6ced3406b?q=python+html+parser+cp1252&_done=%2Fgroups%3Fq%3Dpython+html+parser+cp1252%26qt_s%3DSearch+Groups%26&_doneTitle=Back+to+Search&&d#11991de6ced3406b
) .  However, I am still unable to convert the characters to something
meaningful.  In the case of the lookup table, this failed as all of
the imporoperly encoded characters were returning as ? rather than
their original encoding.

I'm using urllib and htmllib to open, read, and parse the html
fragments, Python 2.3 on OS X 10.3 

Any ideas or pointers would be greatly appreciated.

-Dylan Schiemann
http://www.dylanschiemann.com/



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Aborting Python from C code

2011-04-30 Thread Dylan Evans
I think i see what you are trying to do but it depends on the environment
and your goals.

Generally i think you need to separate your code by forking (or perhaps you
have already done that?),
then you can run a check to see if the process died as expected. I don't
know though, this not much
information to go on, but if you are running untrusted code then you need to
be able to isolate and kill it.

On Sat, Apr 30, 2011 at 6:17 PM, Chris Angelico  wrote:

> On Sat, Apr 30, 2011 at 6:08 PM, Miki Tebeka 
> wrote:
> >> In our sandboxed Python environment, I would like to be able to
> >> trigger an abort of the currently-running Python script (from a signal
> >> handler or another thread).
> > There's os.abort
>
> That core dumps the process; what I want is to force the
> PyRun_StringFlags to return. Normally PyErr_SetInterrupt will do
> exactly this (within a few instructions is fine), but the Python
> script is able to prevent that from happening, which I don't like.
>
> Chris Angelico
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
http://dylan-evans.github.com

"The UNIX system has a command, nice ... in order to be nice to the other
users. Nobody ever uses it." - Andrew S. Tanenbaum
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: stderr writting before stdout

2020-05-24 Thread Dylan Evans
Hi,
This data is being line buffered, so either a newline or flush is required
to get it to actually write to the terminal / file.

On Sun, May 24, 2020 at 2:34 PM Souvik Dutta 
wrote:

> Also this code maintains order i.e. writting is displayed before no errors.
> Why is that?
>
> import sys
> sys.stdout.write("Writting \n")
> sys.stderr.write("No errors \n")
>
> On Sun, 24 May, 2020, 9:57 am Souvik Dutta, 
> wrote:
>
> > Hi,
> > Is there any precedence or priority order by which sys.stderr.write() and
> > sys.stdout.write() works. Because when running the below code...
> >
> > import sys
> > sys.stdout.write("Writting")
> > sys.stderr.write("No errors \n")
> >
> > No errors is written (displayed) first and writting is written later. Why
> > does this happen?
> >
> >
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Final statement from Steering Council on politically-charged commit messages

2020-08-17 Thread Dylan Distasio
That's quite an interesting ruling by the SC.  I'm not surprised to see
them bend the knee to PC, but it is disheartening to see they're fine
opening a can of political worms in a programming language.  I suspect they
will deplore messages outside of their bubble though.

On Mon, Aug 17, 2020 at 2:30 PM Chris Angelico  wrote:

> For context, see this commit:
>
>
> https://github.com/python/peps/commit/0c6427dcec1e98ca0bd46a876a7219ee4a9347f4
>
> The commit message is highly politically charged and is now a
> permanent part of the Python commit history. The Python Steering
> Council has this to say:
>
> https://github.com/python/steering-council/issues/34#issuecomment-675028005
>
> "The SC discussed this and ... we do not deplore the message."
>
> So now we know: go ahead and put all the political messages you like
> into the commit messages, just don't put anything inappropriate into
> the content. White supremacy has been mentioned; who wants to pick the
> next hot topic?
>
> ChrisA
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


compound strip() string problem

2005-04-08 Thread Dylan Wilson
Hi,
I'm new to python and i have a string problem.
My problem is this
--
>>>import time
>>>time = time.asctime()
>>>time
'Fri Apr 08 22:14:14 2005'
>>>ti = time[0:13]
>>>me = time[14:16]
>>>time = ti + me
>>>time
'Fri Apr 08 2214'
--
Now i need to compond that string remove the whitespace if you will.Well
i read up on strip(), lstrip() and rstrip() and all i could deduce was 
that they striped the whitespace from the start and/or end of the 
string.But I tried that anyway and failed.Is there an easier way than i 
did it below? I'm sorry it's ugly and tedious.
--
#!/bin/bash/env python

import os, time
#Figure out what os this is
platform = os.name
#Create string with date, time and extension for our pcap file
ext = '.out'
time = time.asctime()
ti = time[0:13]   #
me = time[14:16] #
time = ti + me  #There has to be a better way to do this?
fo = time[0:3]   #
rm = time[4:7]#
at  = time[11:18]
time = fo + rm + at + ext
#Get rid of yukkies
del ti, me, ext, fo, rm, at
#create command string
flag = '-w'
wincommand = 'c:/progra~1/ethereal/tethereal'
lincommand = '/usr/sbin/./tethereal'
#run tethereal and send the output to a pcap file DDDMMMHHMM.out
if platform == 'nt':
os.system('%s %s %s' % (wincommand, flag, time))
if platform == 'posix':
os.system('%s %s %s' % (lincommand, flag, time))
--
Thanks,
Dylan
--
http://mail.python.org/mailman/listinfo/python-list


HELP PLEASE printing single characters!

2015-12-02 Thread Dylan Riley
hi all,
I have been trying to figure out all day why my code is printing single 
characters from my list when i print random elements using random.choice the 
elements in the list are not single characters for example when i print, 
print(LIST[random.choice]) i get:
["e", "x", "a", "m", "p", "l", "e"] when i should get ["example"].

my code is:
#Create a program that prints a list of words in random order.
#The program should print all the words and not repeat any.

import random

LIST = ["blue ", "red ", "yellow ", "green ", "orange "]
order = []

print("This game will print a random order of colours")
print("The list is", LIST)
input("press enter to start")



while LIST != []:
choice = random.choice(LIST)
order += choice
while choice in LIST:
LIST.remove(choice)
print(order)



input("press enter to exit")

thanks in advance guys
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: HELP PLEASE printing single characters!

2015-12-02 Thread Dylan Riley
On Wednesday, December 2, 2015 at 7:09:23 PM UTC, Ian wrote:
> On Wed, Dec 2, 2015 at 12:58 PM, Dylan Riley  wrote:
> > hi all,
> > I have been trying to figure out all day why my code is printing single 
> > characters from my list when i print random elements using random.choice 
> > the elements in the list are not single characters for example when i 
> > print, print(LIST[random.choice]) i get:
> > ["e", "x", "a", "m", "p", "l", "e"] when i should get ["example"].
> 
> Remember that strings are iterable, and that iterating over strings
> results in individual characters. That should give you a clue as to
> what's going on.
> 
> > my code is:
> > #Create a program that prints a list of words in random order.
> > #The program should print all the words and not repeat any.
> >
> > import random
> >
> > LIST = ["blue ", "red ", "yellow ", "green ", "orange "]
> > order = []
> >
> > print("This game will print a random order of colours")
> > print("The list is", LIST)
> > input("press enter to start")
> >
> >
> >
> > while LIST != []:
> > choice = random.choice(LIST)
> > order += choice
> 
> Addition on a list does concatenation, not appending. So this takes
> each element from choice and adds them individually to order.

hi ian what would be the correct code to use in this situation then because as 
far as i am aware the elements of my list should be printed as whole elements 
and not just characters of the elements.
-- 
https://mail.python.org/mailman/listinfo/python-list


problem

2015-12-04 Thread Dylan Goodwin
Every time I try and run python 3.5 it keeps coming up with modify, repair
or uninstall
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Is it possible to deliver different source distributions for different Python versions?

2015-04-06 Thread Dylan Evans
> I would like to distribute a python package with different code for 
> Python 2.* than for Python 3.*. (Mostly this is because of different 
> unicode string handling). 

> There is nothing in to setuptools or PyPi that directly supports 
> this scenario. 
The 2to3 utility will handle the unicode differences. You can set the keyword 
argument use_2to3 to True in setup.py dependent on the version number like so:



extra = {}

if sys.version_info >= (3, ):

    extra['use_2to3'] = True



and then put **extra in setup.py. This will run 2to3 on the code when it 
installs it. I don’t know whether this is good style but it does work. I got it 
from the feedparser source code. 


-- 
Dylan Evans

On 6 April 2015 at 11:05:47, python-list-requ...@python.org 
(python-list-requ...@python.org) wrote:

Send Python-list mailing list submissions to  
python-list@python.org  

To subscribe or unsubscribe via the World Wide Web, visit  
https://mail.python.org/mailman/listinfo/python-list  
or, via email, send a message with subject or body 'help' to  
python-list-requ...@python.org  

You can reach the person managing the list at  
python-list-ow...@python.org  

When replying, please edit your Subject line so it is more specific  
than "Re: Contents of Python-list digest..."  
Today's Topics:  

1. Permission denied when opening a file that was created  
concurrently by os.rename (Windows) (Alexey Izbyshev)  
2. Re: Permission denied when opening a file that was created  
concurrently by os.rename (Windows) (Chris Angelico)  
3. Re: Permission denied when opening a file that was created  
concurrently by os.rename (Windows) (Alexey Izbyshev)  
4. Re: Permission denied when opening a file that was created  
concurrently by os.rename (Windows) (Dave Angel)  
5. Help with pipes, buffering and pseudoterminals (Daniel Ellis)  
6. Re: Permission denied when opening a file that was created  
concurrently by os.rename (Windows) (Terry Reedy)  
7. Is it possible to deliver different source distributions for  
different Python versions? (Dave Hein)  
8. ANN: polynice 0.7 - a nice(1) like utility for throttling  
processes (garabik-news-2005...@kassiopeia.juls.savba.sk)  
9. Re: Help with pipes, buffering and pseudoterminals (Nobody)  
10. Re: Help with pipes, buffering and pseudoterminals  
(Cameron Simpson)  
11. Re: Is it possible to deliver different source distributions  
for different Python versions? (Steven D'Aprano)  
12. XML Parsing (Sepideh Ghanavati)  
13. Re: XML Parsing (Ben Finney)  
14. Re: Is it possible to deliver different source distributions  
for different Python versions? (Mark Lawrence)  
15. Re: Is it possible to deliver different source distributions  
for different Python versions? (Stefan Behnel)  
16. Re: XML Parsing (Stefan Behnel)  
17. Re: OOP for System Administrator (pankaj sharma)  
18. implementing pyshark (Michael S.)  
Hello!  

I've hit a strange problem that I reduced to the following test case:  
* Run several python processes in parallel that spin in the following  
loop:  
while True:  
if os.path.isfile(fname):  
with open(fname, 'rb') as f:  
f.read()  
break  
* Then, run another process that creates a temporary file and then  
renames it to the name than other processes are expecting  
* Now, some of the reading processes occasionally fail with "Permission  
denied" OSError  

I was able to reproduce it on two Windows 7 64-bit machines. It seems  
when the file appears on the filesystem it is still unavailable to  
reading, but I have no idea how it can happen. Both source and  
destination files are in the same directory, and the destination doesn't  
exist before calling os.rename. Everything I could find indicates that  
os.rename should be atomic under this conditions even on Windows, so  
nobody should be able to observe the destination in unaccessible state.  

I know that I can workaround this problem by removing useless  
os.path.isfile() check and wrapping open() with try-except, but I'd like  
to know the root cause of the problem. Please share you thoughts.  

The test case is attached, the main file is test.bat. Python is  
expected to be in PATH. Stderr of readers is redirected to *.log. You  
may need to run several times to hit the issue.  

Alexey Izbyshev,  
research assistant,  
ISP RAS  


On Mon, Apr 6, 2015 at 3:45 AM, Alexey Izbyshev  wrote:  
> The test case is attached, the main file is test.bat. Python is expected to  
> be in PATH. Stderr of readers is redirected to *.log. You may need to run  
> several times to hit the issue.  

You have an interesting-looking problem, but the attachment didn't  
arrive. Is it short enough to include in-line as text in your email?  

ChrisA  

On 2015-04-05 20:45, Alexey Izbyshev wrote:  
> Hello!  
>  
> I've hit a strange problem that I reduced to the follow

Re: Python-list Digest, Vol 139, Issue 7

2015-04-06 Thread Dylan Evans
On Mon, Apr 6, 2015 at 5:52 AM, Steven D’Aprano  wrote:
> I understand that Gmail is a pig about these sorts of things, and makes it
> really hard to avoid breaking list etiquette. We appreciate whatever you
> can do, and while a few of us may bark occasionally, we don't bite.

Oh my days, I’m really sorry about that! It didn’t cross my mind that I was 
using the rich text composer, and I cursed myself for leaving the whole email 
on the end.

I use an email client called Airmail, so I’ve just set plain text as the 
default. It shouldn’t affect me at all.

Thank you for being understanding and my apologies once again. I hope my 
attempt at help was at least readable.

(Also sorry if I’m committing another faux pas by clogging up the list but I 
had to apologise!)

—

Dylan Evans
-- 
https://mail.python.org/mailman/listinfo/python-list


error help import random

2015-11-20 Thread Dylan Riley
This is my fortune cookie program i wrote in python.
the problem is it will not run past the first line of input.
could someone please identify the error and explain to me why.
here is the code:

#the program silulates a fortune cookie
#the program should display one of five unique fortunes, at randon, each time 
its run

import random

print("  \\ \\ \\ \\ DYLANS FORTUNE COOKIE \\ \\ \\ ")
print("\n\n\tGood things come to those who wait")
input("\nPress enter to see your fortune")

fortune = random.randrange(6) + 1
print(fortune)
if fortune == 1:
print("happy")
elif fortune == 2:
print("horny")
elif fortune == 3:
print("messy")
elif fortune == 4:
print("sad")
elif fortune == 5:
print("lool")

print("hope ypu enjoyed your fortune being told")
input("\nPress enter to exit")


many thanks in advance
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: error help import random

2015-11-20 Thread Dylan Riley
On Friday, November 20, 2015 at 11:06:05 PM UTC, Rob Gaddi wrote:
> On Fri, 20 Nov 2015 15:15:42 -0500, Terry Reedy wrote:
> 
> > On 11/20/2015 12:22 PM, Dylan Riley wrote:
> >> This is my fortune cookie program i wrote in python.
> >> the problem is it will not run past the first line of input.
> >> could someone please identify the error and explain to me why.
> >> here is the code:
> >>
> >> #the program silulates a fortune cookie #the program should display one
> >> of five unique fortunes, at randon, each time its run
> >>
> >> import random
> >>
> >> print("  \\ \\ \\ \\ DYLANS FORTUNE COOKIE \\ \\ \\ ")
> >> print("\n\n\tGood things come to those who wait")
> >> input("\nPress enter to see your fortune")
> >>
> >> fortune = random.randrange(6) + 1 print(fortune)
> >> if fortune == 1:
> >>  print("happy")
> >> elif fortune == 2:
> >>  print("horny")
> >> elif fortune == 3:
> >>  print("messy")
> >> elif fortune == 4:
> >>  print("sad")
> >> elif fortune == 5:
> >>  print("lool")
> > 
> > Use a dict instead of if-elif.
> > 
> > i = random.randrange(6)
> > fortunes = {0:'happy', 1:'horny', 2:'messy',
> >  3:'sad', 4:'lool', 5:'buggy'}
> > print(i, fortunes[i])
> > 
> 
> Or a list/tuple, which saves in typing, memory, and access time.
> 
>   fortunes = ('happy', 'horny', 'messy', 'sad', 'lool', 'buggy')
>   i = random.randrange(len(fortunes))
>   print(i, fortunes[i])
> 
> Or to be lazier still, just use random.choice
> 
>   fortunes = ('happy', 'horny', 'messy', 'sad', 'lool', 'buggy')
>   print(random.choice(fortunes))
> 
> None of which actually addresses the OP's issue with input(), but it's 
> nice to get the back half clean as well.
> 
> -- 
> Rob Gaddi, Highland Technology -- www.highlandtechnology.com
> Email address domain is currently out of order.  See above to fix.

very nice i like the way you code. i managed to solve the problem it was 
because i wasnt using raw_input however i updated to python 3 so the original 
now works. many thanks anyway
-- 
https://mail.python.org/mailman/listinfo/python-list


anyone tell me why my program will not run?

2015-11-20 Thread Dylan Riley
i am learning python and was tasked with making a program that flips a coin 100 
times and then tells you
the number of heads and tails.

I have done so coming up with this piece of work but it doesnt run can anyone 
help me out?

#This is credited to dylan

print(" \\ \\ \\ \\ \\ \\ \\ \\ D FLIPS \\ \\ \\ \\ \\ \\ \\ \\")
print("\n\nThis is D's coin flipper program. You get 100 flips. \n\t LETS SEE 
HOW LUCKY YOU ARE")
input("Press enter")

import random

heads = int("1")
tails = int("2")
flips = 100
headscount = 0
tailscount = 0

while flips != 0:
flips -= 1

result = random.randint(heads, tails)
if result = heads:
headscount += 1
else:
tailscount += 1


print(headscount, tailscount)

input("press enter to exit")
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: HTTPserver: how to access variables of a higher class?

2013-04-05 Thread Dylan Evans
On 05/04/2013 9:09 PM, "Tom P"  wrote:
>
> First, here's a sample test program:
> 
> import sys
> from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
>
> class MyRequestHandler(BaseHTTPRequestHandler, object):
> def do_GET(self):
> top_self = super(MyRequestHandler, self) # try to access
MyWebServer instance
> self.send_response(200)
> self.send_header('Content-type','text/html')
> self.end_headers()
> self.wfile.write("thanks for trying, but I'd like to get at
self.foo and self.bar")
> return
>
> class MyWebServer(object):
> def __init__(self):
> self.foo = "foo"  # these are what I want to access from inside
do_GET
> self.bar = "bar"
> self.httpd = HTTPServer(('127.0.0.1', 8000), MyRequestHandler)
> sa = self.httpd.socket.getsockname()
> print "Serving HTTP on", sa[0], "port", sa[1], "..."
>
> def runIt(self):
> self.httpd.serve_forever()
>
> server = MyWebServer()
> server.runIt()
>
> 
>
> I want to access the foo and bar variables from do_GET, but I can't
figure out how. I suppose this is something to do with new-style vs.
old-style classes, but I lost for a solution.

Consider inheriting HTTPServer in MyWebServer which is passed to the
request handler.

> --
> http://mail.python.org/mailman/listinfo/python-list
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Run python script with ./

2013-04-05 Thread Dylan Evans
On Sat, Apr 6, 2013 at 1:04 AM, LubanWorks  wrote:
>
>
>
> My question is:
>
> Why  when I use #!/home/luban/Linux/Python/2.7.3/bin/python at the
> beginning of myscript.py, *./*myscript.py can work,
>
> but if I use the wrapper #!/home/luban/bin/python in my python script, use
> *./*  to run the script, it cannot not work?
>

Your shell will be trying to run your python script. The reason being that
when you do #!/bin/sh in the wrapper the shell tries to execute $0 which in
this case is the name of your python script.


>
>
> I had many scripts used #!/home/luban/bin/python when I only installed
> python  under #!/home/luban/ for Linux, they can run with ./, I don't want
> to change them,
>
> so, how to let ./ run the python script If I want to *KEEP* wrapper
> #!/home/luban/bin/python as the shebang line?
>
>
Probably easier to use a symlink, or just use #!python and adjust your
$PATH.


>
> Best Regards,
> Luban
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>


-- 
"The UNIX system has a command, nice ... in order to be nice to the other
users. Nobody ever uses it." - Andrew S. Tanenbaum
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Trying to understand working with dicts

2013-04-05 Thread Dylan Evans
On Fri, Apr 5, 2013 at 10:34 PM, inshu chauhan wrote:

> Hello everyone,
>
> Here in my part of the code where cc is a dictionary. I want to understand
> what actually cc.iterkeys() and cc[k] actually doing.
> I am already reading
> http://docs.python.org/2/library/stdtypes.html#dict.items
> and http://www.tutorialspoint.com/python/python_dictionary.htm but still
> not very clear.
>
> cc = Computesegclass(segimage, refimage)
> for k in sorted(cc.iterkeys()):
> i = argmax(cc[k])
> print >> f, i+1
>
>
Not sure what Computesegclass is but i am guessing that it is a class which
implements __getitem__ and __setitem__, which allows the use of the square
bracket notation cc[k], you could also write cc.__getitem__(k) , if you
really wanted to.
See http://docs.python.org/2/reference/datamodel.html#object.__getitem__

iterkeys returns an iterator over the dictionary keys, which is an object
with a next method which returns each key in the dictionary until there are
no more, then it raises StopIteration.


> Thanks in Advance
>
>
--
> http://mail.python.org/mailman/listinfo/python-list
>
>


-- 
"The UNIX system has a command, nice ... in order to be nice to the other
users. Nobody ever uses it." - Andrew S. Tanenbaum
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: I hate you all

2013-04-05 Thread Dylan Evans
On Sat, Apr 6, 2013 at 7:41 AM,  wrote:

> Hello
>
> I just tried python 3.3 with some simple script meant for unit test.
>
> How can python authors be so arrogant to impose their tabs and spaces
> options on me ? It should be my choice if I want to use tabs or not !
>
>
Don't like it? Use ruby.



> I know people have all goten into this frenzy of using either tabs, either
> spaces for indentation, but using a hard-tab of 8 spaces and a soft tab of
> 4 spaces has worked fine long before python 3 showed up.
>
> And if they decided to throw a TabError, they should have at least created
> an option to specify tab size, so I can work around that.
>
> I am aware that so many editors use a tab stop of 4 spaces instead of 8
> (which by the way started as a cheap way to work around their initial lack
> of a "soft tab stop" option, and then was kept at 4 for "compatibility").
> But the rest of us who always use a tab stop of 8 should not be forced to
> change preferences because python reached version 3.
>
> Timothy Madden
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
"The UNIX system has a command, nice ... in order to be nice to the other
users. Nobody ever uses it." - Andrew S. Tanenbaum
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: HTTPserver: how to access variables of a higher class?

2013-04-06 Thread Dylan Evans
On Sun, Apr 7, 2013 at 1:05 AM, Tom P  wrote:

> On 04/05/2013 02:27 PM, Dylan Evans wrote:
>
>> On 05/04/2013 9:09 PM, "Tom P"  wrote:
>>
>>>
>>> First, here's a sample test program:
>>> 
>>> import sys
>>> from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
>>>
>>> class MyRequestHandler(**BaseHTTPRequestHandler, object):
>>>  def do_GET(self):
>>>  top_self = super(MyRequestHandler, self) # try to access
>>>
>> MyWebServer instance
>>
>>>  self.send_response(200)
>>>  self.send_header('Content-**type','text/html')
>>>  self.end_headers()
>>>  self.wfile.write("thanks for trying, but I'd like to get at
>>>
>> self.foo and self.bar")
>>
>>>  return
>>>
>>> class MyWebServer(object):
>>>  def __init__(self):
>>>  self.foo = "foo"  # these are what I want to access from inside
>>>
>> do_GET
>>
>>>  self.bar = "bar"
>>>  self.httpd = HTTPServer(('127.0.0.1', 8000), MyRequestHandler)
>>>  sa = self.httpd.socket.getsockname(**)
>>>  print "Serving HTTP on", sa[0], "port", sa[1], "..."
>>>
>>>  def runIt(self):
>>>  self.httpd.serve_forever()
>>>
>>> server = MyWebServer()
>>> server.runIt()
>>>
>>> 
>>>
>>> I want to access the foo and bar variables from do_GET, but I can't
>>>
>> figure out how. I suppose this is something to do with new-style vs.
>> old-style classes, but I lost for a solution.
>>
>> Consider inheriting HTTPServer in MyWebServer which is passed to the
>> request handler.
>>
>>  --
>>> http://mail.python.org/**mailman/listinfo/python-list<http://mail.python.org/mailman/listinfo/python-list>
>>>
>>
>>
> I keep getting the same problem - if inherit from any of these classes in
> BaseHTTPServer and try to use super(class, self) to initiate the higher
> class, I get the error "TypeError: must be type, not classobj" - in other
> words, these are old-style classes.
> That means that in this call -
> self.httpd = MyHTTPServer(('127.0.0.1', 8000), MyRequestHandler)
>
> there doesn't seem to be a way to define a
>  class MyHTTPServer(HTTPServer)
>
>
>
You can call the __init__ method on the class as a workaround for it being
old style. This works on 2.7


from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler

class MyRequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header('Content-type', 'text/plain')
self.end_headers()
self.wfile.write('Got foo? %s' % self.server.foo)


class MyWebServer(HTTPServer):
def __init__(self):
self.foo = 'foo'
HTTPServer.__init__(self, ('127.0.0.1', 8000), MyRequestHandler)
sa = self.socket.getsockname()
print "Serving HTTP on", sa[0], "port", sa[1]

def runit(self):
self.serve_forever()

server = MyWebServer()
server.runit()


>
>
>
> --
> http://mail.python.org/**mailman/listinfo/python-list<http://mail.python.org/mailman/listinfo/python-list>
>



-- 
"The UNIX system has a command, nice ... in order to be nice to the other
users. Nobody ever uses it." - Andrew S. Tanenbaum
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: I hate you all

2013-04-06 Thread Dylan Evans
Then you see my point, unless you are being told what to use by a boss then
there are plenty of other languages you can choose from. Python is rigid
about it's format, that's just what it is and a lot of people like it but
if it's not your thing then some other language will probably suit you
better. However, if you are working for a company, or OSS project, you are
probably going to have your style dictated whatever language you use, for
example the 2 space indents (*shudder*) that google uses in c++
http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml?showone=Spaces_vs._Tabs#Spaces_vs._Tabs
(Interestingly
google use 4 space indents in python for compatibility with PEP-8
http://google-styleguide.googlecode.com/svn/trunk/pyguide.html?showone=Indentation#Indentation
)

You probably won't like everything in a project style but it's not about
being tyrannical, and it's not a bad thing to have restrictions at the
language level.

I work for a company with a load of lagacy c formatted as follows:

int many_many_globals;
int func(int iFoo,int iBar)
{
int var = 10;
if(iBar>1)
{
var=iFoo+many_many_globals;
}
return var;
}

So i am pretty happy to adopt a language which defines a sane style.

This is a nice flame war you have stirred up.



On Sat, Apr 6, 2013 at 3:13 PM,  wrote:

> On Saturday, April 6, 2013 7:28:55 AM UTC+3, Dylan Evans wrote:
> > On Sat, Apr 6, 2013 at 7:41 AM,   wrote:
> >
> > Hello
> >
> >
> > I just tried python 3.3 with some simple script meant for unit test.
> >
> > How can python authors be so arrogant to impose their tabs and spaces
> options on me ? It should be my choice if I want to use tabs or not !
> >
> >
> > Don't like it? Use ruby.
>
>
> Actually next on my list is perl. I know ruby is sexy, but taming the wild
> beast is what makes me feel like the real cowboy.
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
"The UNIX system has a command, nice ... in order to be nice to the other
users. Nobody ever uses it." - Andrew S. Tanenbaum
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: parse the file

2013-04-07 Thread Dylan Evans
You can read the fantastic manual at
http://docs.python.org/2/library/xml.etree.elementtree.html or i'm sure
someone will do it for a modest fee.


On Sat, Apr 6, 2013 at 3:11 PM, 水静流深 <1248283...@qq.com> wrote:

> I have an xml file . http://s.yunio.com/bmCS5h
>
> It is the list of my files in Google-blogger, how can I parse it in python
> to get every article?please give me the right code,which can get exact
> result.
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>


-- 
"The UNIX system has a command, nice ... in order to be nice to the other
users. Nobody ever uses it." - Andrew S. Tanenbaum
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: subprocess question re waiting

2013-04-08 Thread Dylan Evans
On Mon, Apr 8, 2013 at 9:48 PM, Alain Ketterlin  wrote:

> loial  writes:
>
> > I want to call a child process to run a shell script and wait for that
> > script to finish. Will the code below wait for the script to finish?
> > If not then how do I make it wait?
> [...]
> > process = subprocess.Popen(command,
> stdin=subprocess.PIPE,stdout=subprocess.PIPE, stderr=subprocess.PIPE,
> close_fds=True, shell=True)
>
> process.wait()
>

Or use subprocess.call instead which does what you want.


> -- Alain.
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
"The UNIX system has a command, nice ... in order to be nice to the other
users. Nobody ever uses it." - Andrew S. Tanenbaum
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can anyone please help me in resolving the error => AttributeError: Array instance has no attribute '__trunc__'

2013-04-08 Thread Dylan Evans
On Mon, Apr 8, 2013 at 8:07 PM,  wrote:

> I am trying to create 2D arrays without using advanced features like
> numpy, for this I have created 2 separate modules arrays.py and array2D.py.
> Here's the code for that:
>
> arrays.py module:
> ==
> import ctypes
>
> class Array:
>
> #Creates an array with size elements.
> def __init__( self, size ):
> assert size > 0, "Array size must be > 0"
> self._size = size
> print "sixe is %s" %self._size
>
>  # Create the array structure using the ctypes module.
> PyArrayType = ctypes.c_int * size
> self._elements = PyArrayType()
> print "type is e", type(self._elements)
> #self._elements = ctypes.c_int * size
>
> print "Elements are self.element %s" % self._elements
> # Initialize each element.
> #for i in range(self._size):
> #   self.clear( i )
>
>
> # Returns the size of the array.
> def __len__( self ):
> return self._size
>
> # Gets the contents of the index element.
> def __getitem__( self, index ):
> assert index >= 0 and index < len(self), "Array subscript out of
> range"
> return self._elements[ index ]
>
> # Puts the value in the array element at index position.
> def __setitem__( self, index, value ):
> assert index >= 0 and index < len(self), "Array subscript out of
> range"
> print "Type is ", type(index)
> self._elements[ index ] = value
>
> # Clears the array by setting each element to the given value.
> def clear( self, value ):
> for i in range( len(self) ) :
> self._elements[i] = value
>
> # Printing the arrays:
> def __str__(self):
> return self._elements
>
>
>
> array2D.py module
> ==
>
>
> import arrays
>
> class Array2D :
> # Creates a 2-D array of size numRows x numCols.
> def __init__( self, numRows, numCols ):
> # Create a 1-D array to store an array reference for each row.
>
> self._theRows = arrays.Array( numRows )
> # Create the 1-D arrays for each row of the 2-D array.
> print "Num of Cloumns is", numCols
>
> for i in range( numRows ) :
> self._theRows[i] = arrays.Array( numCols )
>
> # Returns the number of rows in the 2-D array.
> def numRows( self ):
> return len( self._theRows )
>
> # Returns the number of columns in the 2-D array.
> def numCols( self ):
> return len( self._theRows[0] )
>
> # Clears the array by setting every element to the given value.
> def clear( self, value ):
> for row in range( self.numRows() ):
> row.clear( value )
>
> # Gets the contents of the element at position [i, j]
> def __getitem__( self, ndxTuple ):
> assert len(ndxTuple) == 2, "Invalid number of array subscripts."
> row = ndxTuple[0]
> col = ndxTuple[1]
> assert row >= 0 and row < self.numRows() \
> and col >= 0 and col < self.numCols(), \
> "Array subscript out of range."
> the1dArray = self._theRows[row]
> return the1dArray[col]
>
> # Sets the contents of the element at position [i,j] to value.
> def __setitem__( self, ndxTuple, value ):
> #assert len(ndxTuple) == 3, "Invalid number of array subscripts."
> row = ndxTuple[0]
> col = ndxTuple[1]
> assert row >= 0 and row < self.numRows() \
> and col >= 0 and col < self.numCols(), \
> "Array subscript out of range."
> the1dArray = self._theRows[row]
> the1dArray[col] = value
>
>
> arr = Array2D(2,4)
>
> print "arr is %s" %arr
>
>
> Traceback is :
>
> sixe is 2
> type is e 
> Elements are self.element 
> Cols in 4
> Num of Cloumns is 4
> !! i is 0
> sixe is 4
> type is e 
> Elements are self.element 
> Type is  
> Traceback (most recent call last):
>   File "C:\Python27\Lib\array2D.py", line 53, in 
> arr = Array2D(2,4)
>   File "C:\Python27\Lib\array2D.py", line 16, in __init__
> self._theRows[i] = arrays.Array( numCols )
>   File "C:\Python27\Lib\arrays.py", line 36, in __setitem__
> self._elements[ index ] = value
> AttributeError: Array instance has no attribute '__trunc__'
> --
> http://mail.python.org/mailman/listinfo/python-list
>


Not sure about the __trunc__ problem but i can suggest this alternative
which is a bit simpler

def array2D(x, y, val=None):
return [[val for col in xrange(x)] for row in xrange(y)]


-- 
"The UNIX system has a command, nice ... in order to be nice to the other
users. Nobody ever uses it." - Andrew S. Tanenbaum
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: subprocess question re waiting

2013-04-08 Thread Dylan Evans
On Mon, Apr 8, 2013 at 10:22 PM, Dave Angel  wrote:

> On 04/08/2013 08:01 AM, Dylan Evans wrote:
>
>> On Mon, Apr 8, 2013 at 9:48 PM, Alain Ketterlin <
>> al...@dpt-info.u-strasbg.fr
>>
>>> wrote:
>>>
>>
>>  loial  writes:
>>>
>>>  I want to call a child process to run a shell script and wait for that
>>>> script to finish. Will the code below wait for the script to finish?
>>>> If not then how do I make it wait?
>>>>
>>> [...]
>>>
>>>> process = subprocess.Popen(command,
>>>>
>>> stdin=subprocess.PIPE,stdout=**subprocess.PIPE, stderr=subprocess.PIPE,
>>> close_fds=True, shell=True)
>>>
>>> process.wait()
>>>
>>>
>> Or use subprocess.call instead which does what you want.
>>
>>
Actually after having a look through the manual i like check_output for
this since it simplifies the code, but some extra exception handling would
be required if the output is still required when the script exits with a
non zero value, so it's a bit of a trade off.


>  -- Alain.
>>> --
>>> http://mail.python.org/**mailman/listinfo/python-list<http://mail.python.org/mailman/listinfo/python-list>
>>>
>>>
>>
> http://docs.python.org/2/**library/subprocess.html#popen-**objects<http://docs.python.org/2/library/subprocess.html#popen-objects>
>
> or use communicate(), which is what the OP had in the first place.
>
>
> --
> DaveA
> --
> http://mail.python.org/**mailman/listinfo/python-list<http://mail.python.org/mailman/listinfo/python-list>
>



-- 
"The UNIX system has a command, nice ... in order to be nice to the other
users. Nobody ever uses it." - Andrew S. Tanenbaum
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: is "_io.py" missing from 2.7.4 ?

2013-04-08 Thread Dylan Evans
On Mon, Apr 8, 2013 at 11:12 PM, dbv  wrote:

> In 2.7.4, io.py shows:
>
> import _io
> import abc
>
> from _io import (DEFAULT_BUFFER_SIZE, BlockingIOError,
> UnsupportedOperation,
>  open, FileIO, BytesIO, StringIO, BufferedReader,
>  BufferedWriter, BufferedRWPair, BufferedRandom,
>  IncrementalNewlineDecoder, TextIOWrapper)
>
> but, cannot find _io.py, though there is the old _pyio.py in the
> //Python27//Lib folder.
>
> >>> _io.__file__
'/usr/lib/python2.7/lib-dynload/_io.so'

Looks like it's implemented in C.



> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
"The UNIX system has a command, nice ... in order to be nice to the other
users. Nobody ever uses it." - Andrew S. Tanenbaum
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: USBLock : lock/unlock your computer with a USB key

2013-04-11 Thread Dylan Evans
This looks cool, would actual be pretty useful. I see you did it as a usb
project but probably bluetooth would be better so you could just pair it to
your phone and know that your PC will lock when you walk away.



On Tue, Apr 9, 2013 at 1:21 AM, Sven  wrote:

> I've been working on a little project and have a working Linux
> implementation so far. Basically it allows a user to use any USB stick as a
> key to lock and unlock their computer. More info in the repo or PyPi
> https://pypi.python.org/pypi/USBLock
>
> Basically run the program with -a to add a device (added once you insert
> it), then run it without any arguments. Insert the key again, and when you
> remove it your computer will lock. Insert the key again and it will unlock.
> It's not intended to provide military grade security, it's more of a
> convenience tool to launch built in screen locking software.
>
> Currently it locks a Linux box with xlock, pending a better solution.
>
> I wrote it as an exercise in playing around with USB media and events, and
> also because I needed a use for these old USB keys I have lying around :)
>
> Always looking for contributions, suggestions and improvements. Especially
> OS X and Win support.
>
> Repo:
> https://github.com/Svenito/usblock
>
> Thanks for your time.
>
> --
> ./Sven
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>


-- 
"The UNIX system has a command, nice ... in order to be nice to the other
users. Nobody ever uses it." - Andrew S. Tanenbaum
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: USBLock : lock/unlock your computer with a USB key

2013-04-12 Thread Dylan Evans
On Fri, Apr 12, 2013 at 6:16 AM, Ian Kelly  wrote:

> On Thu, Apr 11, 2013 at 9:23 AM, Ethan Furman  wrote:
> > On 04/11/2013 04:13 AM, Sven wrote:
> >>
> >> Yes, I had the idea to add bluetooth too, removes the whole plugging and
> >> unplugging spiel. I might start work on that,
> >> and if anyone else wants to dive in and help, feel free. I will probably
> >> need to refactor the Listener a little, or
> >> create a USB and BT listener class.
> >
> >
> > Doesn't BlueTooth have a 30 foot range?  For locking I'd rather be at 10
> or
> > even 5 feet away.
>
>
I guess it depends on your needs, I'd want it locked when i wander out of
the office.


> Pair it with a Google Glass and have it lock after you've stopped
> looking at the screen for 30 seconds.
>

That would be awesome.


> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
"The UNIX system has a command, nice ... in order to be nice to the other
users. Nobody ever uses it." - Andrew S. Tanenbaum
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newline at EOF Removal

2006-01-09 Thread Dylan Wilson
Do you mean somthing like this?

>>> f = open("file.txt")
>>> w = open('outfile.txt', 'w')
>>> for line in f.split('\n'):
...w.write(line)
...
>>> w.close()
>>> '\n' in open('/home/wandleg/outfile.txt').read()
False

-- 
http://mail.python.org/mailman/listinfo/python-list


A __getattr__ for class methods?

2006-02-08 Thread Dylan Moreland
I'm trying to implement a bunch of class methods in an ORM object in
order to provide functionality similar to Rails' ActiveRecord. This
means that if I have an SQL table mapped to the class "Person" with
columns name, city, and email, I can have class methods such as:

Person.find_by_name
Person.find_by_city_and_name
Person.find_by_name_and_city_and_email

I have a metaclass generating basic properties such as .name and .city,
but I don't want to generate a class method for every permutation of
the attributes. I'd like to have something much like __getattr__ for
instance attributes, so that if a method like
Person.find_by_city_and_email cannot be found, I can construct a call
to the basic find method that hides the SQL. Is there any way of doing
this, or am I trying to mirror a functionality that Python simply does
not have?

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A __getattr__ for class methods?

2006-02-08 Thread Dylan Moreland
Michael Spencer wrote:
> Dylan Moreland wrote:
> > I'm trying to implement a bunch of class methods in an ORM object in
> > order to provide functionality similar to Rails' ActiveRecord. This
> > means that if I have an SQL table mapped to the class "Person" with
> > columns name, city, and email, I can have class methods such as:
> >
> > Person.find_by_name
> > Person.find_by_city_and_name
> > Person.find_by_name_and_city_and_email
> >
> > I have a metaclass generating basic properties such as .name and .city,
> > but I don't want to generate a class method for every permutation of
> > the attributes. I'd like to have something much like __getattr__ for
> > instance attributes, so that if a method like
> > Person.find_by_city_and_email cannot be found, I can construct a call
> > to the basic find method that hides the SQL. Is there any way of doing
> > this, ...
>
> Sure, define __getattr__ on the type of the class i.e., the metaclass, just as
> you define it on a class to provide default-attribute-lookup to its instances:
>
>   >>> class A(object):
>   ... class __metaclass__(type):
>   ... def __getattr__(cls, attr):
>   ... return "%s.%s" % (cls.__name__, attr)
>   ...
>   >>> A.somefunc
>   'A.somefunc'
>   >>> A.someotherfunc
>   'A.someotherfunc'
>   >>>
>
> HTH
>
> Michael

Thanks! I only recently realized that I would have to learn metaclasses
in order to make this work, and I'm still a bit unclear on their
properties.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What editor shall I use?

2006-02-08 Thread Dylan Moreland

Radek Kubicek wrote:
> > What editor shall I use if my Python script must contain utf-8
> > characters?
> > I use XP
>
> vim :-)
>
> > Thank you for reply
> > l.b.
>
> not for all :-)

I myself have just begun using vim. Does anyone have any
tips/convenient tweaks for python programming with it?

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to remove using replace function?

2006-02-08 Thread Dylan Moreland
I think you want to use the replace method of the string instance.
Something like this will work:

# See http://docs.python.org/lib/string-methods.html#l2h-196
txt = "an unfortunate  in the middle"
txt = txt.replace("", "")

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to remove using replace function?

2006-02-08 Thread Dylan Moreland

[EMAIL PROTECTED] wrote:
> nope didn't work

Could you be more specific about the error? Both my example and yours
work perfectly on my box.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie Q: dynamically assigning object attribute

2006-02-09 Thread Dylan Moreland
Take a look at the built-in function setattr:

http://ftp.python.org/doc/lib/built-in-funcs.html#l2h-64

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie Q: dynamically assigning object attribute

2006-02-09 Thread Dylan Moreland
No problem. There are, in fact, ugly class-based methods of doing this.
You could assign to an instance's __dict__ dictionary, or -- if the
class is a new-style class -- you can call the __setattr__(self, name,
value) method.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Splitting a string

2006-02-14 Thread Dylan Moreland
Take a look at:

http://docs.python.org/lib/node115.html#l2h-878

So I would try something like:

pat = re.compile(r" (?:AND|OR|AND NOT) ")
pat.split(string)

Compile the regular expression with re.IGNORECASE if you like.

Nico Grubert wrote:
> Dear Python users,
>
> I'd like to split a string where 'and', 'or', 'and not' occurs.
>
> Example string:
> s = 'Smith, R. OR White OR Blue, T. AND Black AND Red AND NOT Green'
>
> I need to split s in order to get this list:
> ['Smith, R.', 'White', 'Blue, T.', 'Back', 'Red', 'Green']
>
> Any idea, how I can split a string where 'and', 'or', 'and not' occurs?
> 
> 
> Thank you very much in advance,
> Nico

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Splitting a string

2006-02-14 Thread Dylan Moreland
Woops! Thanks for the correction. I was assuming greediness for some
reason.

Fredrik Lundh wrote:
> Dylan Moreland wrote:
>
> > So I would try something like:
> >
> > pat = re.compile(r" (?:AND|OR|AND NOT) ")
> > pat.split(string)
>
> footnote: this yields:
>
> ['Smith, R.', 'White', 'Blue, T.', 'Black', 'Red', 'NOT Green']
>
> (the | operator picks the first (leftmost) alternative that results in an
> overall match.)
> 
> 

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to write a C-style for loop?

2006-02-14 Thread Dylan Moreland

John Salerno wrote:
> I assume this is the way for loops are written in C, but if it helps to
> be specific, I'm referring to C# for loops. The Python for loop seems to
> be the same (or similar) to C#'s foreach loop:
>
> foreach int i in X
>
> But how would you write a C# for loop in Python? Do you rework a while
> loop, or use the range() function?
>
> Here's an example:
>
> for (int i = 0; i < 50; i += 5)
>
> How would that go in Python, in the simplest and most efficient way?
>
> Thanks.

Take a look at the range() builtin. That should give you what you need.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pop line from file

2006-02-15 Thread Dylan Wilson
Try open.readline()

>>>help(open)
...

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: looping over more than one list

2006-02-16 Thread Dylan Moreland
> def lowest(s1,s2):
> s = ""
> for c1,c2 in [x for x in zip(s1,s2)]:
> s += lowerChar(c1,c2)
> return s
>
> but it's hardly any more elegant than using a loop counter, and I'm
> guessing it's performance is a lot worse - I assume that the zip
> operation is extra work?
>
> Iain

Always look in itertools for stuff like this:

http://docs.python.org/lib/itertools-functions.html#l2h-1392

for c1, c2 in itertools.izip(s1, s2):
...

I haven't profiled it, but it makes sense that this would be fast.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: general coding issues - coding style...

2006-02-18 Thread Dylan Moreland

calmar wrote:
> On 2006-02-18, Diez B. Roggisch <[EMAIL PROTECTED]> wrote:
> >   - why are these {{{ thingies there?
>
> markers for folding for vim
> http://www.calmar.ws/tmp/sc.png

I would look into one of the many Vim scripts which automatically fold
most large blocks without the ugly {{{.

-- 
http://mail.python.org/mailman/listinfo/python-list


How to best return a string from C to CPython 2.5?

2008-10-06 Thread dylan . fun
I'm trying to return a Python string from a C++ function (actually
inside gnuradio) using CPython 2.5. My C++ function is declared like:

typedef struct {
  int size;
  unsigned char *data;
} STRING

STRINGBUF myfunc(std::string s)
{
  STRINGBUF buf;
  .
  .
  .
  buf.size = s.length();
  buf.data = s.data();
  return buf;
}

Since gnuradio uses SWIG, I found a SWIG example that seemed to fit:

%typemap(myfunc) STRINGBUF {
  $result = PyString_FromStringAndSize($1.data, $1.size);
}

STRINGBUF myfunc(std::string s);

At runtime though, I'm getting a type mismatch error from Python
(PyObject of some type found when PyString was expected - I can post
the exact message tomorrow if it'll help.)

Any ideas or suggestions appreciated!
--
http://mail.python.org/mailman/listinfo/python-list


file()

2008-07-18 Thread Dylan Wilson
well, I'm in the beginings of making a random sentence generator for a mod my 
friend makes, but I want the nouns, verbs pastverbs, etc. to be easily 
customizable by editing a file, but, last night file() worked fine and today 
it's saying " line 1: `read_who = file('who.ini', 'r')'"

here's what I have so far, but for reference it's possible I'm just being an 
idiot because I'm very new to Python and programming in general



read_who = file('who.ini', 'r')
who = read_who.read()

read_what = file('what.ini', 'r')
what = read_what.read()

read_end = file('end.ini', 'r')
end = read_end.read()

read_because = file('because.ini', 'r')
because = read_because.read()

read_the = file('the.ini', 'r')
da = read_the.read()

read_period = file('punc.ini', 'r')
period = read_period.read()
prd = read_period.read()

read_nouns = file('nouns.ini', 'r')
nouns = read_nouns.read()

read_verbs = file('verbs.ini', 'r')
verbs = read_verbs.read()

read_pastverbs = file('pastverbs.ini', 'r')
pastverbs = read_pastverbs.read()



  --
http://mail.python.org/mailman/listinfo/python-list

Re: Getting a list of all classes derived from a base class

2006-04-02 Thread Dylan Moreland
Vijairaj  R wrote:
> Hi,
> I have a requirement to findout all the classes that are derived from a
> single base class.
>
> This is how I do it currently.
>
> class Test:
> case = []
>
> class Test1(Test):
> Test.case.append("Test1")
>
> class Test2(Test):
> Test.case.append("Test2")
>
> 1. Is there a better way of doing this.
> 2. Is there a way to generalize the Test.case.append("TestN")
> statements to something like
> Test.case.append(__myclass__)
>
> --
> Warm Regards,
> Vijairaj

If you're willing to use metaclass madness:

class TestMeta(type):
def __init__(cls, name, bases, dct):
if bases == (object,): return # Prevent the appending of Test
cls.case.append(cls)

class Test(object):
__metaclass__ = TestMeta
case = []

class Test1(Test): pass
class Test2(Test): pass

print Test.case

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Getting a list of all classes derived from a base class

2006-04-03 Thread Dylan Moreland
Alex Martelli wrote:
> Vijairaj  R <[EMAIL PROTECTED]> wrote:
>...
> > class Test:
>
> do not use old-style classes: they exist ONLY for backwards
> compatibility.
>
> Make you class Test new-style:
>
> class Test(object):
>...
>
>
> and you can call Test.__subclasses__() to get a list of all extant
> subclassed of Test at any time.
>
>
> Alex

Thanks Alex. That's a new one to me -- new-style classes have so many
strange properties.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: - Removing Need For Repeated Definition of __str__

2006-04-03 Thread Dylan Moreland
Ilias Lazaridis wrote:
> I have some python code which looks similar to this:
>
> class Car(BaseClass) :
>manufacturer = factory.string()
>model = factory.string()
>modelYear = factory.integer()
>
>def __str__(self):
>return '%s %s %s' % (self.modelYear, self.manufacturer,
> self.model)
>
> def factory.string(self)
>   s = String() # creates a string object
>   #... # does several things
>   return s # returns the string object
>
> -
>
> I would like to simplify it in this way:
>
> class Car(BaseClass):
>manufacturer = factory.string(2)  # 2 = position number...
>model = factory.string(3) # ...withinn __str__
>modelYear = factory.integer(1)
>
> def factory.string(self, position)
>   s = String() # creates a string object
>   ...  # does several things
>
   # creates somehow the __str__ functionality...
>
>   return s # returns the string object
>
> -
>
> How could I achieve this?
>
> .
>

I'm slightly confused about your use of factory functions for making
instance variables (perhaps you could explain that?). Without knowing
more about that, here's a mixin solution I've used in the past (note
that __strdef__ is something I just made up):

class SmartStr(object):

def __str__(self):
return "<%s %s>" % (self.__class__.__name__,
", ".join(attrname + "=" + str(getattr(self, attrname))
  for attrname in self.__strdef__))

class Car(SmartStr):

__strdef__ = ["model_year", "manufacturer", "model"]

def __init__(self, manufacturer, model, model_year):
self.manufacturer = manufacturer
self.model = model
self.model_year = model_year

c = Car("Toyota", "Camry", 1990)
print c # => 

-- 
http://mail.python.org/mailman/listinfo/python-list


FW: IDE+hg

2009-11-30 Thread Dylan Palmboom
From: NiklasRTZ [mailto:nikla...@gmail.com] 
Sent: 26 November 2009 12:38 PM
To: python-list@python.org
Subject: Re: IDE+hg

On Nov 25, 7:28 am, alex23  wrote:
> NiklasRTZ  wrote:
> > no py IDE I found has easy hg access.
>
> ActiveState's Komodo IDE has support for CVS, Perforce, subversion, 
> bazaar, git and mercurial.

unavailable via synaptic ubuntu karmic repos, presuming its commercially
bound like wing. Boa constructor, PIDA, Eric, drPython are 4 where all
should be configurable for obvious reasons + I like it.
thanks for anyway prompt reply my friend

Eclipse with PyDev and SVN Team Provider works very well too.

-- 
http://mail.python.org/mailman/listinfo/python-list


Graphical nodes

2009-10-06 Thread Dylan Palmboom
Hi everyone
 
Please could someone tell me of any libraries that you could use to make use
of graphical nodes in python.
Each node would hold data and properties.
I am trying to achieve a similar effect, as in the application spoken about
below.
If you have seen an application called Nuke, by the foundry, you will see
what I mean. It uses graphical nodes
such as rectangles etc (similar to UML) to link operations on images
together with arrows etc.
I know that Nuke is made using the Qt toolkit, so maybe someone could tell
me what classes were probably used
to make this node based interface. Maybe the QGraphicsItem and
QGraphicsScene classes? It looks cool
so if anyone has any ideas on how to do something like this, it would be
great.
 
Thanks
-- 
http://mail.python.org/mailman/listinfo/python-list


Colour sampling

2009-10-15 Thread Dylan Palmboom
Does anyone know what python libraries are available to do the following:
 
1. I would like to take a photograph of an object with a colour. In this
case, it is a sheet of sponge.
2. Feed this image into a function in a python library and let the function
"automatically scan" this image's
pixel colours, and return an average of all the pixels' colours in the
image.
3. I could then use the rgb values to set a colour swatch for the object's
colour.
 
Please let me know if you have any ideas. It would be appreciated.
In the meantime, I will search Google and see what I can find.
 
Thanks
 
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: Python GUI

2009-10-25 Thread Dylan Palmboom
 PyQt is what we use at work and it is excellent and easy to learn too! I
definitely recommend it.


-Original Message-
From: Philip Semanchuk [mailto:phi...@semanchuk.com] 
Sent: 26 October 2009 03:42 AM
To: Python-list (General)
Subject: Re: Python GUI


On Oct 25, 2009, at 8:39 PM, Ronn Ross wrote:

> I need to create a gui for python. I'm looking for something that is 
> easy to learn and cross platform. Any suggestions? If you have any 
> good tutorials please send along. Thanks in advance.

wxPython (which wraps wxWidgets) is popular and IMO reasonably well laid
out. I hear great things about PyQt (which wraps QT) but I haven't used it.
PySide is a new wrapper for QT that has generated a lot of excitement but is
still its infancy, I think.


HTH
Philip



-- 
http://mail.python.org/mailman/listinfo/python-list


Choosing GUI Module for Python

2009-11-13 Thread Dylan Palmboom
-Original Message-
From: catalinf...@gmail.com [mailto:catalinf...@gmail.com] 
Sent: 13 November 2009 10:06 AM
To: python-list@python.org
Subject: Re: Choosing GUI Module for Python

Tkinter is deafult on python .
Is more easy to use any editor text (geany).
I don?t see a good IDE for GUI
On Nov 9, 6:49 am, Antony  wrote:
> Hi all
>    I just wanted to know which module is best for developing designing 
> interface in python .
> i have come across some modules which are listed here . please tell 
> your suggestions and comments to choose best one
>  1. PyGTK
>  2. PyQT
>  3. PySide
>  4.  wxPython
>  5 . TKinter
>
> Also i need to know is there any IDE for developing these things . . .


PyQt is an excellent toolkit for us at work. It has nice documentation and
very easy to learn.
We use Eclipse IDE at work with the PyDev workspace loaded for the coding.
Eclipse has nice features for integration with subversion all from one
place,
so it makes it more manageable when you have more than 1 person working on a
project.
There's only 2 of us here working together, but the subversion integration
makes
our lives so much easier.

We use eclipse for gui design in code or we use Qt Creator which is very
intuitive to use if you want to design a gui visually. Also, there's a
python script we use
called MakePyQt that you can find here: http://www.qtrac.eu/pyqtbook.tar.gz
to convert the ui files from
Qt Creator to python files. Then all you need to do is implement these
generated python
files in your program and add functionality etc.

-- 
http://mail.python.org/mailman/listinfo/python-list


IDLE won't start on Mac OSX

2010-07-15 Thread Dylan Gleason
Hello, 

My name is Dylan. I am new to this list and am just getting started with Python 
and programming in general (although I have some experience with general UNIX 
wankery).

I am trying to fire up Python ver. 2.7 with IDLE (I am using Mac OSX 10.6.3), 
but it will not start, citing the following error message:

>>> IDLE's subprocess didn't make connection. Either IDLE can't start 
>>> subprocess or 
>>>personal firewall software is blocking the connection.

I tried disabling my firewall and restarting but unfortunately I still get the 
same message.

I executed Python via the command line and it seemed to work just fine. Can 
someone help me??

Thanks,
Dylan


  -- 
http://mail.python.org/mailman/listinfo/python-list


Mail Merge from python data

2010-11-02 Thread Dylan Evans
I'm setting up a database for an organisation who want to do mail merges in
office 2010. I know i can use the MySQL ODBC driver for the mail merge but i
have set up the database with lots of relations and many-to-many links which
i'm sure will lead to a huge amount of confusion (I think, i don't really
know much about mail merge).

What i want to know is, is there anyway to send data from python, which the
UI is written in, to office templates and mail merges?

-- 
"The UNIX system has a command, nice ... in order to be nice to the other
users. Nobody ever uses it." - Andrew S. Tanenbaum
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Mail Merge from python data

2010-11-03 Thread Dylan Evans
On Wed, Nov 3, 2010 at 3:20 PM, Tim Harig  wrote:

> This page didn't make it to through to my nntp server so I appologize if I
> miss something that was covered.
>
> On 2010-11-03, Dennis Lee Bieber  wrote:
> > On Tue, 2 Nov 2010 20:32:13 +1000, Dylan Evans 
> > declaimed the following in gmane.comp.python.general:
> >
> >> I'm setting up a database for an organisation who want to do mail merges
> in
> >> office 2010. I know i can use the MySQL ODBC driver for the mail merge
> but i
> >> have set up the database with lots of relations and many-to-many links
> which
> >> i'm sure will lead to a huge amount of confusion (I think, i don't
> really
> >> know much about mail merge).
>
> Many to many relationships without some kind of intersection table are
> considered a rather poor practice in general.


Yes an intersection table with a description char field.

>
> >> What i want to know is, is there anyway to send data from python, which
> the
> >> UI is written in, to office templates and mail merges?
> >
> >   If a long lived form, I'd probably define a query or view (I think
> > MySQL 5.x has output-only views) that isolates just to the data fields
> > used in the mail merge.
>
> I agree that a view would be the best solution if you have the access to do
> so; but, a couple of other alternatives come to mind in case you do not.
>
> That would help alot, it would certainly make it easier for then, i didn't
know about views, i will rtfm.


> 1. Do the mail merge in Python using a Word template.  Then you can add any
>kind of logic that you need to the merge.
>
> Can this be done in pure python? Bearing in mind that the server will be
linux


> 2. Add some kind of export function to your python UI that allows you to
>export the data to an Excel sheet, CSV, or even another ODBC data
>source (like another MySQL table or database that you might have
>access to).
>

I have considered this one, ideally the file saving would be skipped, since
it's only temporary and i am concerned that users may save many files mixing
them up, or try to use old export files which are out of sync with the
database. This is a community organisation with volunteers, so i expect
technical competency to be low. However if i can send the data directly from
python to office somehow i could avoid that issue. What would be perfect is
an ODBC driver which connected via XMLRPC or some other simple protocol.

Thanks for the help.

--
>
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
"The UNIX system has a command, nice ... in order to be nice to the other
users. Nobody ever uses it." - Andrew S. Tanenbaum



-- 
"The UNIX system has a command, nice ... in order to be nice to the other
users. Nobody ever uses it." - Andrew S. Tanenbaum
-- 
http://mail.python.org/mailman/listinfo/python-list