Re: python backup script
In <[email protected]> [email protected] writes: > > cmd2 = subprocess.Popen(['gzip' '-c'], > > > > shell=False, > > > > stdout=filename > > > > stdin=cmd1.stdout) > Thank you Enrico. I've just tried your script and got this error: > stdin=cmd1.stdout) > ^ > SyntaxError: invalid syntax Looks like you need a comma after 'stdout=filename'. -- John Gordon A is for Amy, who fell down the stairs [email protected] B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: Get filename using filefialog.askfilename
In [email protected] writes: > print(file) > the output is: <..name="file.doc"...mode=..encoding.. > > How can i get the second member of 'file'? If you're using the interpreter, you can type this command: >>> help(file) And it will display documentation for using objects of that type. You can also use this command: >>> dir(file) And it will display all the members and methods that the object provides. -- John Gordon A is for Amy, who fell down the stairs [email protected] B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: @staticmethods called more than once
In <[email protected]> Christian writes: > Hi, > i'm somewhat confused working with @staticmethods. My logger and > configuration methods are called n times, but I have only one call. > n is number of classes which import the loger and configuration class > in the subfolder mymodule. What might be my mistake mistake? > Many thanks > Christian > ### __init__.py ### > from mymodule.MyLogger import MyLogger > from mymodule.MyConfig import MyConfig > # my_test.py ## > from mymodule import MyConfig,MyLogger > #Both methods are static > key,logfile,loglevel = MyConfig().get_config('Logging') > log = MyLogger.set_logger(key,logfile,loglevel) > log.critical(time.time()) > #Output > 2013-05-21 17:20:37,192 - my_test - 17 - CRITICAL - 1369149637.19 > 2013-05-21 17:20:37,192 - my_test - 17 - CRITICAL - 1369149637.19 > 2013-05-21 17:20:37,192 - my_test - 17 - CRITICAL - 1369149637.19 > 2013-05-21 17:20:37,192 - my_test - 17 - CRITICAL - 1369149637.19 You haven't given us the code for your MyLogger class, so it's difficult to say exactly what the problem is. However, I have a guess. Does MyLogger.set_logger() contain a call to addHandler()? Each call to addHandler() adds another handler to your logger, and when you call log.critical() [or any other log function] you get one line of output for each handler. You should only call addHandler() once. -- John Gordon A is for Amy, who fell down the stairs [email protected] B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: @staticmethods called more than once
In John Gordon writes: > You should only call addHandler() once. ...for each intended logging output destination, of course. If you want logging output to appear in a file and on-screen, then you would call addHandler() once with a file handler and once with a screen handler. But I think you may be calling addHandler multiple times for the same file handler, which is causing the duplicate logging output. -- John Gordon A is for Amy, who fell down the stairs [email protected] B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: lstrip problem - beginner question
In <[email protected]> mstagliamonte writes: > Hi everyone, > I am a beginner in python and trying to find my way through... :) > I am writing a script to get numbers from the headers of a text file. > If the header is something like: > h01 = ('>scaffold_1') > I just use: > h01.lstrip('>scaffold_') > and this returns me '1' > But, if the header is: > h02: ('>contig-100_0') > if I use: > h02.lstrip('>contig-100_') > this returns me with: '' > ...basically nothing. What surprises me is that if I do in this other way: > h02b = h02.lstrip('>contig-100') > I get h02b = ('_1') > and subsequently: > h02b.lstrip('_') > returns me with: '1' which is what I wanted! > Why is this happening? What am I missing? It's happening because the argument you pass to lstrip() isn't an exact string to be removed; it's a set of individual characters, all of which will be stripped out. So, when you make this call: h02.lstrip('>contig-100_') You're telling python to remove all of the characters in '>contig-100_' from the base string, which leaves nothing remaining. The reason it "worked" on your first example was that the character '1' didn't occur in your sample header string 'scaffold_'. If the underscore character is always the separating point in your headers, a better way might be to use the split() method instead of lstrip(). -- John Gordon A is for Amy, who fell down the stairs [email protected] B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: How to increment date by week?
In PieGuy
writes:
>Starting on any day/date, I would like to create a one year list, by week
> (start date could be any day of week). Having a numerical week index in
> front of date, ie 1-52, would be a bonus.
>ie, 1. 6/4/2013
>2. 6/11/2013
>3. 6/18/2013etc to # 52.
>And to save that result to a file.
>Moving from 2.7 to 3.3
> TIA
from datetime import date, timedelta
the_date = date(year=2013, month=6, day=4)
print "%d. %s" % (1, the_date)
for n in range(2, 53):
the_date = the_date + timedelta(days=7)
print "%d. %s" % (n, the_date)
--
John Gordon A is for Amy, who fell down the stairs
[email protected] B is for Basil, assaulted by bears
-- Edward Gorey, "The Gashlycrumb Tinies"
--
http://mail.python.org/mailman/listinfo/python-list
Re: Errin when executing a cgi script that sets a cookie in the browser
In <[email protected]> =?ISO-8859-7?B?zenq/Ovh7/Igyu/98eHy?= writes: > 'python files.py' interprets without an error. > Problem is that when via browser - http://superhost.gr/cgi-bin/koukos.py > i receive the following: Why should 'files.py' have any relation to 'koukous.py'? > What file does the error complain it cannot find? I do not understand its > message. Here is the code of koukos.py > - > #!/usr/bin/python Does /usr/bin/python exist? Scripts can throw a 'No such file or directory' or 'Command not found' error if they begin with a shebang line which refers to a nonexistent program. -- John Gordon A is for Amy, who fell down the stairs [email protected] B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: Having a hard time to 'get' bing api search results
In "Yves S. Garret" writes: > Hello all, > This is my dilemma, I'm trying to get the generated JSON file using the > bing api search. > This is the code that I'm executing from inside the shell: > http://bin.cakephp.org/view/460660617 > The port doesn't matter to me. Thoughts? It looks like the code is mistakenly interpreting 'user:A' as a port specifier instead of a username and password. Can you supply the credentials another way, perhaps in a header? -- John Gordon A is for Amy, who fell down the stairs [email protected] B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: Natural Language Processing with Python .dispersion_plot returns nothing
In <[email protected]> sixtyfourbit writes: > When I load all of the necessary modules and try to create the dispersion > plott, I get no return - no plot, no error message, not even a new >>> > prompt, just a blinking cursor under the last line I typed. How long did you wait for results before interrupting the command? How large is text4? It might just take a while to process. -- John Gordon A is for Amy, who fell down the stairs [email protected] B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: Updating a filename's counter value failed each time
In Simpleton writes:
> Hello again, something simple this time:
> After a user selects a file from the form, that sleection of his can be
> found form reading the variable 'filename'
> If the filename already exists in to the database i want to update its
> counter and that is what i'm trying to accomplish by:
> ---
> if form.getvalue('filename'):
> cur.execute('''UPDATE files SET hits = hits + 1, host = %s, lastvisit =
> %s WHERE url = %s''', (host, lastvisit, filename) )
> ---
> For some reason this never return any data, because for troubleshooting
> i have tried:
> -
> data = cur.fetchone()
> if data:
> print("something been returned out of this"_
>
An UPDATE statement isn't a query. There are no results to be fetched.
If you want to get results, execute a query (usually a SELECT.)
Also, that print statement is an obvious syntax error. Please post
the actual code you're running; don't type it in from memory.
--
John Gordon A is for Amy, who fell down the stairs
[email protected] B is for Basil, assaulted by bears
-- Edward Gorey, "The Gashlycrumb Tinies"
--
http://mail.python.org/mailman/listinfo/python-list
Re: Updating a filename's counter value failed each time
In Simpleton writes:
> if form.getvalue('filename'):
> cur.execute('''UPDATE files SET hits = hits + 1, host = %s, lastvisit =
> %s WHERE url = %s''', (host, lastvisit, filename) )
Add an 'else' statement above that prints something, so you will at least
know if the UPDATE statement is ever executed.
Print the cur.rowcount attribute, which contains the number of rows that
were affected by the update. If it's zero, that should tell you something.
--
John Gordon A is for Amy, who fell down the stairs
[email protected] B is for Basil, assaulted by bears
-- Edward Gorey, "The Gashlycrumb Tinies"
--
http://mail.python.org/mailman/listinfo/python-list
Re: Updating a filename's counter value failed each time
In Alister writes:
> > #update file's counter if cookie does not exist cur.execute('''UPDATE
> > files SET hits = hits + 1, host = %s, lastvisit =
> > %s WHERE url = %s''', (host, lastvisit, filename) )
> >
> > if cur.rowcount:
> > print( " database has been affected" )
> >
> > indeed every time i select afilename the message gets printed bu then
> > again noticing the database via phpmyadmin the filename counter is
> > always remaining 0, and not added by +1
> replase
> if cur.rowcount:
> print( " database has been affected" )
> with print cur.rowcount()
rowcount isn't a method call; it's just an attribute. You don't need
the parentheses.
--
John Gordon A is for Amy, who fell down the stairs
[email protected] B is for Basil, assaulted by bears
-- Edward Gorey, "The Gashlycrumb Tinies"
--
http://mail.python.org/mailman/listinfo/python-list
Re: Problem with the "for" loop syntax
In <[email protected]> arturo balbuena writes: > Hello guys... > I=B4m a begginer in Python, I'm doing a Hangman game, but I'm having troubl= > e with this blank space. I would be greatful if you help me. :) > Here's my code: > http://snipplr.com/view/71581/hangman/ Snipplr says that link doesn't exist. > When I run the code it says: Invalid Syntax and this is the error: > http://i.imgur.com/jKYOPMY.png > http://i.imgur.com/ySoOZFR.png I don't see anything obviously wrong with that code. Are you sure that's a real blank space, and not some weird character that *looks* like a space? -- John Gordon A is for Amy, who fell down the stairs [email protected] B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: n00b question on spacing
In "Yves S. Garret"
writes:
> Hi, I have a question about breaking up really long lines of code in Python.
> I have the following line of code:
> log.msg("Item wrote to MongoDB database %s/%s" %(settings['MONGODB_DB'],
> settings['MONGODB_COLLECTION']), level=log.DEBUG, spider=spider)
> Given the fact that it goes off very far to the right on my screen is not
> terribly pleasing to my eyes (and can be rude for other developers).
> I was thinking of splitting it up like so:
> log.msg("Item wrote to MongoDB database %s/%s"
> %(settings['MONGODB_DB'], settings['MONGODB_COLLECTION']),
> level=log.DEBUG, spider=spider)
> Is this ok? Are there any rules in Python when it comes to breaking up
> long lines of code?
There are guidelines in the PEP8 document:
http://www.python.org/dev/peps/pep-0008/
Check out the section entitled 'Code lay-out'.
--
John Gordon A is for Amy, who fell down the stairs
[email protected] B is for Basil, assaulted by bears
-- Edward Gorey, "The Gashlycrumb Tinies"
--
http://mail.python.org/mailman/listinfo/python-list
Re: How can i fix this?
In <[email protected]> =?UTF-8?B?0JHQvtGA0LjRgdC70LDQsiDQkdC+0YDQuNGB0LvQsNCy0L7Qsg==?= writes: > > > while 1: > > > name=raw_input("What is your name? ") > > > if name == "bobi": > > print "Hello Master!" > > break > > > else: print "error" > this doesent help me at all Then you'll have to explain why, exactly, it doesn't help. Simply saying "this doesn't help me" is very unhelpful to *us*. Does it produce a syntax error? Does it run, but produce the wrong output? Some other reason? -- John Gordon A is for Amy, who fell down the stairs [email protected] B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: Loop Question
In [email protected] writes: > On Sunday, June 23, 2013 6:18:35 PM UTC-5, [email protected] wrote: > > How do I bring users back to beginning of user/password question once they > > > > fail it? thx > Can't seem to get this to cooperate...where does the while statement belong? while True: username = raw_input("Please enter your username: ") password = raw_input("Please enter your password: ") if username == "john doe" and password == "fopwpo": print "Login Successful" break else: print "Please try again" -- John Gordon A is for Amy, who fell down the stairs [email protected] B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: Loop Question
In
=?UTF-8?B?Q2hyaXMg4oCcS3dwb2xza2HigJ0gV2Fycmljaw==?=
writes:
> > while True:
> > username = raw_input("Please enter your username: ")
> > password = raw_input("Please enter your password: ")
> >
> > if username == "john doe" and password == "fopwpo":
> > print "Login Successful"
> > break
> >
> > else:
> > print "Please try again"
> You didn't test the code, did you? Because the code you posted is
> right.
It's right, therefore I did not test it? I don't understand.
If the code has a bug, please point it out.
> And note that the getpass module is what you should use for that second
> thing in real life, for the security of your users.
I'm sure this is just an exercise for the OP to understand loops. Security
would be counter-productive.
--
John Gordon A is for Amy, who fell down the stairs
[email protected] B is for Basil, assaulted by bears
-- Edward Gorey, "The Gashlycrumb Tinies"
--
http://mail.python.org/mailman/listinfo/python-list
Re: What's wrong with this code? (UnboundLocalError: local variable referenced before assignment)
In [email protected] writes: > isWhite = True > > def change(event): > if event.x > x1 and event.x < x2 and event.y > y1 and event.y < y2: > if isWhite: > w.itemconfig(rect, fill="blue") > isWhite = False > else: > w.itemconfig(rect, fill="white") > isWhite = True > > w.bind("", change) > > root.mainloop() > The problem occurs when clicking on the white square. The following error > appears: > "if isWhite: > UnboundLocalError: local variable 'isWhite' referenced before assignment" > However, the isWhite variable is clearly defined at "True" a few lines > before. Since you're new to programming, this might be a bit tricky to explain, but I'll do my best. :-) The problem is that change() isn't being executed here; instead it's being executed from within root.mainloop(), whenever the user presses button-1. And within root.mainloop(), there is no variable called isWhite. -- John Gordon A is for Amy, who fell down the stairs [email protected] B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: What's wrong with this code? (UnboundLocalError: local variable referenced before assignment)
In Dave Angel writes: > > The problem is that change() isn't being executed here; instead it's being > > executed from within root.mainloop(), whenever the user presses button-1. > > > > And within root.mainloop(), there is no variable called isWhite. > > > Actually that's irrelevant. Whether or not there's one global with the > same name, or twenty-three object attributes with the same name, the > fact that there's a binding of the local makes that name a local. The > only way to avoid that is not to bind, or to use global or nonlocal > declarations. Quite right. I should have verified my answer before posting. Thanks for setting me straight. :-) -- John Gordon A is for Amy, who fell down the stairs [email protected] B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: Python HTTP POST
In <[email protected]> Matt Graves writes: > How would I submit a python HTTP POST request to... for example, go to > google.com, enter "Pie" into the search box and submit (Search) Something like this: import urllib import urllib2 # the google form search input box is named 'q' data = { 'q': 'Pie' } response = urllib2.urlopen('http://google.com', urllib.urlencode(data)) print response.read() -- John Gordon A is for Amy, who fell down the stairs [email protected] B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: Find and Replace Simplification
In Devyn Collier Johnson
writes:
> I have some code that I want to simplify. I know that a for-loop would
> work well, but can I make re.sub perform all of the below tasks at once,
> or can I write this in a way that is more efficient than using a for-loop?
> DATA = re.sub(',', '', 'DATA')
> DATA = re.sub('\'', '', 'DATA')
> DATA = re.sub('(', '', 'DATA')
> DATA = re.sub(')', '', 'DATA')
If your actual use-case is this simple, you might want to use one of the
built-in string functions such as strip() or translate().
--
John Gordon A is for Amy, who fell down the stairs
[email protected] B is for Basil, assaulted by bears
-- Edward Gorey, "The Gashlycrumb Tinies"
--
http://mail.python.org/mailman/listinfo/python-list
Re: Newbie: Python 3 and web applications?
In Rui Maciel writes: > I'm currently learning Python, and I've been focusing on Python3. To try to > kill two birds with one stone, I would also like to learn the basics of > writing small web applications. > These web applications don't need to do much more than provide an interface > to a small database, and they may not even be required to be accessible > outside of a LAN. > Does anyone have any tips on what's the best way to start off this > adventure? I recommend using a web framework such as Django or Pylons. It's more to learn, but frameworks handle a ton of low-level details for you and make web development overall much easier. -- John Gordon A is for Amy, who fell down the stairs [email protected] B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: embedded python and threading
In <[email protected]> "David M. Cotter" writes: > == > 9: Traceback (most recent call last): > 9: File "", line 10, in ? > 9: File "", line 6, in main > 9: AttributeError: 'builtin_function_or_method' object has no attribute > 'sleep' > == You must have a file named 'time.py' in the current directory, and the import statement is getting that module instead of the system time module. -- John Gordon A is for Amy, who fell down the stairs [email protected] B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: dump a multi dimensional dictionary
In cerr
writes:
> Can I somehow use pickle.dump() to store a dictionary of lists to a file?
> I tried this:
> >>> import pickle
> >>> mylist = []
> >>> mydict = {}
> >>> mylist = '1','2'
> >>> mydict['3'] = mylist
> >>> fhg = open ("test", 'w')
> >>> pickle.dump(fhg,mydict)
> Traceback (most recent call last):
> File "", line 1, in
> File "/usr/lib/python2.7/pickle.py", line 1370, in dump
> Pickler(file, protocol).dump(obj)
> File "/usr/lib/python2.7/pickle.py", line 203, in __init__
> self.write = file.write
> AttributeError: 'dict' object has no attribute 'write'
> >>> print mydict
> {'3': ('1', '2')}
> or should I just write my own dump function that can hanle thiS?
I think you have the arguments to pickle.dump() in the wrong order.
The data to be dumped should come first, then the file object.
--
John Gordon A is for Amy, who fell down the stairs
[email protected] B is for Basil, assaulted by bears
-- Edward Gorey, "The Gashlycrumb Tinies"
--
http://mail.python.org/mailman/listinfo/python-list
Re: PEP8 79 char max
In Devyn Collier Johnson writes: > (http://www.python.org/dev/peps/pep-0008/#code-lay-out). What devices > cannot handle 80 or more characters on a line? For a start, older fixed-width dumb terminals and printers. And even some very new devices (tablet, smartphone) might have limited screen sizes. And even if you're on a device that can display more than 80 characters, it can be convenient to have several windows display side-to-side. > Would following this recommendation improve script performance? No, but it improves human readability. -- John Gordon A is for Amy, who fell down the stairs [email protected] B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: binary key in dictionary
In <[email protected]> cerr writes: > Traceback (most recent call last): > File "gateway.py", line 2485, in > main() > File "gateway.py", line 2459, in main > cloud_check() > File "gateway.py", line 770, in cloud_check > gnstr_dict[src] = gn_from_cloud(curr_mac) > File "gateway.py", line 2103, in gn_from_cloud > tmpgndict[binmac] += "HELLO" > KeyError: '\x04\xeeu' You're not assigning to tmpgndict[binmac]; you're appending to it. This requires that tmpgndict[binmac] already exists, which it does not. Make sure that tmpgndict[binmac] exists before you try appending to it. -- John Gordon A is for Amy, who fell down the stairs [email protected] B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: script to Login a website
In [email protected] writes: > I have created a script to log in a website. It gets its username and > password from two files, then log's in with this credentials. My code is > not showing me what username it is using to login from the file. And I am > not sure if it is even opening up the url and prompting for login. I am > stuck can someone help me ? How is the data in 'users.txt' and 'password.txt' organized? Given the filenames, I would expect that 'users.txt' contains one username on each line, and 'password.txt' contains one password on each line, with the first username belonging with the first password, the second username belonging with the second password, and so on. Is this correct? If so, that raises the question of how to handle multiple usernames and passwords. Do you just want to use one, or are you supposed to use them all somehow? Anyway, to begin to solve your problem, I'd copy just the file-reading code into a separate program and add plenty of print statements to make sure it works correctly. Once you have that fixed, then you can worry about the web login stuff. And when you read the contents of each file, be aware that the newlines at the end of each line are included. If you don't want these, be sure to call the rstrip() method to remove traling whitespace. -- John Gordon A is for Amy, who fell down the stairs [email protected] B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: how to compare below 2 json structure in python
In hisan
writes:
> sample_json1={{
>"globalControlId": 72,
>"value": 0,
>"controlId": 2
>},
>{
>"globalControlId": 77,
>"value": 3,
>"controlId": 7
>}
> }
> sample_json2={
>{
>"globalControlId": 77,
>"value": 3,
>"controlId": 7
>},
> {
>"globalControlId": 72,
>"value": 0,
>"controlId": 2
>}
> }
Assuming you have valid json strings (which these aren't), I think you
could convert them into python objects with json.loads() and then compare
the python objects.
For example:
>>> import json
>>> json1 = '{"color": "blue", "amount": 10}'
>>> json2 = '{"amount": 10, "color": "blue"}'
>>> python1 = json.loads(json1)
>>> python2 = json.loads(json2)
>>> print python1 == python2
True
>>>
--
John Gordon A is for Amy, who fell down the stairs
[email protected] B is for Basil, assaulted by bears
-- Edward Gorey, "The Gashlycrumb Tinies"
--
http://mail.python.org/mailman/listinfo/python-list
Re: code review
In Kushal Kumaran writes: > I haven't actually seen the rest of the code, but I would like to > point out that applications placing maximum length limits on passwords > are extremely annoying. As a practical matter, doesn't there have to be *some* sort of limit? For example if the (encrypted) password is stored in a database, you can't exceed the table column width. -- John Gordon A is for Amy, who fell down the stairs [email protected] B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: Adding to a List and displaying quantity in the list
In Shamefaced
writes:
> else:
> print("%8.3f %s: Waited too long %6.3f" % (now()/60, self.name,
> wait) + " time units have passed - Customer has left")
> leavelist.append(self.acquired)
What is self.acquired? Judging from earlier code it appears to be a
function, but here you're appending it to leavelist. Did you really mean
to append a function object to leavelist?
--
John Gordon A is for Amy, who fell down the stairs
[email protected] B is for Basil, assaulted by bears
-- Edward Gorey, "The Gashlycrumb Tinies"
--
http://mail.python.org/mailman/listinfo/python-list
Re: adding a simulation mode
In andrea crotti
writes:
> try:
> copytree('sjkdf', 'dsflkj')
> Popen(['notfouhd'], shell=True)
> except Exception as e:
> print("here")
> behaves differently from:
> try:
> Popen(['notfouhd'], shell=True)
> copytree('sjkdf', 'dsflkj')
> except Exception as e:
> print("here")
> because if copytree fails it quits anyway.
> I also looked at the code but can't quite get why.. any idea?
copytree() could contain a call to sys.exit(), although that seems like
a rude thing to do.
--
John Gordon A is for Amy, who fell down the stairs
[email protected] B is for Basil, assaulted by bears
-- Edward Gorey, "The Gashlycrumb Tinies"
--
http://mail.python.org/mailman/listinfo/python-list
Re: adding a simulation mode
In andrea crotti writes: > Well that's what I thought, but I can't find any explicit exit > anywhere in shutil, so what's going on there? Try catching SystemExit specifically (it doesn't inherit from Exception, so "except Exception" won't catch it.) -- John Gordon A is for Amy, who fell down the stairs [email protected] B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: Encapsulation, inheritance and polymorphism
In Dennis Lee Bieber writes: > > Sure it terminates...If you don't run out of RAM to represent the > > number "i" in question, there's also this "heat death of the > > universe" limit I keep hearing about ;-) > > > Since the current evidence indicates the universe will just keep > expanding, it's more of a "deep freeze death..." Heat death means *lack* of heat. -- John Gordon A is for Amy, who fell down the stairs [email protected] B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: Encapsulation, inheritance and polymorphism
In Chris Angelico writes: > The second law of thermodynamics states that energy tends to go from > higher states to lower, with heat being the very lowest. It's possible > to do work using (say) kinetic energy, and in the process, some of > that energy becomes heat. It's also possible to do work with any > difference in temperature (eg Stirling engines), so the state of the > universe in which it's no longer possible to do any work will be one > in which all energy is heat and everything's at the same temperature. > That doesn't mean a lack of heat; in fact, it implies that there'll be > rather more heat than there now is, because we currently have a whole > lot of chemical energy available to be used. *mind blown* -- John Gordon A is for Amy, who fell down the stairs [email protected] B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: the meaning of rï¾â¢.......ï¾
In Mark Lawrence writes: > Sorry not with you is there something special about April 1st next year? In the United States, April 1st (also known as April Fool's Day) is an occasion for practical jokes, faked 'news' stories, and general silliness. I don't know if it is observed outside the U.S. -- John Gordon A is for Amy, who fell down the stairs [email protected] B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: looking for a neat solution to a nested loop problem
In Tom P writes: > consider a nested loop algorithm - > for i in range(100): > for j in range(100): > do_something(i,j) > Now, suppose I don't want to use i = 0 and j = 0 as initial values, but > some other values i = N and j = M, and I want to iterate through all > 10,000 values in sequence - is there a neat python-like way to this? I > realize I can do things like use a variable for k in range(1): and > then derive values for i and j from k, but I'm wondering if there's > something less clunky. You could define your own generator function that yields values in whatever order you want: def my_generator(): yield 9 yield 100 for i in range(200, 250): yield i yield 5 -- John Gordon A is for Amy, who fell down the stairs [email protected] B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: Objects in Python
In <[email protected]> shaun writes: > I'm having an issue its my first time using python and i set up a class one > of the methods is supposed to return a string but instead returns: > 389E0>> It looks like you're referencing the method object itself, instead of calling it method. In other words, you've left off the parentheses. I.e. you're doing something like this: print my_object.foo Instead of this: print my_object.foo() -- John Gordon A is for Amy, who fell down the stairs [email protected] B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: ctypes - python2.7.3 vs python3.2.3
In <[email protected]> Rolf writes: > uint32_t myfunction (char ** _mydata) > { >char mydata[16]; >strcpy(mydata, "Hello Dude!"); >*_mydata = mydata; >return 0; > } mydata is an auto variable, which goes out of scope when myfunction() exits. *_mydata ends up pointing to garbage. -- John Gordon A is for Amy, who fell down the stairs [email protected] B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: ctypes - python2.7.3 vs python3.2.3
In <[email protected]> Jan Kuiken writes: > >> uint32_t myfunction (char ** _mydata) > >> { > >> char mydata[16]; > > > >> strcpy(mydata, "Hello Dude!"); > > > >> *_mydata = mydata; > > > >> return 0; > >> } > > > > mydata is an auto variable, which goes out of scope when myfunction() > > exits. *_mydata ends up pointing to garbage. > I'm not completely sure, but i think this can be solved by using: > static char mydata[16]; That will solve the immediate problem, however it makes myfunction() non-reentrant. > (Btw.: I don't know why you use char ** _mydata, i would use > char * _mydata, but then again, i'm not very familiar with > ctypes) He uses char **_mydata because he wants myfunction()'s caller to see the new value of _mydata, which it wouldn't if it were just char *_mydata. -- John Gordon A is for Amy, who fell down the stairs [email protected] B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: Python presentations
In andrea crotti writes: > For my experience if I only see code in slides I tend not to believe > that it works somehow Presumably you will have some credibility with your audience so they won't just assume you're making it up? I think slides would be fine. -- John Gordon A is for Amy, who fell down the stairs [email protected] B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: Installing Pip onto a mac os x system
In John Mordecai Dildy writes: > Now it shows the error of: > sudo: easy_instal: command not found Try 'easy_install' instead of 'easy_instal'. -- John Gordon A is for Amy, who fell down the stairs [email protected] B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: Print Function
In [email protected] writes: > I am currently using Python 3.2.3 . WHen I use the print function by > typing print "Game Over" , it mentions " SyntaxError : invalid syntax ". > Any ideas on what the problem is and how to resolve it ? Thanks a lot . In python version 3, print was changed into a function. Use this and it will work: print("Game Over") -- John Gordon A is for Amy, who fell down the stairs [email protected] B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: Reducing cache/buffer for faster display
In Chris Angelico writes: > On Fri, Sep 28, 2012 at 7:57 AM, Rikishi42 wrote: > > I have these 2 scripts that are very heavy on the file i/o, consume a very > > reasonable amount of cpu and output their counters at a - very - relaxed > > pace to the console. The output is very simply done using something like: > > > >print "files:", nFiles, "\r", > > > > > > Yet alltough there is no real reason for it, even a pace of a print every > > 10-30 secs will be cached, only to actually show an output update every 1-2 > > min or so. > Yup! Just add a call to sys.stdout.flush() after each print. Isn't terminal output line-buffered? I don't understand why there would be an output delay. (Unless the "\r" is messing things up...) -- John Gordon A is for Amy, who fell down the stairs [email protected] B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: How to get progress in python script.
In =?ISO-8859-1?Q?Rolando_Ca=F1er_Roblejo?= writes: > Hi all, > Please, I need you suggest me a way to get statistics about a progress > of my python script. My python script could take a lot of time > processing a file, so I need a way that an external program check the > progress of the script. My first idea was that the python script write a > temp file showing the progress and the external program can check that > file, but I think might happen file read/write locking issues. The external program should open the progress file for read only, so I wouldn't think file locking would be an issue. -- John Gordon A is for Amy, who fell down the stairs [email protected] B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: how to insert random error in a programming
In Debashish Saha writes: > how to insert random error in a programming? Open the program source file and replace the Nth character with a random character. -- John Gordon A is for Amy, who fell down the stairs [email protected] B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: Exception Messages
In MRAB writes: > > Why wasn't the message printed out? > > You didn't add a __str__ method: > class PvCamError(Exception): > def __init__(self, msg): > self.msg = msg > def __str__(self): > return self.msg Wouldn't PvCamError inherit __str__() from Exception? -- John Gordon A is for Amy, who fell down the stairs [email protected] B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: How to only get a list of the names of the non-directory files in current directory ('.')?
In iMath writes: > how to get a list of names of everything in the current directory ? Try os.listdir() . -- John Gordon A is for Amy, who fell down the stairs [email protected] B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: How to only get a list of the names of the non-directory files in current directory ('.')?
In Chris Angelico writes: > It yields it? You mean Google is an iterator? ITYM generator. -- John Gordon A is for Amy, who fell down the stairs [email protected] B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: Generate unique ID for URL
In <[email protected]> Richard writes: > I want to create a URL-safe unique ID for URL's. > Currently I use: > url_id = base64.urlsafe_b64encode(url) > >>> base64.urlsafe_b64encode('docs.python.org/library/uuid.html') > 'ZG9jcy5weXRob24ub3JnL2xpYnJhcnkvdXVpZC5odG1s' > I would prefer more concise ID's. > What do you recommend? - Compression? Does the ID need to contain all the information necessary to recreate the original URL? -- John Gordon A is for Amy, who fell down the stairs [email protected] B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: Robust regex
In "Joseph L. Casale"
writes:
> Trying to robustly parse a string that will have key/value pairs separated
> by three pipes, where each additional key/value (if more than one exists)
> will be delineated by four more pipes.
> string = 'key_1|||value_1key_2|||value_2'
> regex = '((?:(?!\|\|\|).)+)(?:\|\|\|)((?:(?!\|\|\|).)+)(?:\|\|\|\|)?'
> I am not convinced this is the most effective or safest, any opinions would
> be greatly appreciated!
Regexes may be overkill here. A simple string split might be better:
string = 'key_1|||value_1key_2|||value_2'
pairs = string.split('')
for pair in pairs:
keyval = pair.split('|||')
print '%s=%s' % (keyval[0], keyval[1])
--
John Gordon A is for Amy, who fell down the stairs
[email protected] B is for Basil, assaulted by bears
-- Edward Gorey, "The Gashlycrumb Tinies"
--
http://mail.python.org/mailman/listinfo/python-list
Re: 10 sec poll - please reply!
In <[email protected]> Michael Herrmann writes: > What, in your view, would be the most intuitive alternative name? keyboard_input(). -- John Gordon A is for Amy, who fell down the stairs [email protected] B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: List problem
In <[email protected]> [email protected] writes: > Dear Group, > I have a list of the following pattern, > [("''", "''"), ('Eastern', 'NNP'), ('Army', 'NNP'), ('Commander', 'NNP'), (= > 'Lt', 'NNP'), ('Gen', 'NNP'), ('Dalbir', 'NNP'), ('Singh', 'NNP'), ('Suhag'= > , 'NNP'), ('briefed', 'VBD'), ('the', 'DT'), ('Army', 'NNP'), ('chief', 'NN= > '), ('on', 'IN'), ('the', 'DT'), ('operational', 'JJ'), ('preparedness', 'N= > N'), ('and', 'CC'), ('the', 'DT'), ('security', 'NN'), ('scenario', 'NN'), = > ('in', 'IN'), ('the', 'DT'), ('eastern', 'NN'), ('region', 'NN'), (',', ','= > ), ("''", "''"), ('defence', 'NN'), ('spokesperson', 'NN'), ('Group', 'NNP'= > ), ('Capt', 'NNP'), ('T', 'NNP'), ('K', 'NNP'), ('Singha', 'NNP'), ('said',= > 'VBD'), ('here', 'RB')] > Now, as we see it has multiple VBD elements. > I want to recognize,count and index them all. That depends on exactly what you mean by 'reorganize' and 'index'. But here's a start: items = [("''", "''"), ('Eastern', 'NNP'), ('Army', 'NNP'), ('Commander', 'NNP'), ('Lt', 'NNP'), ('Gen', 'NNP'), ('Dalbir', 'NNP'), ('Singh', 'NNP'), ('Suhag' , 'NNP'), ('briefed', 'VBD'), ('the', 'DT'), ('Army', 'NNP'), ('chief', 'NN'), ('on', 'IN'), ('the', 'DT'), ('operational', 'JJ'), ('preparedness', 'NN'), ('and', 'CC'), ('the', 'DT'), ('security', 'NN'), ('scenario', 'NN'), ('in', 'IN'), ('the', 'DT'), ('eastern', 'NN'), ('region', 'NN'), (',', ','), ("''", "''"), ('defence', 'NN'), ('spokesperson', 'NN'), ('Group', 'NNP'), ('Capt', 'NNP'), ('T', 'NNP'), ('K', 'NNP'), ('Singha', 'NNP'), ('said', 'VBD'), ('here', 'RB')] vbds = [item[0] for item in items if item[1] == 'VBD'] print vbds -- http://mail.python.org/mailman/listinfo/python-list
Re: Conversion of List of Tuples
In <[email protected]> [email protected] writes: > Dear Group, > I have a tuple of list as, > tup_list=[(1,2), (3,4)] > Now if I want to covert as a simple list, > list=[1,2,3,4] > how may I do that? new_list = [] for t in tup_list: for item in t: new_list.append(item) -- John Gordon A is for Amy, who fell down the stairs [email protected] B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: Conversion of List of Tuples
In [email protected] writes: > Thanks. But I am not getting the counter "5posts 0 views"...if > moderator can please check the issue. I logged in via Google Groups and all the replies were present. What is your question? (This group is not moderated.) -- John Gordon A is for Amy, who fell down the stairs [email protected] B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: mini browser with python
In inq1ltd writes: > In other words I need a mini, simple browser; > something I can build that will open, read and > display a saved html or the connected url site. What will be the output of this mini browser? Plain text? Rendered graphics? An audible screen reader? Something else? What web standards does this mini browser need to support? Full HTML5? Partial HTML? CSS? Javascript? Flash? -- John Gordon A is for Amy, who fell down the stairs [email protected] B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: mini browser with python
In inq1ltd writes: > Right now I need some way to display > 15 to 20 lines of html in its own window or > as part of my screen. Could you open a shell window and run a text web browser such as Lynx? -- John Gordon A is for Amy, who fell down the stairs [email protected] B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: date-time comparison, aware vs naive
In <[email protected]> noydb writes: > I want to compare a user entered date-and-time against the date-and-time of > a pdf file. I posted on this (how to get a file's date-time) before, was > advised to do it like: > import datetime, os, stat > mtime = os.lstat(filename)[stat.ST_MTIME] // the files modification time > dt = datetime.datetime.fromtimestamp(mtime) > I am having problems with the comparison, that line is failing. What line? You haven't posted any comparison line of code here. Please post the actual code you're using, instead of telling us about it. -- John Gordon A is for Amy, who fell down the stairs [email protected] B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: String manipulation in python..NEED HELP!!!!
In [email protected] writes: > """ crypto.py > Implements a simple substitution cypher > """ > alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" > key = "XPMGTDHLYONZBWEARKJUFSCIQV" > def main(): > keepGoing = True > while keepGoing: > response = menu() > if response == "1": > plain = raw_input("text to be encoded: ") > print encode(plain) > elif response == "2": > coded = raw_input("code to be decyphered: ") > print decode(coded) > elif response == "0": > print "Thanks for doing secret spy stuff with me." > keepGoing = False > else: > print "I don't know what you want to do..." > i really need help on how to encrypt it im not sure how to go about doing > that please help. def encode(plain): '''Return a substituted version of the plain text.''' encoded = '' for ch in plain: encoded += key[alpha.index(ch)] return encoded -- John Gordon A is for Amy, who fell down the stairs [email protected] B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: MySQLdb compare lower
In Anatoli Hristov
writes:
> I have a situation where I compare the SKU in my DB and there are some
> SKU that are with lowercase and some with uppercase, how can I solve
> this in your opinion ?
> def Update_SQL(price, sku):
> db = MySQLdb.connect("localhost","getit","opencart",
> use_unicode=True, charset="utf8")
> cursor = db.cursor()
> sql = "UPDATE product SET price=%s WHERE sku=%s"
> cursor.execute(sql, (price, sku))
> db.commit()
> db.close()
I think this will work:
sql = 'UPDATE product SET price=%s WHERE LOWER(sku)=%s'
cursor.execute(sql, (price, sku.lower())
--
John Gordon A is for Amy, who fell down the stairs
[email protected] B is for Basil, assaulted by bears
-- Edward Gorey, "The Gashlycrumb Tinies"
--
http://mail.python.org/mailman/listinfo/python-list
Re: Why Doesn't This MySQL Statement Execute?
In Tom Borkin
writes:
> Actually, what I originally had was:
> cursor.execute("""insert into interactions values(Null, %s, "Call Back",
> %s)""", (i_id, date_plus_2))
> and that didn't work, either. I tried your variation like:
> cursor.execute("""insert into interactions values(Null, %s, "Call Back",
> %s)""" % (i_id, date_plus_2))
> and no cigar :(
> Tom
Have you tried using single-quotes around Call Back, instead of
double quotes? I've noticed that SQL statements prefer single-quoted
strings (although that may be Oracle specific, as that's all I've really
worked with).
--
John Gordon A is for Amy, who fell down the stairs
[email protected] B is for Basil, assaulted by bears
-- Edward Gorey, "The Gashlycrumb Tinies"
--
http://mail.python.org/mailman/listinfo/python-list
Re: Evaluate postgres boolean field
In [email protected] writes: > for row in cursor: > row_count += 1 > if row[4] = True > print row[1] Since row[4] is a boolean value, you should be able to just say: if row[4]: print row[1] -- John Gordon A is for Amy, who fell down the stairs [email protected] B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: new to python and programming at large.
In [email protected] writes: > thanks for ur help I wz able to do it.but I wish to expand it by asking > a user to input a number for the sqrt to be calculated it I dd it this > way but its not working. > from math import sqrt > number = raw_input('enter a number:') > def number(y): > return number(Y) You're storing the user input in a variable called 'number', but then you define a method also called 'number'. Call them something different. Within your method, you probably want to return sqrt(y) instead of calling the method from itself. The argument to your method is called 'y' in the definition, but you refer to it as 'Y' in the return statement. Variable names are case-sensitive. -- John Gordon A is for Amy, who fell down the stairs [email protected] B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: Why BOM in logging message?
In [email protected] (Roy Smith) writes: > What's weird is that two of the servers, and only those two, stick a > BOM (Byte Order Mark) in front of the message they log. It shows up > in syslog as: > 2013-01-09T00:00:00+00:00 web5.songza.com 2013-01-0900:00:00,754 > [18979]: [etc...] I worked on an application that would insert a BOM in syslog messages if the logged message contained unicode, but not if it was plain ascii. Not sure if this relates to your issue, but it's similar enough that it seemed worth mentioning. -- John Gordon A is for Amy, who fell down the stairs [email protected] B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: Psycopg2 SyntaxError: invalid syntax on "INSERT INTO" database
In [email protected] writes: > I'm a bit stuck on this "INSERT INTO" syntax error. I have no idea why it's What syntax error? It's always helpful if you can post the actual error message. > not working actually... I've tried changing column types to char but that > didn't work. I've gone a bit blind looking at it, but hopefully you can set > me right. With the '#'d out lines instead the file does work. > #!/usr/bin/python > import psycopg2 > import sys > def main(): >db = psycopg2.connect( > host = 'localhost', > database = 'gisdb', > user = 'postgres', > password = '##' >) >cursor = db.cursor() >cursor.execute("DROP TABLE IF EXISTS tubecross") >cursor_to.execute("CREATE TABLE tubecross (id serial PRIMARY KEY, > station_code char, SAJ interval, SPB interval, SOQ interval);") >#cursor.execute("CREATE TABLE tubecross (id serial PRIMARY KEY, num > integer, data varchar);") >#cursor.execute("INSERT INTO tubecross (num, data) VALUES (%s, %s)",(900, > "9abc'def")) >cursor_to.execute("INSERT INTO tubecross (station_code, SAJ, SPB, SOQ) > VALUES (%s, %s, %s, %s)",(SAJ, 00:00, 00:22, 00:27)) >db.commit() > if __name__ == "__main__": > main() You appear to have two very different versions of the tubecross table. One version has three fields (id, num, data) and the other version has at least four (station_code, SAJ, SPB, SOQ). Which one is correct? Also, what is the 'cursor_to' variable? It doesn't appear to be defined anywhere. -- John Gordon A is for Amy, who fell down the stairs [email protected] B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: Thought of the day
In Michael Torrie writes: > On 01/13/2013 09:16 PM, Steven D'Aprano wrote: > > A programmer had a problem, and thought Now he has "I know, I'll solve > > two it with threads!" problems. > The same applies to regular expressions, which is actually what the > expression was first used with years ago. Probably applies to just > about any technology. Including Java. Steven cleverly worded it in such a way as to apply directly to threads. The sentences are jumbled and interleaved, as if they were the output of two threads that are not synchronized. -- John Gordon A is for Amy, who fell down the stairs [email protected] B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: Uniquely identifying each & every html template
In <[email protected]> Ferrous Cranus writes: > Problem is that i have to insert at the very first line of every .html > template of mine, a unique string containing a number like: > index.html > somefile.html > other.html > nikos.html > cool.html > to HELP counter.py identify each webpage at a unique way. Instead of inserting unique content in every page, can you use the document path itself as the identifier? -- John Gordon A is for Amy, who fell down the stairs [email protected] B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: Uniquely identifying each & every html template
In <[email protected]> Ferrous Cranus writes: > > If that's the case, then I figure you have about 3 choices: > > 1) use the file path as your key, instead of requiring a number > No, i cannot, because it would mess things at a later time on when i for > example: > 1. mv name.html othername.html (document's filename altered) > 2. mv name.html /subfolder/name.html (document's filepath altered) Will the file always reside on the same device? If so, perhaps you could use the file inode number as the key. (That seems fairly brittle though. For example if the disk crashes and is restored from a backup, the inodes could easily be different.) -- John Gordon A is for Amy, who fell down the stairs [email protected] B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: Using filepath method to identify an .html page
In Ferrous Cranus writes: > I just need a way to CONVERT a string(absolute path) to a 4-digit unique > number with INT!!! That's all i want!! But i cannot make it work :( Given your requirements, I don't think it *can* work. There's just no way to do it. How can the computer guarantee that billions of possible inputs (file paths) map to 10,000 unique outputs (4-digit numbers)? It's not possible. It might be possible if you had control over the format of the input strings, but it doesn't sound like you do. Can you maintain a separate database which maps file paths to numbers? If so, then this is an easy problem. Just keep a lookup table, like so: filepath number -- /home/files/bob/foo.html 0001 /home/files/bob/bar.html 0002 /home/files/steve/recipes/chocolate-cake.html0003 /home/files/mary/payroll.html 0004 -- John Gordon A is for Amy, who fell down the stairs [email protected] B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: Converting a string to a number by using INT (no hash method)
In <[email protected]> Ferrous Cranus writes: > > pin int( htmlpage.encode("hex"), 16 ) % 1 > > > > It'll give you your number, but there are no guarantees of uniqueness. > You're looking at more blind random luck using that. > Finally!! THANK YOU VERY MUCH!!! THIS IS WHAT I WAS LOOKING FOR!!! No it isn't; you said you wanted a unique 4-digit number. This method can return the same 4-digit number for lots of different file paths. > NOW, if you please explain it to me from the innermost parenthesis please, > because i do want to understand it!!! 1. Transform the html path string into a (large) hexadecimal number using the encode() function. 2. Convert the hexadecimal number into a decimal integer using the int() function. 3. Shrink the integer into the range 0- by using the % operator. -- http://mail.python.org/mailman/listinfo/python-list
Re: Using filepath method to identify an .html page
In <[email protected]> Ferrous Cranus writes: > And the .html files are not even close 10.000 You said you wanted a 4-digit number. There are 10,000 different 4-digit numbers. 0001 0002 ... 9999 -- John Gordon A is for Amy, who fell down the stairs [email protected] B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: Importing class from another file
In Kevin Holleran writes: > I have a class called My_Class in a subdir called Sub_Dir. > in My_Class.py is the following > class My_Class_Connector: > def __init__(self,un,pw,qs_srv="domain.com"): > self.username = un > self.password = pw > Then I am trying to call from a script in the parent dir like this: > from Sub_Dir.My_Class import * > q_api = My_Class.My_Class_Connector(string1,string2) Even if your import had worked, this would be wrong. You're importing everything from Sub_Dir.My_Class, so My_Class_Connector is in the current namespace. You don't need to add "My_Class." on the front (and in fact it's an error to do so.) > Traceback (most recent call last): > File "testing.py", line 1, in > from Sub_Dir.My_Class import * > ImportError: No module named Sub_Dir.My_Class Is there a file named __init__.py in Sub_Dir? A directory must contain that file in order to be considered a "module". (If you don't know what to put in the file, just leave it empty.) -- John Gordon A is for Amy, who fell down the stairs [email protected] B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: Converting a string to a number by using INT (no hash method)
In Ferrous Cranus writes: > May i sent you my code by mail so for you see whats wrong and > http://superhost.gr produces error? I tried going to that address and got some error output. I noticed this in the error dump: 186 if cursor.rowcount == 0: 187 cursor.execute( '''INSERT INTO visitors(pin, host , hits, useros, browser, date) VALUES(%s, %s, %s, %s, %s)''', (pin, hos t, 1, useros, browser, date) ) The INSERT statement gives six column names but only five placeholders (%s) in the VALUES clause. Perhaps that's the problem? -- John Gordon A is for Amy, who fell down the stairs [email protected] B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: Search log for string and display hourly/daily report
In <[email protected]> [email protected] writes: > I need to search a log file for a specific string (Successfully Sent) and > report the number of instances in the last hour (from when executed) and > total for the day so far (midnight till the time executed). Can anyone > provide any examples of such a program or get me started? from datetime import datetime, timedelta from time import mktime, strptime now = datetime.now() midnight = now.replace(hour=0, minute=0, second=0, microsecond=0) one_hour_ago = now - timedelta(hours=1) daily_instances = 0 hourly_instances = 0 with open('myfile.log') as logfile: for line in logfile: if 'Successfully Sent' in line: time_string = line[0:19] struct = strptime(time_string, "%Y-%m-%dT%H:%M:%S") log_time = datetime.fromtimestamp(mktime(struct)) if log_time > midnight: daily_instances += 1 if log_time > one_hour_ago: hourly_instances += 1 print "Instances in the last hour: ", hourly_instances print "Instances since midnight: ", daily_instances This code assumes that log lines begin with a timestamp similar to "2013-01-23T09:27:01". If the timestamp is in a different format, or occurs elsewhere in the line, you'll have to adjust for that. -- John Gordon A is for Amy, who fell down the stairs [email protected] B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: Arent these snippets equivalent?
In Coolgg
writes:
> Is this:
> while True:
> data = fp.read(4096)
> if not data:
> break
> ...
> not equivalent to this:
> data = fp.read (4096)
> while data:
> ...{handle the chunk here}
> data = fp.read (4096)
It looks equivalent to me (in terms of control flow).
But in the second example the fp.read() statement is duplicated, which is
undesirable. It would be all too easy for a maintenance programmer to go
into the code a year from now and change the first one but miss the second
one.
--
John Gordon A is for Amy, who fell down the stairs
[email protected] B is for Basil, assaulted by bears
-- Edward Gorey, "The Gashlycrumb Tinies"
--
http://mail.python.org/mailman/listinfo/python-list
Re: The best, friendly and easy use Python Editor.
In Hazard Seventyfour writes: > Hello, > I new in this python and decided to learn more about it, so i can make > an own script :), > for all senior can you suggest me the best, friendly and easy use with > nice GUI editor for me, and have many a good features such as auto > complete/auto correct. Try PyScripter. http://code.google.com/p/pyscripter/ -- John Gordon A is for Amy, who fell down the stairs [email protected] B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: The best, friendly and easy use Python Editor.
In Sharwan Joram writes: > use vim. He said he wanted autocomplete. Does Vim have that? -- John Gordon A is for Amy, who fell down the stairs [email protected] B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: Please provide a better explanation of tuples and dictionaries
In "Daniel W. Rouse Jr."
writes:
> I have recently started learning Python (2.7.3) but need a better
> explanation of how to use tuples and dictionaries.
A tuple is a linear sequence of items, accessed via subscripts that start
at zero.
Tuples are read-only; items cannot be added, removed, nor replaced.
Items in a tuple need not be the same type.
Example:
>>> my_tuple = (1, 5, 'hello', 9.)
>>> print my_tuple[0]
1
>>> print my_tuple[2]
hello
A dictionary is a mapping type; it allows you to access items via a
meaningful name (usually a string.)
Dictionaries do not preserve the order in which items are created (but
there is a class in newer python versions, collections.OrderedDict, which
does preserve order.)
Example:
>>> person = {} # start with an empty dictionary
>>> person['name'] = 'John'
>>> person['age'] = 40
>>> person['occupation'] = 'Programmer'
>>> print person['age']
40
Dictionaries can also be created with some initial values, like so:
>>> person = { 'name': 'John', 'age': 40, 'occupation' : 'Programmer' }
--
John Gordon A is for Amy, who fell down the stairs
[email protected] B is for Basil, assaulted by bears
-- Edward Gorey, "The Gashlycrumb Tinies"
--
http://mail.python.org/mailman/listinfo/python-list
Re: Weird newbie question
In Matty Sarro
writes:
> Hey everyone. I'm running into a funky error as I work through "Learn
> Python the Hard Way." What's weird is both idle and the python
> interpreter in idle spit out an error about syntax, but when I run the
> same script from the command line it works just fine, with no issue.
> I'm not sure if its an issue with IDLE or if I'm doing something
> wrong.
> Here's the book's code:
> from sys import argv
> script, filename = argv
> txt = open(filename)
> print "Here's your file %r:" % filename
> print txt.read()
> print "Type the filename again:"
> file_again = raw_input("> ")
> txt_again = open(file_again)
> print txt_again.read()
> Here's my code:
> from sys import argv
> script,filename=argv
> txt=open(filename)
> print "Here is your file %r:" % filename
> print txt.read()
> print "I'll also ask you to type it again:"
> file_again=raw_input("> ")
> txt_again=open(file_again)
> print txt_again.read()
> IDLE is saying that my error is on line 4, at the second set of
> quotation marks. Since I can't get the error from the command line, I
> can't actually see what the syntax error is that it's complaining
> about. Any advice would really be appreciated, thank you!!
This may be a Python version mismatch error.
In python version 2.x (and 1.x for that matter), "print" is a statement,
but it was changed to be a function in python version 3.x.
In other words, in python 2.x you can say this:
print x
print "hello there"
But in python 3.x you have to do it a little differently:
print(x)
print("hello there")
It sounds like your IDLE is running python 3, but your command line is
running python 2.
--
John Gordon A is for Amy, who fell down the stairs
[email protected] B is for Basil, assaulted by bears
-- Edward Gorey, "The Gashlycrumb Tinies"
--
http://mail.python.org/mailman/listinfo/python-list
Re: Reading files in from the proper directory
In [email protected] writes: > Am I correct in thinking that I need to change the current working > directory to this folder in order for Python to read in these files, > then generate my output? You don't have to do it that way, no. In general, when opening a file, you can do it two ways: Either provide a full pathname, or provide a relative pathname. If you provide a full pathname (for example "/usr/home/smith/myfile.txt"), that file will be opened and it does not matter what the current working directory is. If you provide a relative pathname (for example "myfile.txt"), python will attempt to open that file starting from the current working dir. -- John Gordon A is for Amy, who fell down the stairs [email protected] B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: Reading files in from the proper directory
In <[email protected]> [email protected] writes: > xls_files = glob.glob(in_dir + "*.xls") You may want to put a directory separator character in between the directory name and the filename glob pattern. -- John Gordon A is for Amy, who fell down the stairs [email protected] B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
How can I catch misnamed variables?
Recently I was been bitten by some stupid errors in my code, and I'm wondering if there's a simple way to catch them. One error was of the form: my_object.some_function() .. when I hadn't declared an object named "my_object". The other error was similar: x = my_module.CONSTANT .. when I hadn't imported my_module. Of course both of these errors were deep inside a long-running function call, so it took a while for them to crop up. Is there an automated way to catch errors like these? I'm using the compileall module to build my program and it does catch some errors such as incorrect indentation, but not errors like the above. -- John Gordon A is for Amy, who fell down the stairs [email protected] B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: datetime module and timezone
In <[email protected]> Olive writes: > In the datetime module, it has support for a notion of timezone but is > it possible to use one of the available timezone (I am on Linux). Linux > has a notion of timezone (in my distribution, they are stored > in /usr/share/zoneinfo). I would like to be able 1) to know the current > timezone and 2) to be able to use the timezone available on the system. > How can I do that? I believe the current user's timezone is stored in the TZ environment variable. I don't understand your second question. Are you asking for a list of of all the possible timezone choices? -- John Gordon A is for Amy, who fell down the stairs [email protected] B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: log and figure out what bits are slow and optimize them.
In Kev Dwyer writes: > *Any* instrumentation code is going to affect performance. Funny story about that... I wanted to profile some code of mine, and a colleague recommended the 'hotshot' module. It's pretty easy to use: there are functions to start profiling, stop profiling and print results. So I added the function calls and ran my code and it took a really long time. I mean a REALLY long time. In fact I eventually had to kill the process. I briefly wondered if my coworker was playing a prank on me... then I realized that I had neglected to call the function to stop profiling! So when I went to print the results, it was still profiling... endlessly. (Okay, maybe it wasn't that funny.) -- John Gordon A is for Amy, who fell down the stairs [email protected] B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: Python code file prototype
In <[email protected]> Bruce Eckel writes: > There's an option when you do this to insert default file contents, so > I began searching the web for some kind of prototype Python file that > would be appropriate to start with. I'm certain I've seen this before > and that there's been discussions about the best starting point for a > python code file, but I find I can't get any search hits for it. Here's what PyScripter inserts in a new python file: #- # Name:module1 # Purpose: # # Author: $USERNAME # # Created: $DATE # Copyright: (c) $USERNAME $YEAR # Licence: #- #!/usr/bin/env python def main(): pass if __name__ == '__main__': main() Where $USERNAME, $DATE and $YEAR are expanded to the actual values. -- John Gordon A is for Amy, who fell down the stairs [email protected] B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: list comprehension question
In James Broadhead writes: > On 29 February 2012 13:52, Johann Spies wrote: > > In [82]: t.append(instansie) > > t.append(instansie) > > > > In [83]: t > > t > > Out[83]: ['Mangosuthu Technikon'] > > In [84]: t = [x.alt_name for x in lys].append(instansie) > > t = [x.alt_name for x in lys].append(instansie) > > > > In [85]: t > > t > > > > In [86]: type t > > type t > > ---> type(t) > > Out[86]: NoneType > > > You should note that in [82], you're not doing: > > t = t.append(instansie) append() modifies the list in-place. It doesn't return anything. (and therefore its return value is None) >>> x = [1, 2, 3] >>> y = x.append(4) >>> print x [1, 2, 3, 4] >>> print y None -- John Gordon A is for Amy, who fell down the stairs [email protected] B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: Project
In Dev Dixit writes: > Please, tell me how to develop project on "how people intract with > social networing sites". First you need a more detailed description of exactly what you want. -- John Gordon A is for Amy, who fell down the stairs [email protected] B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: What's the best way to write this regular expression?
In <21519dbf-4097-4780-874d-41d76f645...@x17g2000yqj.googlegroups.com> John Salerno writes: > Well, after a bit of experimentation, I got it to run, but I seem to > have run into the same error as when I used setup.py: > http://i271.photobucket.com/albums/jj138/JohnJSal/lxml_error.png > Now I have no idea what to do. The first error on that screen is that "xslt-config" is not found as a command. Try a web search for "xslt-config not found", there seemed to be some helpful results. -- John Gordon A is for Amy, who fell down the stairs [email protected] B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Best way to disconnect from ldap?
I'm writing an application that interacts with ldap, and I'm looking
for advice on how to handle the connection. Specifically, how to
close the ldap connection when the application is done.
I wrote a class to wrap an LDAP connection, similar to this:
import ldap
import ConfigParser
class MyLDAPWrapper(object):
def __init__(self):
config = ConfigParser.SafeConfigParser()
config.read('sample.conf')
uri = config.get('LDAP', 'uri')
user = config.get('LDAP', 'user')
password = config.get('LDAP', 'password')
self.ldapClient = ldap.initialize(uri)
self.ldapClient.simple_bind_s(user, password)
My question is this: what is the best way to ensure the ldap connection
gets closed when it should? I could write an explicit close() method,
but that seems a bit messy; there would end up being lots of calls to
close() scattered around in my code (primarily inside exception handlers.)
Or I could write a __del__ method:
def __del__(self):
self.ldapClient.unbind_s()
This seems like a much cleaner solution, as I don't ever have to worry
about closing the connection; it gets done automatically.
I haven't ever used __del__ before. Are there any 'gotchas' I need to
worry about?
Thanks!
--
John Gordon A is for Amy, who fell down the stairs
[email protected] B is for Basil, assaulted by bears
-- Edward Gorey, "The Gashlycrumb Tinies"
--
http://mail.python.org/mailman/listinfo/python-list
Re: Python Gotcha's?
In <7367295.815.1333578860181.JavaMail.geo-discussion-forums@ynpp8> Miki Tebeka writes: > Greetings, > I'm going to give a "Python Gotcha's" talk at work. > If you have an interesting/common "Gotcha" (warts/dark corners ...) > please share. This is fairly pedestrian as gotchas go, but it has bitten me: If you are working with data that is representable as either an integer or a string, choose one and stick to it. Treating it as both/either will eventually lead to grief. Or, in other words: 1 != '1' -- John Gordon A is for Amy, who fell down the stairs [email protected] B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: Best way to disconnect from ldap?
In John Gordon writes:
> I'm writing an application that interacts with ldap, and I'm looking
> for advice on how to handle the connection. Specifically, how to
> close the ldap connection when the application is done.
> I wrote a class to wrap an LDAP connection, similar to this:
> import ldap
> import ConfigParser
> class MyLDAPWrapper(object):
> def __init__(self):
> config = ConfigParser.SafeConfigParser()
> config.read('sample.conf')
>
> uri = config.get('LDAP', 'uri')
> user = config.get('LDAP', 'user')
> password = config.get('LDAP', 'password')
> self.ldapClient = ldap.initialize(uri)
> self.ldapClient.simple_bind_s(user, password)
> My question is this: what is the best way to ensure the ldap connection
> gets closed when it should? I could write an explicit close() method,
> but that seems a bit messy; there would end up being lots of calls to
> close() scattered around in my code (primarily inside exception handlers.)
> Or I could write a __del__ method:
> def __del__(self):
> self.ldapClient.unbind_s()
Thanks everyone for your input. I learned a lot!
However, I just ran across this bit of documentation on python-ldap.org:
class ldap.LDAPObject
Instances of LDAPObject are returned by initialize() and open()
(deprecated). The connection is automatically unbound and closed
when the LDAP object is deleted.
So, given that, do I need to do anything at all?
--
John Gordon A is for Amy, who fell down the stairs
[email protected] B is for Basil, assaulted by bears
-- Edward Gorey, "The Gashlycrumb Tinies"
--
http://mail.python.org/mailman/listinfo/python-list
Re: python module development workflow
In <2900f481-fbe9-4da3-a7ca-5485d1ceb...@m13g2000yqc.googlegroups.com> Peng Yu writes: > It is confusing to me what the best workflow is for python module > development. There is setup.py, egg. Also, pip, easy_install. It's unclear what you are asking. How to develop your own modules? How to package and distribute your own modules once they're finished? How to install modules that other people have developed? -- John Gordon A is for Amy, who fell down the stairs [email protected] B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: Converting a string to list for submission to easygui multenterbox
In <[email protected]> ksals writes: > Please help a newbe. I have a string returned from an esygui > multchoicebox that looks like > this: ('ksals', '', 'alsdkfj', '3', '') I need to convert this to > this: ['ksals', '', 'alsdkfj', '3', ''] That looks like a tuple which contains five strings. But you said it's a string, so I'll believe you. >>> x = "('ksals', '', 'alsdkfj', '3', '')" >>> print x ('ksals', '', 'alsdkfj', '3', '') >>> y = "[%s]" % x[1:-1] >>> print y ['ksals', '', 'alsdkfj', '3', ''] -- John Gordon A is for Amy, who fell down the stairs [email protected] B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: Re: Converting a string to list for submission to easygui multenterbox
In <3b5f65c4-cd95-4bb4-94f2-0c69cf2b1...@d20g2000vbh.googlegroups.com> ksals
writes:
> The original choice looks like this when I print it:
> print(choice)
> ('ksals', '', 'alsdkfj', '3', '')
> I need to submit these as defaults to a multenterbox. Each entry above
> ksals, "", "alsdkfj', 3 , '' need to fill the five fields in the box.
> I tried your suggestion so you must be right it is a tuple of 5
> strings. But I need them to work in an instruction like
> fieldValues =3D eg.multenterbox(msg1,title, fieldNames, choice)
> fieldNames has 5 fields.
If you just need to convert a tuple to a list, that's easy. Call the
built-in function list() and pass the tuple as an intializer:
>>> choice = ('ksals', '', 'alsdkfj', '3', '')
>>> print choice
('ksals', '', 'alsdkfj', '3', '')
>>> choice_list = list(choice)
>>> print choice_list
['ksals', '', 'alsdkfj', '3', '']
--
John Gordon A is for Amy, who fell down the stairs
[email protected] B is for Basil, assaulted by bears
-- Edward Gorey, "The Gashlycrumb Tinies"
--
http://mail.python.org/mailman/listinfo/python-list
How to get outer class name from an inner class?
I'm trying to come up with a scheme for organizing exceptions in my application. Currently, I'm using a base class which knows how to look up the text of a specific error in a database table, keyed on the error class name. The base class looks like this: class ApplicationException(Exception): """Base class for application-specific errors.""" def get_message(self): """Return the error message associated with this class name.""" class_name = self.__class__.__name__ return UserMessage.objects.get(key=class_name).text And then I define a bunch of subclasses which all have different names: class QuestionTooShortError(NetIDAppsError): """User entered a security question which is too short.""" pass class QuestionTooLongError(NetIDAppsError): """User entered a security question which is too long.""" pass This scheme works, but I'd like to make it more streamlined. Specifically, I'd like to group the classes underneath a parent class, like so: class Question(ApplicationException): class TooShort(ApplicationException): pass class TooLong(ApplicationException): pass This will make it easier in the future for organizing lots of sub-errors. My problem is this: the get_message() method in the base class only knows the current class name, i.e. "TooShort" or "TooLong". But that's not enough; I also need to know the outer class name, i.e. "Question.TooShort" or "Question.TooLong". How do I get the outer class name? Thanks, -- John Gordon A is for Amy, who fell down the stairs [email protected] B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: How to get outer class name from an inner class?
In John Gordon writes: > class QuestionTooShortError(NetIDAppsError): > """User entered a security question which is too short.""" > pass > class QuestionTooLongError(NetIDAppsError): > """User entered a security question which is too long.""" > pass Oops! These classes inherit from ApplicationException, not NetIDAppsError. -- John Gordon A is for Amy, who fell down the stairs [email protected] B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: Extracting DB schema (newbie Q)
In Steve Sawyer writes: > What I think I want to do is to construct a dictionary using the > column names as the index value, and a list containing the various > attributes (data type, lenghth, precision). If you're using just the column name as the dictionary key, make sure there are no duplicate column names among all your tables. > If this is a good approach, I ran into a problem populating the > dictionary as I couldn't seem to figure out how to make the update() > method work by passing the name property of the row object; I kept > getting a "keyword can't be an expression" error. The general syntax for assigning to a dictionary is: my_dictionary[key] = value What are you trying that isn't working? -- John Gordon A is for Amy, who fell down the stairs [email protected] B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: Carbon Event Manager (Carbon.CarbonEvt module) - working?
In msmucr writes: > Do I have something wrong or is it simply broken and unmaintained now? We have no idea if you did anything wrong, because you didn't tell us exactly what you did and exactly what error message you received. -- John Gordon A is for Amy, who fell down the stairs [email protected] B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: Object cleanup
In <[email protected]> "[email protected]" writes: > How do I force the memory for these soup objects to be freed? Have you tried deleting them, using the "del" command? -- John Gordon A is for Amy, who fell down the stairs [email protected] B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: Why does this leak memory?
In "Steve" writes: > gc: objects in each generation: 453 258 4553 > gc: collectable > gc: collectable > gc: collectable > gc: collectable <_Link 02713300> > gc: collectable > gc: collectable > gc: collectable > gc: collectable <_Link 02713350> > gc: collectable > gc: collectable > gc: collectable > gc: collectable <_Link 02713378> > gc: collectable > gc: collectable > gc: collectable > gc: collectable > gc: collectable <_Link 02713328> > gc: collectable > gc: collectable > gc: done, 19 unreachable, 0 uncollectable, 0.s elapsed. > The leaks can be removed by uncommenting both lines shown. > This strikes me as very odd behaviour. Can anyone explain it, or is it a > bug? I'm unfamiliar with gc output, but just glancing over it I don't see anything that looks like a leak. It reported that there were 19 objects which are unreachable and therefore are candidates for being collected. What makes you think there is a leak? -- John Gordon A is for Amy, who fell down the stairs [email protected] B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: Of Functions, Objects, and Methods-I NEED HELP PLEASE
In Cathy James writes: > b) I would like to append to my list, but my line dogs.dogAppend() is > giving a TypeError: > for i in enumerate (self.dogAppend()): > TypeError: 'list' object is not callable > def dogAppend(self): > self.dogAppend = [] You have a method and a list that are both called dogAppend. Try naming one of them something different. -- John Gordon A is for Amy, who fell down the stairs [email protected] B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
