[issue4613] Can't figure out where SyntaxError: can not delete variable 'x' referenced in nested scope us coming from in python shows no traceback
Albert Hopkins added the comment: You can close this one out. I don't even remember the use case anymore. -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue4613 ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
Re: print function and unwanted trailing space
On Wed, Sep 11, 2013, at 07:36 AM, Wayne Werner wrote: On Sat, 31 Aug 2013, candide wrote: # - for i in range(5): print(i, end=' ') # - The last ' ' is unwanted print() # - Then why not define end='' instead? I think the OP meant that ' ' is wanted up until the final item.. so something like for i in range(4): print(i, end=' ') print(4) or, better: print(' '.join(str(i) for i in range(5))) -- https://mail.python.org/mailman/listinfo/python-list
Re: Contact information for Jim Hugunin?
On Mon, Jul 22, 2013, at 05:33 PM, Larry Hastings wrote: Does anybody have an email address (or anything, really) for Jim Hugunin? He left Google in May and appears to have dropped off the face of the internet. Please email me privately. I swear I will use the information only for good and never for evil, Is that your definition of good and evil or mine? -- http://mail.python.org/mailman/listinfo/python-list
Re: Why is Ruby on Rails more popular than Django?
On Wed, Mar 6, 2013, at 02:16 PM, Tim Johnson wrote: I had problems getting django to work on my hostmonster account which is shared hosting and supports fast_cgi but not wsgi. I put that effort on hold for now, as it was just RD for me, but I would welcome you to take a look at this link where I opened a ticket. https://code.djangoproject.com/ticket/19970 From what I inferred there and from the django ML, the django community is indifferent to fastcgi and the shared hosting environment. As someone is new to shared hosting environments (I would mostly on dedicated servers) I get the impression that django is cutting itself out of some (if not a lot) of the market. I don't know about RoR tho I haven't any experience with shared hosting, so can't help you there. I did do some work with lighttpd and fast_cgi and the Django docs worked fine for that. But you're right. wsgi is pretty much the standard for web services in Python, like DB API is to relational database access. Ruby has Rack. Python has WSGI. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Newbie
Most of what gets hung in art galleries these days is far less visually pleasing than well-written code. +1 QOTW -- http://mail.python.org/mailman/listinfo/python-list
Re: Is Python venerable?
On Tue, Feb 19, 2013, at 11:10 PM, Gene Heskett wrote: [...] And even us old (78) farts are calling things Kewl now. 78??? Is that the year you were born or the years since you were born? -a -- http://mail.python.org/mailman/listinfo/python-list
Re: AttributeError: 'gr_hier_block2_sptr' object has no attribute 'set_callback'
On Thu, Feb 14, 2013, at 04:39 PM, Dave Angel wrote: [... snip] For those of us using text-based email, the program in this message is totally unreadable. This is a text mailing-list, so please put your email program in text mode, or you'll lose much of your audience. For those of us not using not using text-based email, it looked just as bad (if not worse). -- http://mail.python.org/mailman/listinfo/python-list
Re: how to call shell?
On Tue, Feb 12, 2013, at 12:12 AM, contro opinion wrote: import os os.system(i=3) 0 os.system(echo $i) 0 why i can't get the value of i ? Whenever you call os.system, a new shell is created and the command is run, system() then waits for the command to complete. You don't see i because your two system() calls are in two different processes: python import os python os.system('echo $$') 24294 0 python os.system('echo $$') 24295 0 However, ths (e.g.) would work: python os.system('i=3; echo $i') 3 0 HTH, -a -- http://mail.python.org/mailman/listinfo/python-list
Re: Is Python programming language?
On Fri, Feb 8, 2013, at 08:03 AM, gmspro wrote: Hello all, One said, Python is not programming language, rather scripting language, is that true? According to Wikipedia[1] a scripting languages are a subset of programming languages so it goes that any scripting language is, be definition, a programming language. It also says that scripting is not so much an attribute of the language, but an attribute of the interpreter, so one could say that C++ is a scripting language if one were to use a C++ interpreter. [1] http://en.wikipedia.org/wiki/Scripting_language -- http://mail.python.org/mailman/listinfo/python-list
Re: Best Practice Question
[...] By the way, did someone ever notice that r'\' fails ? I'm sure there's a reason for that... (python 2.5) Anyone knows ? r'\' SyntaxError: EOL while scanning single-quoted string Even in a raw string, string quotes can be escaped with a backslash, but the backslash remains in the string; for example, r\ is a valid string literal consisting of two characters: a backslash and a double quote; r\ is not a valid string literal (even a raw string cannot end in an odd number of backslashes). Specifically, a raw string cannot end in a single backslash (since the backslash would escape the following quote character). -- python docs -- http://mail.python.org/mailman/listinfo/python-list
Re: error in except
On Mon, Feb 4, 2013, at 04:49 PM, Rodrick Brown wrote: For the life of me I cant figure out why this exception is being thrown. How could I use pdb to debug this? $ python udp_local2.py server File udp_local2.py, line 36 except: ^ SyntaxError: invalid syntax #!/usr/bin/env python import random, socket, sys s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) MAX = 65535 PORT = 1060 if 2 = len(sys.argv) = 3 and sys.argv[1] == 'server': interface = sys.argv[2] if len(sys.argv) 2 else '' s.bind((interface, PORT)) print 'Listening at', s.getsockname() while True: data, address = s.recvfrom(MAX) if random.randint(0, 1): print 'The client at', address, 'says:', repr(data) s.sendto('Your data was %d bytes' % len(data), address) else: print 'Pretending to drop packet from', address elif len(sys.argv) == 3 and sys.argv[1] == 'client': hostname = sys.argv[2] s.connect((hostname, PORT)) print 'Client socket name is', s.getsockname() delay = 0.1 while True: s.send('This is another message') print 'Waiting up to', delay, 'seconds for a reply' s.settimeout(delay) try: data = s.recv(MAX) except socket.timeout: delay *= 2 if delay 2.0: raise RuntimeError('I think the server is down') except: raise else: break print 'The server says', repr(data) else: print sys.stderr, 'usage: %d server [interfae]' % sys.argv[0] print sys.stderr, ' or: %d client host' % sys.argv[0] sys.exit(2) -- http://mail.python.org/mailman/listinfo/python-list Your except statement is on the same level as if delay 2.0.. effectively: if delay 2.0 ... except: which is not valid syntax. Excepts go with try: blocks, not if: blocks. -- http://mail.python.org/mailman/listinfo/python-list
Re: sockobj.connect Errno 13 Permission denied
On Sat, Jan 26, 2013, at 08:52 AM, Joel Goldstick wrote: On Sat, Jan 26, 2013 at 8:47 AM, Joel Goldstick joel.goldst...@gmail.comwrote: On Sat, Jan 26, 2013 at 6:19 AM, nobody jupiter@gmail.com wrote: Hi, I have a client program Client.py which has a statement of sockobj.connect(), the port number 6 is used, so no problem from port permission. I am puzzled because I can run Client.py from command line in my user account or apache user account without any problems. But if I run it from a web page http://localhost/client.php, the client.php called exec(Client.py), Check the arguments to exec. I think it has to be an open file object. then it got an exception of sockobj.connect Errno 13 Permission denied. Why it can run from command line, but cannot make connection from a web file? Appreciate any tips and clues. Thank you. Kind regards. Maybe I spoke too soon. You should probably be asking in a php forum since what you are doing is running a php exec. If you are actually getting a python error you should show the code and the traceback so that someone can look at your code. In either case (py and php) it looks like exec needs either a string of executable text or (in py case) an open file handle. So the code you describe isn't really what you are running Also your php/apache config needs to be set up to enable execs (I think it's off by the default). Either way it's a PHP question, not a Python question. -- http://mail.python.org/mailman/listinfo/python-list
Re: When is overriding __getattr__ is useful?
On Mon, Jan 7, 2013, at 10:54 AM, Rodrick Brown wrote: Can someone provide an example why one would want to override __getattr__ and __getattribute__ in a class? They're good for cases when you want to provide an attribute-like quality but you don't know the attribute in advance. For example, the xmlrpclib uses __getattr__ to expose XML-RPC methods over the wire when it doesn't necessarily know what methods are exposed by the service. This allows you do simply do service.method(*args) And have the method seem like it's just a local method on an object. There are countless other examples. But that's just one that can be found in the standard library. -- http://mail.python.org/mailman/listinfo/python-list
Re: Tarfile and usernames
On Sun, Dec 30, 2012, at 01:57 PM, Nicholas Cole wrote: Dear List, I'm hoping to use the tarfile module in the standard library to move some files between computers. I can't see documented anywhere what this library does with userids and groupids. I can't guarantee that the computers involved will have the same users and groups, and would like the archives to be extracted so that the files are all owned by the extracting user. Essentially, I do *not* with to preserve the owner and groups specified in the archives. Each member in the tar file has misc. metadata associated with it, which can be retrieved with the get_info() method. You can add/modify this metadata if creating a TarFile. However, it should be stated that by default (on *nix anyway) if the user is not root then user/groups are assigned to the user exctracting the file (because only root can assign userids/non-member-groups). The TarFile extract*() methods pretty much inherit the same behavior as the *nix tar command. So if you are extracting as a non-root user, you should expect the same behavoir. If you are extracting as root but don't want to change user/groups may have to extract it manually or create your own class by inheriting TarFile and overriding the .chown() method. -a -- http://mail.python.org/mailman/listinfo/python-list
Re: who can give me some practical tutorials on django 1.4 or 1.5?
On Sun, 2012-11-04 at 13:29 +0800, Levi Nie wrote: Who can give me some practical tutorials on django 1.4 or 1.5? Thank you. Is the official[1] tutorial not practical enough? [1] https://docs.djangoproject.com/en/1.4/intro/tutorial01/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Fastest web framework
On Sun, 2012-09-23 at 12:19 +0300, Andriy Kornatskyy wrote: I have run recently a benchmark of a trivial 'hello world' application for various python web frameworks (bottle, django, flask, pyramid, web.py, wheezy.web) hosted in uWSGI/cpython2.7 and gunicorn/pypy1.9... you might find it interesting: http://mindref.blogspot.com/2012/09/python-fastest-web-framework.html Comments or suggestions are welcome. The thing I don't like about these benchmarks is.. they tell you which framework is best for writing a trivial 'hello world' application. But no one writes trivial 'hello world' applications. A framework/programming language/software package/what-have-you. Can be really fast for trivial stuff, but perform much less favorably when performing real-world tasks. It's kind of the same argument that's used when people say X computer boots faster than Y computer. That's nice and all, but I spend much more of my time *using* my computer than *booting* it, so it doesn't give me a good picture of how the computers perform. This is why most good benchmarks run a series various tests based on real-world use cases. -a -- http://mail.python.org/mailman/listinfo/python-list
Re: 'indent'ing Python in windows bat
On Tue, 2012-09-18 at 22:12 -0600, Jason Friedman wrote: I'm converting windows bat files little by little to Python 3 as I find time and learn Python. The most efficient method for some lines is to call Python like: python -c import sys; sys.exit(3) How do I indent if I have something like: if (sR=='Cope'): sys.exit(1) elif (sR=='Perform') sys.exit(2) else sys.exit(3) Some months ago I posted what I think is a similar question in the Unix world: I wanted to call a small portion of Python from within a Bash script. Someone on this list answered (for Bash): #!/bin/bash command1 command2 python -c if True: import module if condition: do_this else: do_that command4 # end code A better way (in *nix) would be, e.g.: #!/bin/sh read -p 'Enter a number ' count python EOF print 'Odd numbers between 0 and ${count}' for i in range(${count}): if i % 2: print i EOF Horribly bad example, but you get the idea. -- http://mail.python.org/mailman/listinfo/python-list
Re: subtle error slows code by 10x (builtin sum()) - replace builtin sum without using import?
On Friday, July 1 at 19:17 (-0700), bdb112 said: Question: Can I replace the builtin sum function globally for test purposes so that my large set of codes uses the replacement? The replacement would simply issue warnings.warn() if it detected an ndarray argument, then call the original sum I could then find the offending code and use the appropriate import to get numpy.sum You shouldn't do this, but you could use the __builtins__ module e.g. __builtins__.sum = numpy.sum # bad -- http://mail.python.org/mailman/listinfo/python-list
Re: changing current dir and executing a shell script
On Sat, 2011-05-28 at 09:41 +0200, Peter Otten wrote: You don't want to do this because cd is a built-in shell command, and subprocess does not execute within a shell (by default). The problem is not that cd is built-in, but that there is no shell at all. You can change that with shell=True: This is exactly what I said, but using different words. -- http://mail.python.org/mailman/listinfo/python-list
Re: float(nan) in set or as key
On Sun, 2011-05-29 at 00:41 +0100, MRAB wrote: Here's a curiosity. float(nan) can occur multiple times in a set or as a key in a dict: {float(nan), float(nan)} {nan, nan} These two nans are not equal (they are two different nans) except that sometimes it can't: nan = float(nan) {nan, nan} {nan} This is the same nan, so it is equal to itself. Two nans are not equal in the manner that 1.0 and 1.0 are equal: 1.0 == 1.0 True float(nan) == float(nan) False I can't cite this in a spec, but it makes sense (to me) that two things which are nan are not necessarily the same nan. -- http://mail.python.org/mailman/listinfo/python-list
Re: changing current dir and executing a shell script
On Fri, 2011-05-27 at 14:25 -0700, suresh wrote: Hi, I want to execute the following command line stuff from inside python. $cd directory $./executable I tried the following but I get errors import subprocess subprocess.check_call('cd dir_name;./executable') Due to filename path issues, I cannot try this version. subprocess.check_call('./dir_name/executable') You don't want to do this because cd is a built-in shell command, and subprocess does not execute within a shell (by default). The proper way to do this is to use the cwd keyword argument to subprocess calls, i.e.: subprocess.check_call(('/path/to/exec',), cwd=/path/to/dir) -a -- http://mail.python.org/mailman/listinfo/python-list
Re: FW: help please
On Tue, 2011-05-17 at 21:46 -0300, Gabriel Genellina wrote: En Tue, 17 May 2011 16:48:29 -0300, Albert Hopkins mar...@letterboxes.org escribió: On Tue, 2011-05-17 at 10:18 -0600, Littlefield, Tyler wrote: Not to be pedantic or anything, and I may not be able to help regardless, but it looks like your space key is fixed, and I don't really care to pick through and try to play hangman with your message. I actually, at first glance, thought it was spam, ignored it, and was wondering why people were replying to it :| I can't remember exactly in which release 'perfect English skills' were added to Python runtime requirements, could you please refresh my memory? I can't speak for Tyler (I assume your message was meant for him) but as for myself: I saw a glob of practically unreadable text and simply passed it off as spam, concluding that any well-intentioned, moderately intelligent human being wouldn't have intentionally posted such a monstrosity and actually expected an intelligent response. I'm guessing Tyler's message was to help you so that your messages don't continue to be ignored by people who may otherwise be of assistance. -- http://mail.python.org/mailman/listinfo/python-list
Re: FW: help please
On Wed, 2011-05-18 at 13:39 +0100, Stuart MacKay wrote: If you were required to answer the question then asking the poster to phrase it better is going to help solve the issue faster but for a mailing list like this simply ignore it. Which is what I've done. -- http://mail.python.org/mailman/listinfo/python-list
Re: How To Make Fast Money Legally
On Wed, 2011-05-18 at 15:48 -0400, D'Arcy J.M. Cain wrote: On Wed, 18 May 2011 12:06:07 -0700 (PDT) tmac641...@yahoo.com tmac641...@yahoo.com wrote: HOW TO MAKE EASY MONEY FAST AND LEGALLY Wow! Was this stuck in someone's mail queue since 1992? Me too! -- http://mail.python.org/mailman/listinfo/python-list
Re: FW: help please
On Tue, 2011-05-17 at 10:18 -0600, Littlefield, Tyler wrote: Not to be pedantic or anything, and I may not be able to help regardless, but it looks like your space key is fixed, and I don't really care to pick through and try to play hangman with your message. I actually, at first glance, thought it was spam, ignored it, and was wondering why people were replying to it :| -a -- http://mail.python.org/mailman/listinfo/python-list
Re: if statement multiple or
On Fri, 2011-05-06 at 13:47 +0300, Lutfi Oduncuoglu wrote: Hi, I am trying to write a script and I realised that I need to use something like if ('a' or 'b' or 'c') not in line: print line The expression: ('a' or 'b' or 'c') evaluates to True True not in line Is probably not what you intended. -- http://mail.python.org/mailman/listinfo/python-list
Re: if statement multiple or
Correction: ('a' or 'b' or 'c') evaluates to 'a' -- http://mail.python.org/mailman/listinfo/python-list
Re: PIL: The _imaging C module is not installed
On Thu, 2011-05-05 at 15:35 +0200, Nico Grubert wrote: Hi there I am having trouble to install PIL 1.1.7 on CentOS. I read and followed the instructions from http://effbot.org/zone/pil-imaging-not-installed.htm However, I still get the The _imaging C module is not installed error if I run the selftest: $ python selftest.py *** The _imaging C module is not installed Here is what I have tested so far: 1.) $ python -v ... import Image ... dlopen(/usr/local/lib/python2.4/site-packages/PIL/_imaging.so, 2); import _imaging # dynamically loaded from /usr/local/lib/python2.4/site-packages/PIL/_imaging.so ... I had this problem earlier this week. Assuming that you pip-installed or similar. PIL will compile and install if you don't have some development libraries and then simply not work or not work up to full steam when used. To avoid this, you need to install the appropriate libraries, among which are: libjpeg-devel freetype-devel libpng-devel Probably others as well. HTH, -a -- http://mail.python.org/mailman/listinfo/python-list
Re: PIL: The _imaging C module is not installed
Oh I forgot to say, after installing these libraries, you will need to re-compile (install) PIL. -a -- http://mail.python.org/mailman/listinfo/python-list
Re: PIL: The _imaging C module is not installed
On Fri, 2011-05-06 at 01:45 +0200, Michel Claveau - MVP wrote: Hi! you need to install the appropriate libraries, among which are: libjpeg-devel freetype-devel libpng-devel OK, but where can I find it? I want use PIL with Python under Windows, and I can't compile C's sources. Should I replace PIL by ImageMagick? The OP was about CentOS. I have no idea about Windows. -- http://mail.python.org/mailman/listinfo/python-list
Re: Restarting a daemon
On Tue, 2011-04-26 at 06:13 -0600, Jeffrey Barish wrote: Not exactly a Python question, but I thought I would start here. I have a server that runs as a daemon. I can restart the server manually with the command myserver restart This command starts a new myserver which first looks up the pid for the one that is running and sends it a terminate signal. The new one then daemonizes itself. I want the server to be able to restart itself. Will it work to have myserver issue myserver restart using os.system? I fear that the new myserver, which will be running in a subshell, will terminate the subshell along with the old myserver when it sends the terminate signal to the old myserver. If so, what is the correct way to restart the daemon? Will it work to run the restart command in a subprocess rather than a subshell or will a subprocess also terminate when its parent terminates? You should look into tools like daemon-tools, or similar. It already solves this (and many other) problems. -a -- http://mail.python.org/mailman/listinfo/python-list
Re: How to concatenate unicode strings ???
On Tue, 2011-04-26 at 17:58 +0200, Ariel wrote: Hi everybody, how could I concatenate unicode strings ??? What I want to do is this: unicode('this an example language ') + unicode('español') but I get an: Traceback (most recent call last): File console, line 1, in module UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 11: ordinal not in range(128) How could I concatenate unicode strings ??? Your problem isn't with concationation. Your problem is with: unicode('español') That is your are passing a non-unicode string to the unicode type and, it seems the default encoding on your system is ASCII, but ñ is not valid ASCII encoding. So you can do one of two things: * Use a unicode literal, e.g. u'español' * pass whatever encoding you are actually using in your byte string, e.g. unicode('español', 'utf8') If you are writing this in a module and you want to use unicode literals, you should put something similar at the top of the file: # -*- encoding: utf-8 -*- HTH, -a -- http://mail.python.org/mailman/listinfo/python-list
[issue4608] urllib.request.urlopen does not return an iterable object
Albert Hopkins mar...@python.net added the comment: This issue appears to persist when the protocol used is FTP: root@tp-db $ cat test.py from urllib.request import urlopen for line in urlopen('ftp://gentoo.osuosl.org/pub/gentoo/releases/'): print(line) break root@tp-db $ python3.2 test.py Traceback (most recent call last): File test.py, line 2, in module for line in urlopen('ftp://gentoo.osuosl.org/pub/gentoo/releases/'): TypeError: 'addinfourl' object is not iterable -- nosy: +marduk ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue4608 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue4608] urllib.request.urlopen does not return an iterable object
Albert Hopkins mar...@python.net added the comment: Oops, previous example was a directory, but it's the same if the url points to a ftp file. -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue4608 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
Re: Python 3 encoding question: Read a filename from stdin, subsequently open that filename
On Tue, 2010-11-30 at 11:52 +0100, Peter Otten wrote: Dan Stromberg wrote: I've got a couple of programs that read filenames from stdin, and then open those files and do things with them. These programs sort of do the *ix xargs thing, without requiring xargs. In Python 2, these work well. Irrespective of how filenames are encoded, things are opened OK, because it's all just a stream of single byte characters. I think you're wrong. The filenames' encoding as they are read from stdin must be the same as the encoding used by the file system. If the file system expects UTF-8 and you feed it ISO-8859-1 you'll run into errors. I think this is wrong. In Unix there is no concept of filename encoding. Filenames can have any arbitrary set of bytes (except '/' and '\0'). But the filesystem itself neither knows nor cares about encoding. You always have to know either (a) both the file system's and stdin's actual encoding, or (b) that both encodings are the same. If this is true, then I think that it is wrong to do in Python3. Any language should be able to deal with the filenames that the host OS allows. Anyway, going on with the OP.. can you open stdin so that you can accept arbitrary bytes instead of strings and then open using the bytes as the filename? I don't have that much experience with Python3 to say for sure. -a -- http://mail.python.org/mailman/listinfo/python-list
Re: Python 3 encoding question: Read a filename from stdin, subsequently open that filename
On Wed, 2010-12-01 at 02:14 +, MRAB wrote: If the filenames are to be shown to a user then there needs to be a mapping between bytes and glyphs. That's an encoding. If different users use different encodings then exchange of textual data becomes difficult. That's presentation, that's separate. Indeed, I have my user encoding set to UTF-8, and if there is a filename that's not valid utf-8 then my GUI (GNOME will show (invalid encoding) and even allow me to rename it and my shell (bash) will show '?' next to the invalid characters (and make it a little more challenging to rename ;)). And I can freely copy these invalid files across different (Unix) systems, because the OS doesn't care about encoding. But that's completely different from the actual name of the file. Unix doesn't care about presentation in filenames. It just cares about the data. There are not glyphs in Unix, only in the UI that runs on top of it. Or to put it another way, Unix's filename encoding is RAW-DATA. It's not textual data. The fact that most filenames contain mainly human-readable text is a convenient convention, but not required or enforced by the OS. That's where encodings which can be used globally come in. By the time Python 4 is released I'd be surprised if Unix hadn't standardised on a single encoding like UTF-8. I have serious doubts about that. At least in the Linux world the kernel wants to stay out of encoding debates (except where it has to like Window filesystems). But the point is that: The world does not revolve around Python. Unix filenames have been encoding-agnostic long before Python was around. If Python3 does not support this then it's a regression on Python's part. -- http://mail.python.org/mailman/listinfo/python-list
Re: Why flat is better than nested?
On Tue, 2010-10-26 at 09:45 -0700, John Nagle wrote: On 10/25/2010 6:34 AM, Alex Willmer wrote: On Oct 25, 11:07 am, kjno.em...@please.post wrote: In The Zen of Python, one of the maxims is flat is better than nested? Why? Can anyone give me a concrete example that illustrates this point? I take this as a reference to the layout of the Python standard library and other packages i.e. it's better to have a module hierarchy of depth 1 or 2 and many top level items, than a depth of 5+ and only a few top level items. For instance import re2 import sqlite3 import logging import something_thirdparty vs import java.util.regex import java.sql import java.util.logging As in Python 2: import urllib Python 3: import urllib.request, urllib.parse, urllib.error http://diveintopython3.org/porting-code-to-python-3-with-2to3.html My favorite is always: from django.contrib.auth.models import User # I know, not std lib -- http://mail.python.org/mailman/listinfo/python-list
Re: PyCharm
On Tue, 2010-10-19 at 10:05 -0700, CoffeeKid wrote: Your video is childish When you have someone called Kid calling you childish... that's pretty low. -- http://mail.python.org/mailman/listinfo/python-list
Re: Fastest way to detect a non-ASCII character in a list of strings.
On Sun, 2010-10-17 at 14:59 -0500, Dun Peal wrote: `all_ascii(L)` is a function that accepts a list of strings L, and returns True if all of those strings contain only ASCII chars, False otherwise. What's the fastest way to implement `all_ascii(L)`? My ideas so far are: 1. Match against a regexp with a character range: `[ -~]` 2. Use s.decode('ascii') 3. `return all(31 ord(c) 127 for s in L for c in s)` Any other ideas? Which one do you think will be fastest? Will reply with final benchmarks and implementations if there's any interest. Thanks, D There seems to be some confusion over what is meant by ASCII. So I just assume it means 7-bit character and propose: all([True if not x else x[0] = '\x00' and x[-1] = '\x7f' for x in [sorted(set(y)) for y in L]]) That also kinda assumes and empty list and empty strings are considered true. -- http://mail.python.org/mailman/listinfo/python-list
Re: Boolean value of generators
On Fri, 2010-10-15 at 14:54 +, Grant Edwards wrote: so you could test for emptiness, look ahead at the next item without consuming it, etc. And what happens when the generator is doing things like executing database transactions? You should also add prediction to the caching. This will improve performance even more! -a -- http://mail.python.org/mailman/listinfo/python-list
Re: Boolean value of generators
On Thu, 2010-10-14 at 10:16 +0100, Tony wrote: I have been using generators for the first time and wanted to check for an empty result. Naively I assumed that generators would give appopriate boolean values. For example def xx(): l = [] for x in l: yield x y = xx() bool(y) As people have already mentioned, generators are objects and objects (usually) evaluate to True. There may be times, however, that a generator may know that it doesn't/isn't/won't generate any values, and so you may be able to override boolean evaluation. Consider this example: class DaysSince(object): def __init__(self, day): self.day = day self.today = datetime.date.today() def __nonzero__(self): if self.day self.today: return False return True def __iter__(self): one_day = datetime.timedelta(1) new_day = self.day while True: new_day = new_day + one_day if new_day = self.today: yield new_day else: break g1 = DaysSince(datetime.date(2010, 10, 10)) print bool(g1) for day in g1: print day g2 = DaysSince(datetime.date(2011, 10, 10)) print bool(g2) for day in g2: print day True 2010-10-11 2010-10-12 2010-10-13 2010-10-14 False -- http://mail.python.org/mailman/listinfo/python-list
Re: How to find free resident memory in Linux using python
On Sat, 2010-10-02 at 07:06 -0700, Sandy wrote: Hi all, I want to find how much free memory (RAM) is available in my system using python. I tried psutil, parsing /proc/meminfo, top output etc but not satisfied. For example my gnome-system-monitor gui shows I am using 1GB (25%) of my RAM while /proc/meminfo, top, psutil says around 2GB is used. Is there anyway I can get the correct availble memory, may be adding cache, buffers etc to free memory in these and get some value that matches with the gnome-system-monitor gui? For example 'top' says: Mem: 3995048k total, 2231924k used, 1763124k free,43480k buffers while gnome-system-monitor gui shows I am using 1GB (25%) gnome-system-monitor subtracts buffer/cache usage from total memory used. Those numbrs should (nearly match). For example on one system g-s-m shows: 356.3 MB used and free shows $ free -m total used free sharedbufferscached Mem: 3801782 3018 0 31 395 -/+ buffers/cache:356 3445 Swap: 4094 0 4094 ... So g-s-m shows the used from the second row while top is using the numbers from the first row. Six of one, half dozen of the other. It depends on whether you want to consider memory the kernel allocates to buffers/cache as used memory. All these utilities do read the contents in /proc/meminfo so you can consider that the definitive source of information. -- http://mail.python.org/mailman/listinfo/python-list
Re: SendKeys and Python 2.7
On Thu, 2010-09-09 at 07:07 -0300, Jakson A. Aquino wrote: Vim needs python 2.7 From where do you base this assertion? I have been using vim 7.3 (with embedded python) with python 2.6 pretty much since it has been released. :version VIM - Vi IMproved 7.3 (2010 Aug 15, compiled Aug 29 2010 07:21:44) [...] :python import sys; print sys.version 2.6.5 (release26-maint, Aug 28 2010, 21:57:54) [GCC 4.4.4] -- http://mail.python.org/mailman/listinfo/python-list
Re: Printing the name of a variable
On Thu, 2010-09-09 at 12:43 -0700, Stephen Boulet wrote: Does an arbitrary variable carry an attribute describing the text in its name? I'm looking for something along the lines of: x = 10 print x.name 'x' Perhaps the x.__getattribute__ method? Thanks. Variables are not objects and so they have no attributes. You can't really de-reference the object being referenced as it can potentially contain multiple references, but an innacurate way of doing this would be, e.g. x = [1, 2, 3] y = x g = globals() varnames = [i for i in g if g[i] is x] ['x', 'y'] But this cries the question: why do you want to do this? And usually that question is asked when someone thinks that a: you shouldn't need to do this and b: whatever the desired effect there is probably a better way of accomplishing it. -- http://mail.python.org/mailman/listinfo/python-list
Re: The Samurai Principle
On Mon, 2010-09-06 at 20:48 -0700, Phlip wrote: Pythonistas: The Samurai Principle says to return victorious, or not at all. This is why django.db wisely throws an exception, instead of simply returning None, if it encounters a record not found. How does that compare to, say, the Kamikaze Principle? ;) -a -- http://mail.python.org/mailman/listinfo/python-list
Re: Minimum and Maximum of a list containing floating point numbers
On Mon, 2010-09-06 at 17:37 -0700, ceycey wrote: I have a list like ['1.1881', '1.1881', '1.1881', '1.1881', '1.1881', '1.1881', '1.1881', '1.1881', '1.1881', '1.1881', '1.7689', '1.7689', '3.4225', '7.7284', '10.24', '9.0601', '9.0601', '9.0601', '9.0601', '9.0601']. What I want to do is to find minimum and maximum number in this list. I used min function, s = ['1.1881', '1.1881', '1.1881', '1.1881', '1.1881', '1.1881', '1.1881', '1.1881', '1.1881', '1.1881', '1.7689', '1.7689', '3.4225', '7.7284', '10.24', '9.0601', '9.0601', '9.0601', '9.0601', '9.0601'] print min(s) print max(s) these gives me 1.181 9.0601 maximum value is wrong. It must be 10.24. You are not comparing a list of floats but a list of strings. I know why max function gives wrong number. Because max function processed elements of list as strings. How can I convert the elements of list to float so max function finds the correct answer. min/max in these cases are returning strings as well. So the fact remains that the max function is not giving you a number at all, but a string, and as such is correct. String comparison is not identical to numerical comparison. But to answer your question: s = ['1.1881', '1.1881', '1.1881', '1.1881', '1.1881', '1.1881', ... '1.1881', '1.1881', '1.1881', '1.1881', '1.7689', ... '1.7689', '3.4225', '7.7284', '10.24', '9.0601', '9.0601', '9.0601', ... '9.0601', '9.0601'] [type(x) for x in s] [type 'str', type 'str', type 'str', type 'str', type 'str', type 'str', type 'str', type 'str', type 'str', type 'str', type 'str', type 'str', type 'str', type 'str', type 'str', type 'str', type 'str', type 'str', type 'str', type 'str'] type(max(s)) type 'str' t = [float(x) for x in s] [type(x) for x in t] [type 'float', type 'float', type 'float', type 'float', type 'float', type 'float', type 'float', type 'float', type 'float', type 'float', type 'float', type 'float', type 'float', type 'float', type 'float', type 'float', type 'float', type 'float', type 'float', type 'float'] min(t) 1.1880 max(t) 10.24 type(max(s)) type 'str' type(max(t)) type 'float' -- http://mail.python.org/mailman/listinfo/python-list
Re: Python [repair_cycorder_mov.py]
On Sun, 2010-09-05 at 14:00 +, Steven D'Aprano wrote: By the way, there's no need to send three messages in 10 minutes asking the same question, and adding FORM METHOD links to your post will probably just get it flagged as spam by many people. Apparently it has, as I only got this response. -- http://mail.python.org/mailman/listinfo/python-list
Re: Saving (unusual) linux filenames
On Tue, 2010-08-31 at 16:49 +0200, amfr...@web.de wrote: i have a script that reads and writes linux paths in a file. I save the path (as unicode) with 2 other variables. I save them seperated by , and the packets by newlines. So my file looks like this: path1, var1A, var1B path2, var2A, var2B path3, var3A, var3B this works for normal paths but as soon as i have a path that does include a , it breaks. The problem now is that (afaik) linux allows every char (aside from / and null) to be used in filenames. The only solution i can think of is using null as a seperator, but there have to a cleaner version ? Why is your impression that the null character is dirty? E.g. that's how find|xargs etc. usually work. Another alternative would be if you gaurantee that your varn's don't have commas then put the path last. But that doesn't account for filenames containing newlines. Another alternative would be to wrap with some kind of serialization library. But really, what's so dirty about null? -- http://mail.python.org/mailman/listinfo/python-list
Re: triangle python user's group?
On Mon, 2010-08-30 at 12:38 -0700, Tim Arnold wrote: Hi, Is there a python users group in the Research Triangle Park area (North Carolina, USA)? Google triangle python user's group -- http://mail.python.org/mailman/listinfo/python-list
Re: subprocess.Popen calling httpd reload never finishes
On Wed, 2010-08-18 at 06:58 -0700, Nan wrote: Ah, I'd been told that there would be no conflict, and that this was just reloading the configuration, not restarting Apache. I do need the web app to instruct Apache to reload because just before this it's creating new VirtualHosts that need to be recognized. Is there a better way to do this (e.g. to say start doing this once I'm finished)? I'm getting a status code and output from the call before the Django script stops executing... Is there a way to stop waiting for the process to complete once I have those? I have a wireless router with a built in web server. Sometimes it needs to reload it's config. Basically what it's doing is rebooting the entire router (I can see this if I'm actuall watching the router). All it is doing, I'm pretty sure, is calling some program that forks another process and then exits the main program. The forked process then reboots the router. Meanwhile before that happens the web server sends a response. Basically in the response it sends an HTTP Refresh with x number of seconds. Presumably x is longer than the time it requires for the router to reboot. The router reboots, the browser refreshes and viola. You probably need to so something similar in that your request calls a program that forks off and restarts apaches. It should probably not do so immediately so that your request has time to send a response with a refresh header (but that shouldn't take long). After a second or so, apache will have restarted and the browser will have refreshed. so (untested): def reload(request): subprocess.call(['my_apache_reloader']) # this should fork and exit response = HttpResponse() response['Refresh']='3; url=%s' % reverse(home) # chk back in 3 secs return response BTW There is a Django mailing list where this might be more appropriate to discuss. -a -- http://mail.python.org/mailman/listinfo/python-list
Re: subprocess.Popen calling httpd reload never finishes
On Tue, 2010-08-17 at 12:55 -0700, Nan wrote: Hi folks -- I have a Python script running under Apache/mod_wsgi that needs to reload Apache configs as part of its operation. The script continues to execute after the subprocess.Popen call. The communicate() method returns the correct text (Reloading httpd: [ OK ]), and I get a returncode of 0. But the python script (Django) that calls Popen never seems to complete (by returning an HTTP response. Any other Popen call I've tried exits properly. Here's some sample code: args = ['sudo /etc/init.d/httpd reload'] proc = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True, close_fds=True) (stdout_txt, stderr_txt) = proc.communicate() proc.wait() logging.debug('%d %shr /%s' % (proc.returncode, stdout_txt, stderr_txt)) logging.debug('still executing') return HttpResponse('done') The logging statements are output, but the script doesn't exit. If you substitute sudo ls -l or sudo /etc/init.d/httpd configtest for sudo /etc/init.d/httpd reload, the exits properly. Any idea what I might be doing wrong? Thanks! Django runs inside apache. It's kinda weird to have an apache process restart itself and expect it to return to the caller. If the init script does like mine, reload executes apachectl -k graceful What that instructs apache to do is to restart, but only kill the process(es) when there are no more connections. So apache is waiting for your connection to close, but you are inside an HTTP request waiting for apache to restart. So you have a race condition here. It's not advisable to have apache kill itself and expect it to send a status back to you telling you it's dead. See the apache docs[1] for a better explanation. http://httpd.apache.org/docs/2.0/stopping.html#graceful -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Script Cannot Write to Directory
On Tue, 2010-08-03 at 21:01 -0700, Chris Brauchli wrote: Hi, I am writing a script that, at one point, copies a file from directory A to directory B. Directory B can only be written to by root, but the script is always called with sudo, so this shouldn't be an issue, but it is. I have tried using shutil.copy() and calling sudo cp with os.popen to no avail. I cannot get the script to copy a file to directory B. The strange thing is if I run the python interpreter (as sudo) and type in shutil.copy it works. It also works if I try to copy the file to a less protected directory. It only happens when I try to copy a file to directory B from a python script. Any ideas why this is happening? If more information is needed or something isn't clear let me know. Thanks for helping. Chris Code? Traceback? -- http://mail.python.org/mailman/listinfo/python-list
Re: Why is python not written in C++ ?
On Mon, 2010-08-02 at 01:08 +0200, candide wrote: Python is an object oriented langage (OOL). The Python main implementation is written in pure and old C90. Is it for historical reasons? C is not an OOL and C++ strongly is. I wonder if it wouldn't be more suitable to implement an OOL with another one. Has it ever been planned to rewrite in C++ the historical implementation (of course in an object oriented design) ? Disclaimer: I am neither a C nor C++ programmer. In fact I can barely even program in Python ;-) I would propose that in fact most programming languages are implemented in C. Sun's (Oracle's) Java compiler and runtime are written in ANSI C. The core of the Gnu Compiler Collection (which includes C++ and Objective-C compilers) is written in C. The official Ruby is implemented in C. The Squeak Smalltalk implementation uses C instead of C++. I can't even think of a programming language that is implemented in C++ (maybe C++ is). C seems to be a good, portable language for writing interpreters and compilers. But I wonder if someone has/has tried to write a programming language in C++ and what were their experiences. -- http://mail.python.org/mailman/listinfo/python-list
Re: measuring a function time
On Fri, 2010-07-30 at 14:28 +0200, Hrvoje Niksic wrote: Steven D'Aprano st...@remove-this-cybersource.com.au writes: On Thu, 29 Jul 2010 14:42:58 +0200, Matteo Landi wrote: This should be enough import time tic = time.time() function() toc = time.time() print toc - tic You're typing that in the interactive interpreter, which means the timer is counting the seconds while you're typing subsequent commands. At the very least, you need to put that code into a function. Or, trivially improved as follows: t0 = time.time(); function(); t1 = time.time() print t1 - t0 I'll just throw this out. I sometimes use a decorator to keep track of a functions execution times: def timed_function(f): Function decorator that records the execution time of a function import time def funct(*args, **kwargs): __starttime = time.time() result = f(*args, **kwargs) __endtime = time.time() funct.runtime = __endtime - __starttime return result return funct Then from goodies import timed_function from time import sleep @timed_function ... def test(n): ... sleep(n) ... test(4) test.runtime 4.003864049911499 Works for simple stuff anyway. -a -- http://mail.python.org/mailman/listinfo/python-list
Re: Possible to include \n chars in doctest code samples or output?
On Fri, 2010-07-16 at 01:26 -0400, pyt...@bdurham.com wrote: I understand what you're saying, but I'm struggling with how to represent the following strings in doctest code and doctest results. No matter what combination of backslashes or raw strings I use, I am unable to find a way to code the following. encode( ', \, \t, \n' ) '\, \\, \\t, \\n' encode(', '.join([chr(i) for i in (34, 92, 9, 10)])) But, as another poster already said, if the limitations of doctests are causing you to struggle, then don't use doctests and instead use real tests. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python 2.4.2 Installation error
On Thu, 2010-07-01 at 21:51 +0530, Dhilip S wrote: Hello Everyone.. I'm using Ubuntu 10.04, i try to install Python 2.4.2 Python 2.4.3 got error message while doing make command. anybody can tell tell, How to overcome this error this error apparently did not get included in your post. -- http://mail.python.org/mailman/listinfo/python-list
Re: Scan until random delimiter.
On Sun, 2010-06-27 at 22:41 +0200, Laurent Verweijen wrote: In contrast to java or c python seems not be able to use a random delimiter. In java, you can do: Code: import java.util.Scanner Scanner sc = new Scanner(System.in).useSeperator( ) int a = sc.nextInt() But in python there seems to be no other option then waiting until you see a newline. I wrote a script which should allow more freedom. Code: #!/usr/bin/python def readtoken(source=None, delim= \n\t\r): if source is None: from sys import stdin source = stdin r = [] c = delim + while c not in delim: c = source.read(1) r.append(c) return .join(r) if __name__ == __main__: for _ in range(5): print(readtoken()) I found this recipe (though not tried it): http://code.activestate.com/recipes/134892/ -- http://mail.python.org/mailman/listinfo/python-list
Re: I strongly dislike Python 3
Python 3 is, by design, not 100% backwards compatible with Python 2. Not that I'm completely happy with everything in Python 3 but, in it's defense, discussion of Python 3 has been ongoing for years, almost as long as the existence of Python 2. So the discussion of what went into Python 3 is so old, it's pretty much moot to start talking about it now. Things change and we learn to adapt and evolve. Or we don't. -a -- http://mail.python.org/mailman/listinfo/python-list
Re: Import fails (newbie)
On Thu, 2010-06-17 at 12:04 -0700, mhorlick wrote: Hello, I'm a newbie and I have a small problem. After invoking IDLE -- Python 3.1.2 (r312:79149, Mar 21 2010, 00:41:52) [MSC v.1500 32 bit (Intel)] on win32 Type copyright, credits or license() for more information. import os,glob os.chdir('D:/Python_Programs') print(os.getcwd()) D:\Python_Programs print(glob.glob('*.*')) ['humansize.py', 'humansize.pyc'] import humansize Traceback (most recent call last): File pyshell#5, line 1, in module import humansize ImportError: No module named humansize In a DOS command window I have no problems with the program: Directory of D:\Python_Programs 17/06/2010 01:56 PMDIR . 17/06/2010 01:56 PMDIR .. 17/06/2010 02:53 PM 1,266 humansize.py 17/06/2010 01:56 PM 1,315 humansize.pyc 2 File(s) 2,581 bytes 2 Dir(s) 104,122,085,376 bytes free D:\Python_Programsc:\python31\python humansize.py 1.0 TB 931.3 GiB This 'humansize.py' program I got from the book 'Dive Into Python 3'. I don't know if you need to know the source. Can someone explain why the 'import' fails? os.chdir() is not the same as running python from inside the Python_programs directory. The correct way of doing this is to put Python_Programs in your path, e.g.: import sys sys.path.insert(0, 'D:/Python_Programs') import humansize -- http://mail.python.org/mailman/listinfo/python-list
Re: Challenging Job Opportunity for a C# Architect/ Developer
On Tue, 2010-06-01 at 19:44 -0700, rzzzwilson wrote: http://www.catb.org/~esr/faqs/smart-questions.html#forum werd. -- http://mail.python.org/mailman/listinfo/python-list
Re: max time wait for a function
On Tue, 2010-05-18 at 02:45 -0700, pacopyc wrote: Hi, I've a question for you. I'd like to call a function and waiting its return value for a time max (30 sec). The function could not respond and then I must avoid to wait for infinite time. OS is Windows XP. Can you help me? Thank This is how I do it with a function decorator. I probably borrowed this from someone and not attributed it. Anyway, it works on Linux, not sure about Windows: def function_timeout(seconds): Function decorator to raise a timeout on a function call import signal class FunctionTimeOut(Exception): pass def decorate(f): def timeout(signum, frame): raise FunctionTimeOut() def funct(*args, **kwargs): old = signal.signal(signal.SIGALRM, timeout) signal.alarm(seconds) try: result = f(*args, **kwargs) finally: signal.signal(signal.SIGALRM, old) signal.alarm(0) return result return funct return decorate -- http://mail.python.org/mailman/listinfo/python-list
Re: Django as exemplary design
On Thu, 2010-05-06 at 16:38 -0700, Patrick Maupin wrote: I don't know how this applies to reading other peoples' code, but recent research shows we learn more from success than failure That's good to learn, because for years I have been intentionally failing in order to learn from it and become successful, and it hasn't really worked out for me :| -a -- http://mail.python.org/mailman/listinfo/python-list
Re: pythonrag
On Mon, 2010-04-05 at 11:38 +, Jason Friedman wrote: I saw this posted in the July issue but did not see any follow-up there: $ python Python 2.6.4 (r264:75706, Dec 7 2009, 18:43:55) [GCC 4.4.1] on linux2 Type help, copyright, credits or license for more information. a = 500 b = 500 a == b True a is b False p = 50 q = 50 p == q True p is q True This topic shows here every 3 weeks or so... The short of it: CPython optimizes small integers. It's a feature. Don't rely on it (Google for the rest). -a -- http://mail.python.org/mailman/listinfo/python-list
os.fdopen() issue in Python 3.1?
I have a snippet of code that looks like this: pid, fd = os.forkpty() if pid == 0: subprocess.call(args) else: input = os.fdopen(fd).read() ... This seems to work find for CPython 2.5 and 2.6 on my Linux system. However, with CPython 3.1 I get: input = os.fdopen(fd).read() IOError: [Errno 5] Input/output error Is there something wrong in Python 3.1? Is this the correct way to do this (run a process in a pseudo-tty and read it's output) or is there another way I should/could be doing this? -a -- http://mail.python.org/mailman/listinfo/python-list
Re: os.fdopen() issue in Python 3.1?
On Tue, 2010-03-02 at 13:25 -0500, Terry Reedy wrote: To get help, or report a bug, for something like this, be as specific as possible. 'Linux' may be too generic. This is on Python on Gentoo Linux x64 with kernel 2.6.33. However, with CPython 3.1 I get: input = os.fdopen(fd).read() IOError: [Errno 5] Input/output error Is there something wrong in Python 3.1? Is this the correct way to do this (run a process in a pseudo-tty and read it's output) or is there another way I should/could be doing this? No idea, however, the first thing I would do is call the .fdopen and .read methods separately (on separate lines) to isolate which is raising the error. The exception occurs on the read() method. -- http://mail.python.org/mailman/listinfo/python-list
Re: os.fdopen() issue in Python 3.1?
On Tue, 2010-03-02 at 17:32 +, MRAB wrote: The documentation also mentions the 'pty' module. Have you tried that instead? I haven't but I'll give it a try. Thanks. -a -- http://mail.python.org/mailman/listinfo/python-list
Re: os.fdopen() issue in Python 3.1?
On Tue, 2010-03-02 at 17:32 +, MRAB wrote: The documentation also mentions the 'pty' module. Have you tried that instead? I tried to use pty.fork() but it also produces the same error. I also tried passing 'r', and 'rb' to fdopen() but it didn't make any difference. -a -- http://mail.python.org/mailman/listinfo/python-list
Re: os.fdopen() issue in Python 3.1?
This appears to be Issue 5380[1] which is still open. I've cc'ed myself to that issue. [1] http://bugs.python.org/issue5380 -- http://mail.python.org/mailman/listinfo/python-list
[issue5380] pty.read raises IOError when slave pty device is closed
Changes by Albert Hopkins mar...@python.net: -- nosy: +marduk ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue5380 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
Re: Detecting new removable drives in Linux
On Mon, 2010-03-01 at 10:48 +0100, Bart Smeets wrote: Hello, I'm trying to write a script which detects when a new removable drive is connected to the computer. On #python I was advised to use the dbus-bindings. However the documentation on this is limited. Does anyone know of an example of how I can detect new removable drives? The documentation does suck and, at least for the python bindings, is horribly outdated. Also, the python bindings for dbus are not as pythonic as they could be. I was working on a python/dbus program a while back and basically had to resort to looking at the source of a program that did, or almost did, what I wanted and using that as an example. You may even want to look at C sources as I don't think the python bindings are that much different. HTH, -a -- http://mail.python.org/mailman/listinfo/python-list
Re: pythonpath
On Mon, 2010-03-01 at 02:48 -0800, luca72 wrote: Sorry for my stupid question if i have to load module from a folder i have to append it to the sys path the folder? ex: if my folder module is /home/lucak904/Scrivania/Luca/enigma2 i do this : import sys sys.path.append('/home/lucak904/Scrivania/Luca/enigma2') If this is correct why when i write: form enigma2 import * i get no module named enigma2 There are two reasons for this: 1. enigma2 is not in your namespace. What's inside enigma is. For example, you can't say from site-packages import * because Python doesn't look at site-packages. It looks at what's inside site-packages. If you wanted enigma2 to be in your namespace, you should add /home/lucak904/Scrivania/Luca to your system path. 2. Even if you did above, it may not work because enigma2 is a directory. Remember from x import * only works for modules and packages, so if you want enigma2 to be a package, remember to add an (empty) __init__.py to the directory. Hope this helps. -a -- http://mail.python.org/mailman/listinfo/python-list
Re: Are *.pyd's universal?
On Sat, 2009-10-31 at 21:32 +1300, Lawrence D'Oliveiro wrote: Modules will sometimes find themselves on the path in Windows, so the fact that Windows performs a library search on the path is quite significant. Why is it only Windows is prone to this problem? I think as someone pointed out earlier, in Unix-like operating systems, a regular library's file name starts with lib, e.g. libcrypt.so. So this would not conflict with Python's crypt.so. But in Windows, they would both be named crypt.dll, for example (I'm halfway guessing since I don't have/use Windows). -- http://mail.python.org/mailman/listinfo/python-list
Re: datetime question
On Sat, 2009-10-31 at 10:08 +1100, Ben Finney wrote: The ‘datetime’ module focusses on individual date+time values (and the periods between them, with the ‘timedelta’ type). For querying the properties of the calendar, use the ‘calendar’ module. Yes, it would be nice if the ‘time’, ‘datetime’, and ‘calendar’ modules were all much more unified and consumed a common set of primitive date+time types. It's a wart, and fixing it would (unfortunately) probably require backward-incompatible API changes. But, supposedly, that's why we had Python3. -- http://mail.python.org/mailman/listinfo/python-list
Re: datetime question
On Sat, 2009-10-31 at 20:34 +1100, Ben Finney wrote: Fixing ‘time’, ‘datetime’, and ‘calendar’ was the reason for Python 3? No, it wasn't. Or perhaps you mean that any backward-incompatible change was a reason to have Python 3? Even more firmly no. The extent of changes was severely limited to make the transition from Python 2 to Python 3 as painless as feasible, while still meeting the goals of Python 3. No, I meant cleaning up the standard library in spite of incompatibilities was one of the goals of Python3 (PEP 3108). Personally I don't see anything wrong with the modules, but that was my question to the person who said they should all be integrated but wasn't because of incompatibilities. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python 2.6.4: ./configure does not work
On Sat, 2009-10-31 at 03:07 -0700, knipknap wrote: Hi, Running ./configure in the 2.6.4 sources produces the following error: config.status: error: cannot find input file: Makefile.pre.in Indeed, such a file is not contained anywhere in the Pakage. Which sources are you referring to? Can you verify the checksums: 17dcac33e4f3adb69a57c2607b6de246 13322131 Python-2.6.4.tgz fee5408634a54e721a93531aba37f8c1 11249486 Python-2.6.4.tar.bz2 Also, I found this note: The Unix build and install process is explained clearly in the README file contained in the distribution (http://www.python.org/download/source/) However, there isn't any README (or INSTALL) file contained in the distribution. s...@mach:/home/sab/Python-2.6.4 find . -name README ./Lib/lib2to3/tests/data/README ./Lib/distutils/README ./Lib/test/crashers/README Any hints? There is a README at the root of the tarball: $ pwd /home/marduk/Desktop/Python-2.6.4 $ head -1 README This is Python version 2.6.4 -- http://mail.python.org/mailman/listinfo/python-list
Re: Are *.pyd's universal?
On Sat, 2009-10-31 at 23:58 +1300, Lawrence D'Oliveiro wrote: I just checked my Debian installation: l...@theon:~ find /lib /usr/lib -name \*.so -a -not -name lib\* -print | wc -l 2950 l...@theon:~ find /lib /usr/lib -name \*.so -print | wc -l 4708 So 63% of the shareable libraries on my system have names NOT beginning with lib. Any better theories? Those are likely not system (sharable) libraries (e.g. libcrypt). These are probably plugins loaded by a specific program, for example PAM modules, ImageMagick plugins, python modules, etc. so since they are not in your library path the do not stand getting accidentally loaded (e.g. when a binary is linked against libcrypt.so). These libraries are loaded directly by the program using their exact path name and dlopen(). The issue with windows they were saying is that Windows will load the library with that name if it is in your current directory. So if you happen to have a python library called CRYPT.DLL and you are in that directory and try to run a program that loads CRYPT.DLL then you will be loading the python module instead of the Windows one (I have no idea if Windows has a CRYPT.DLL). OTOH this doesn't happen in Linux because a) programs wanting the system's crypt library are looking for libcrypt.so and b) Linux doesn't look in your current directory (by default) for libraries. -- http://mail.python.org/mailman/listinfo/python-list
Re: import bug
On Sat, 2009-10-31 at 16:27 +, kj wrote: 2) this has been fixed in Py3 In my post I illustrated that the failure occurs both with Python 2.6 *and* Python 3.0. Did you have a particular version of Python 3 in mind? I was not able to reproduce with my python3: $ head ham/*.py == ham/__init__.py == == ham/re.py == == ham/spam.py == import inspect $ python3 ham/spam.py $ python3 --version Python 3.1.1 -- http://mail.python.org/mailman/listinfo/python-list
Re: OT: DARPA red balloon challenge
On Thu, 2009-10-29 at 20:27 -0700, Adam N wrote: [...] On December 5, DARPA will raise 10 red weather balloons somewhere in the US. The first person to get the location of all 10 balloons and submit them will be given $40k. Hasn't the U.S. had enough weather balloon-related publicity stunts? Well, hopefully this one won't turn into 10 missing little boys :-) -a -- http://mail.python.org/mailman/listinfo/python-list
Re: Aaaargh! global name 'eggz' is not defined
On Thu, 2009-10-29 at 17:27 -0500, Robert Kern wrote: I consider import * the first error to be fixed, so it doesn't bother me much. :-) But does pyflakes at least *warn* about the use of import * (I've never used it so just asking)? -- http://mail.python.org/mailman/listinfo/python-list
Re: Web development with Python 3.1
On Wed, 2009-10-28 at 15:32 +0200, Dotan Cohen wrote: def index(request): unmaintanable_html = html head titleIndex/title /head body h1Embedded HTML is a PITA/h1 pbut some like pains.../p /body /html return HttpResponse(unmaintanable_html) And if I need to add a variable or three in there? Static HTML I can do without Python. Put the variables in a dict and then return unmaintanable_html % varDict Or, if you want the the static HTML in a file then you can return open(static_html_filename).read() % varDict Add any complexity beyond that though and you're pretty much on your way to writing a template engine ;-) -a -- http://mail.python.org/mailman/listinfo/python-list
Re: Web development with Python 3.1
On Wed, 2009-10-28 at 16:38 +0200, Dotan Cohen wrote: return HttpResponse(unmaintanable_html % data) That's fine for single variables, but if I need to output a table of unknown rows? I assume that return means the end of the script. Therefore I should shove the whole table into a variable and then copy that variable to the array data? No, if you use a templating system like Django's then basically you pass a QuerySet to your template. A QuerySet is basically a pointer to a SQL query, for example. The templating system just knows to expect an iterable, it can be a list of rows or it can be a QuerySet which does a fetch from a database. No need to shove an entire table into a variable. - second solution: do basically the same thing with a template system - which will give you much more power and options... I will look further into the Django templates, I promise. But I would still like to know how to work with Python proper. Another advantage if templates for many is that it allows programmers to do what they do best (write code) while letting web designers do what they do best (designing web pages) without them walking over each other (that much). -- http://mail.python.org/mailman/listinfo/python-list
Re: popen function of os and subprocess modules
On Wed, 2009-10-28 at 07:15 -0700, banu wrote: Thanks for the reply Jon Basically I need to move into a folder and then need to execute some shell commands(make etc.) in that folder. I just gave 'ls' for the sake of an example. The real problem I am facing is, how to stay in the folder after popen('cd directory') finishes. It seems trivial, but I am not able to do it. The problem is that you are running 2 child, and it's the first subprocess that's changing the directory and then exiting. This actually has little to do with Python specifically. you can see the same thing if you do this: $ pwd /tmp $ cat mycd.sh #!/bin/sh cd /etc $ ./mycd.sh $ pwd /tmp As you can see I am still in tmp. This is because mycd.sh changed to /etc/ but after it exits back to the parent process it is back in /tmp. What you want is to cd inside your script itself. os.chdir() does this. -- http://mail.python.org/mailman/listinfo/python-list
Re: Passing values from html to python
On Thu, 2009-10-22 at 10:44 +0200, Ahmed Barakat wrote: Hi guys, I am new to python and wed-development, I managed to have some nice example running up till now. I am playing with google app engine, I have this situation: I have a text box in an html page, I want to get the value in it and pass it to the python script to process it I can pass values from python to html, but the other way I don't know how to do that. You need a web server: something that speaks the HTTP protocol. -- http://mail.python.org/mailman/listinfo/python-list
Re: creating class objects inside methods
Just by a brief look at your code snippet there are a few things that I would point out, stylistically, that you may consider changing in your code as they are generally not considered pythonic: * As already mentioned the state class is best if given a name that is capitalized. * As already mentioned the name state is (unintentionally) re-used within the same scope. This could have been avoided with the above naming convention change and also if the main body of the code were in a function, say main() * The methods default_board, default_types, and default_moves appear to be static methods but are not defined as such. * Also, since the above methods have no logic and simply return a value they are probably best defined as static attributes rather than methods. But if doing so you would need to alter your constructor. * You used a number of built-in names as attribute names (dir, type). While this is legal Python it is generally not recommended. * You use range(0, n). 0 is the default start value for range() so it is generally left out. * You define a to_string() method. To have a string representation of a class, one usually defines a __str__ method. This gives the advantage whereby print myobject or '%s' % myjobject just work. Probably others can make more suggestions. You will find a lot of these suggestions are borrowed from PEP8 [1] but you can peruse other people's Python code to learn from the masters. Hope this helps, -a -- http://mail.python.org/mailman/listinfo/python-list
Re: Parsing email attachments: get_payload() produces unsaveable data
On Sun, 2009-10-04 at 07:27 -0700, dpapathanasiou wrote: When I try to write the filedata to a file system folder, though, I get an AttributeError in the stack trace. And where might we be able to see that stack trace? -a -- http://mail.python.org/mailman/listinfo/python-list
Re: Parsing email attachments: get_payload() produces unsaveable data
On Sun, 2009-10-04 at 08:16 -0700, dpapathanasiou wrote: And where might we be able to see that stack trace? This is it: Exception: ('AttributeError', 'no args', [' File /opt/server/smtp/ smtps.py, line 213, in handle\ne mail_replier.post_reply(recipient_mbox, \'\'.join(data))\n', ' File / opt/server/smtp/email_replier.py, l ine 108, in post_reply\nsave_attachments(result[2], msg_text)\n', ' File /opt/server/smtp/email_repli er.py, line 79, in save_attachments\ndata_manager.upload_file (item_id, filename, filedata)\n', ' File ../db/data_manager.py, line 697, in upload_file\nif docs_db.save_file(item_id, file_name, file_data) :\n', ' File ../db/docs_db.py, line 102, in save_file\nresult = file_utils.write_file(saved_file_pat h, saved_file_name + saved_file_ext, file_data)\n']) If you're wondering, I'm using this to capture the exception: def formatExceptionInfo(maxTBlevel=5): For displaying exception information cla, exc, trbk = sys.exc_info() excName = cla.__name__ try: excArgs = exc.__dict__[args] except KeyError: excArgs = no args excTb = traceback.format_tb(trbk, maxTBlevel) return (excName, excArgs, excTb) Which is *really* difficult (for me) to read. Any chance of providing a normal traceback? -- http://mail.python.org/mailman/listinfo/python-list
Re: Parsing email attachments: get_payload() produces unsaveable data
On Sun, 2009-10-04 at 09:17 -0700, dpapathanasiou wrote: Which is *really* difficult (for me) to read. Any chance of providing a normal traceback? File /opt/server/smtp/smtps.py, line 213, in handle email_replier.post_reply(recipient_mbox, ''.join(data)) File /opt/server/smtp/email_replier.py, line 108, in post_reply save_attachments(result[2], msg_text) File /opt/server/smtp/email_replier.py, line 79, in save_attachments data_manager.upload_file(item_id, filename, filedata) File ../db/data_manager.py, line 697, in upload_file if docs_db.save_file(item_id, file_name, file_data): File ../db/docs_db.py, line 102, in save_file result = file_utils.write_file(saved_file_path, saved_file_name + saved_file_ext, file_data) AttributeError Are you sure this is the complete traceback? Usually an AttributeError returns a text message such as: AttributeError: foo has no such attribute bar Also, the traceback says the exception happened in save_file, but the code you posted was a function called save_attachments and the function call is different. Would be nice if we could get the full traceback with the exact matching code. Otherwise we have to make guesses. But I've given up. Perhaps someone else is better off helping you. -a -- http://mail.python.org/mailman/listinfo/python-list
Re: Opinions, please, on PEP 8 and local, 3rd party imports
On Fri, 2009-10-02 at 20:22 -0400, Simon Forman wrote: 2.5 +1 I'd like to suggest 2.46 instead. -- http://mail.python.org/mailman/listinfo/python-list
Re: UnboundLocalError with extra code after return
On Tue, 2009-09-29 at 21:15 -0700, Rich Healey wrote: However: def callonce(func): def nullmethod(): pass def __(): return func() func = nullmethod return ret return __ @callonce def t2(): print T2 called t2() Gives me: C:\tmp\calloncecallonce.py Traceback (most recent call last): File C:\tmp\callonce\callonce.py, line 27, in module t2() File C:\tmp\callonce\callonce.py, line 12, in __ return func() UnboundLocalError: local variable 'func' referenced before assignment Any ideas on why? This looks like a bug to me, but I'm quite new to this style of programming so it may be some nuance I'm not aware of. I'm not following your logic. There is no check to see if func is already called. Moreover, you are replacing func which is not recommended. A decorator is supposed to decorate func, not replace it. I think what is happening here is func = nullmethod is being assigned at definition time, not at runtime, so by the time you've defined __() func is no longer there, so Secondly, if nullmethod returns nothing, why not just return nothing in __() instead of creating a new function that does nothing. Thirdly, 'return ret' is never called. Because you return out of __() in the first line of the function. Fourthly, 'ret' is never defined, so even if it were run you would get an undefined error. But what I think is happening is since you have effectively overriden func (t2) with nullmethod it gets 'lost' by the time the __() is actually called. I haven't looked closely but you should be able to see what's happening in a debugger. What you really want to do is something like this: def callonce(func): func.called = False def dec(*args, **kwargs): if func.called: return func.called=True return func(*args, **kwargs) return dec @callonce def t2(): print 't2() Called' t2() t2() Called t2() -- http://mail.python.org/mailman/listinfo/python-list
Re: How to define a function with an empty body?
On Sat, 2009-09-12 at 22:37 -0500, Peng Yu wrote: Hi, I want to define a function without anything in it body. In C++, I can do something like the following because I can use {} to denote an empty function body. Since python use indentation, I am not sure how to do it. Can somebody let me know how to do it in python? void f() { } Surprised no one has mentioned this yet, but since it's a function, and in python all functions return values (whether explicitly or implicitly, a simple return works and, to me, does much more to inform the reader that this function does nothing. def f(): return -- http://mail.python.org/mailman/listinfo/python-list
Re: Is there a similar mailing list about django?
On Sun, 2009-09-13 at 21:27 +0200, Andreas Waldenburger wrote: Didn't like http://groups-beta.google.com/group/django-users ? (Second hit for django mailing list, but I know Google results vary from country to country, so you might not have seen it.) Or, better yet, go to Django's web site (djangoproject.org) and click on Community at the top of the page. -- http://mail.python.org/mailman/listinfo/python-list
Re: Is there a similar mailing list about django?
On Sun, 2009-09-13 at 18:46 -0400, Joel Goldstick wrote: Thanks.. I saw the google group, but I was hoping for a list that I can read in my thunderbird client. Thanks all for the good pointers And if you simply go to the Django web site and click on Community there is a form where you can subscribe to the Django mailing lists and read them in your precious little Thunderbird client. -- http://mail.python.org/mailman/listinfo/python-list
Re: How can I use my modules here?
On Fri, 2009-09-11 at 02:29 -0700, Chris Rebert wrote: For some reason, your Python program is being executed by bash as if it were a shell script, which it's not. No idea what the cause is though. Because the first 2 bytes of the file need to be #!/path/to/interpreter, the OP has: main.py Begin ## This won't work. -- http://mail.python.org/mailman/listinfo/python-list
Re: AttributeError: 'module' object has no attribute 'pack'
On Thu, 2009-09-10 at 21:07 +0300, Sampsa Riikonen wrote: Dear List, I have a freshly installed opensuse 11.2 and I am experiencing the following problem with the module subprocess: sam...@linux-912g:~ python Python 2.6 (r26:66714, Feb 3 2009, 20:52:03) [GCC 4.3.2 [gcc-4_3-branch revision 141291]] on linux2 Type help, copyright, credits or license for more information. import subprocess Traceback (most recent call last): File stdin, line 1, in module File /usr/lib/python2.6/subprocess.py, line 404, in module import pickle File /usr/lib/python2.6/pickle.py, line 171, in module class Pickler: File /usr/lib/python2.6/pickle.py, line 250, in Pickler def put(self, i, pack=struct.pack): AttributeError: 'module' object has no attribute 'pack' Any ideas how to fix this? Kind Regards, Is there another struct module that is overriding the built-in one? import struct struct.__file__ -- http://mail.python.org/mailman/listinfo/python-list
Re: wxGlade question - How to add new event to a button in events tab?
Could you not post the exact same message 3 times within an hour? -- http://mail.python.org/mailman/listinfo/python-list
Re: start default application for read a pdf from python
On Tue, 2009-09-08 at 22:22 +0200, Angelo Ballabio wrote: My problem is a way to run a default application to read and show a pdf file from unix or windows, i have a mixed ambient in the office, so I am try to find a way to start a application to show this pdf file I generate whith reportlab. The (most) portable way to do so in Linux (not necessarily Unix) is to use the xdg-open command. Ex, subprocess.Popen(['xdg-open', 'my-document.pdf']) If you want cross-platform between Linux/Windows, then it's advisable to write a wrapper function that checks the value of sys.platform and and acts accordingly. -a -- http://mail.python.org/mailman/listinfo/python-list
Re: Python for 64bit Linux version
On Thu, 2009-09-03 at 13:30 -0500, Bhanu Srinivas Mangipudi wrote: I just want to that s there a 64 bit Linux version for python ? if yes can you provide me any links for it.I could find a 64bit windows version but could not find Linuux version If you are using a 64bit Linux distribution then likely that distribution already comes with Python and likely that Python is already 64bit. Else you can always download the source from python.org yourself and compile it. -a -- http://mail.python.org/mailman/listinfo/python-list
Re: issue with grep command
On Thu, 2009-09-03 at 11:51 -0700, Jul wrote: [Stuff about tcsh and grep deleted] What on earth does this have to do with Python? -a -- http://mail.python.org/mailman/listinfo/python-list
Re: Try Except Problem
On Tue, 2009-09-01 at 13:45 -0500, Victor Subervi wrote: Hi: I have this code: [blah] It's hard to tell because: 1. You posted code in HTML format, which is really hard to read 2. Even when viewed as plain text, you use non-standard indentation which is really hard to read 3. You used a blank except: clause that catches all exceptions. This is not good programming practice and makes it difficult to debug 4. You didn't reduce your code down to the basic problem, or at least provide an alternative code snippet that others can try to duplicate 5. You didn't show the actual output or provide what inputs were used. In short, it basically looks like you typed or copied some code that is not well written, discovered it doesn't work and expect the list to debug your program for you. Help us help you. -- http://mail.python.org/mailman/listinfo/python-list
Re: Is behavior of += intentional for int?
On Sun, 2009-08-30 at 10:44 +, Steven D'Aprano wrote: It also follows from the idea that there is one abstract entity which English speakers call three and write as 3. There's not two identical entities with value 3, or four, or a million of them, only one. That's not true. There are many different 3s in all the parallel universes. ;) -a -- http://mail.python.org/mailman/listinfo/python-list