title
stringlengths
12
150
question_id
int64
469
40.1M
question_score
int64
2
5.52k
question_date
stringdate
2008-08-02 15:11:16
2016-10-18 06:16:31
answer_id
int64
536
40.1M
answer_score
int64
7
8.38k
answer_date
stringdate
2008-08-02 18:49:07
2016-10-18 06:19:33
tags
listlengths
1
5
question_body_md
stringlengths
15
30.2k
answer_body_md
stringlengths
11
27.8k
Getting method parameter names in python
218,616
131
2008-10-20T14:22:02Z
218,625
73
2008-10-20T14:24:48Z
[ "python", "decorator", "introspection", "python-datamodel" ]
Given the python function: ``` def aMethod(arg1, arg2): pass ``` How can I extract the number and names of the arguments. Ie. given that I have a reference to func, I want the func.[something] to return ("arg1", "arg2") The usage scenario for this is that I have a decorator, and I wish to use the method argument...
In CPython, the number of arguments is ``` aMethod.func_code.co_argcount ``` and their names are in the beginning of ``` aMethod.func_code.co_varnames ``` These are implementation details of CPython, so this probably does not work in other implementations of Python, such as IronPython and Jython. One portable way ...
Getting method parameter names in python
218,616
131
2008-10-20T14:22:02Z
218,709
240
2008-10-20T14:52:19Z
[ "python", "decorator", "introspection", "python-datamodel" ]
Given the python function: ``` def aMethod(arg1, arg2): pass ``` How can I extract the number and names of the arguments. Ie. given that I have a reference to func, I want the func.[something] to return ("arg1", "arg2") The usage scenario for this is that I have a decorator, and I wish to use the method argument...
Take a look at the [inspect](http://docs.python.org/library/inspect.html) module - this will do the inspection of the various code object properties for you. ``` >>> inspect.getargspec(aMethod) (['arg1', 'arg2'], None, None, None) ``` The other results are the name of the \*args and \*\*kwargs variables, and the defa...
Getting method parameter names in python
218,616
131
2008-10-20T14:22:02Z
220,366
10
2008-10-21T00:02:19Z
[ "python", "decorator", "introspection", "python-datamodel" ]
Given the python function: ``` def aMethod(arg1, arg2): pass ``` How can I extract the number and names of the arguments. Ie. given that I have a reference to func, I want the func.[something] to return ("arg1", "arg2") The usage scenario for this is that I have a decorator, and I wish to use the method argument...
Here is something I think will work for what you want, using a decorator. ``` class LogWrappedFunction(object): def __init__(self, function): self.function = function def logAndCall(self, *arguments, **namedArguments): print "Calling %s with arguments %s and named arguments %s" %\ ...
Getting method parameter names in python
218,616
131
2008-10-20T14:22:02Z
2,991,341
9
2010-06-07T16:37:20Z
[ "python", "decorator", "introspection", "python-datamodel" ]
Given the python function: ``` def aMethod(arg1, arg2): pass ``` How can I extract the number and names of the arguments. Ie. given that I have a reference to func, I want the func.[something] to return ("arg1", "arg2") The usage scenario for this is that I have a decorator, and I wish to use the method argument...
I think what you're looking for is the locals method - ``` In [6]: def test(a, b):print locals() ...: In [7]: test(1,2) {'a': 1, 'b': 2} ```
Getting method parameter names in python
218,616
131
2008-10-20T14:22:02Z
16,542,145
11
2013-05-14T11:36:45Z
[ "python", "decorator", "introspection", "python-datamodel" ]
Given the python function: ``` def aMethod(arg1, arg2): pass ``` How can I extract the number and names of the arguments. Ie. given that I have a reference to func, I want the func.[something] to return ("arg1", "arg2") The usage scenario for this is that I have a decorator, and I wish to use the method argument...
In a decorator method, you can list arguments of the original method in this way: ``` import inspect, itertools def my_decorator(): def decorator(f): def wrapper(*args, **kwargs): # if you want arguments names as a list: args_name = inspect.getargspec(f)[0] ...
How do you share data between a parent and forked child process in Python?
218,935
10
2008-10-20T15:57:05Z
219,048
12
2008-10-20T16:26:05Z
[ "python", "fork", "share" ]
I'm pretty sure one would do this using the os.plock(op) function, but I have no idea how. Also, if there's a better way, I'd be grateful to find out. Code snippets are very welcome.
[Subprocess](http://docs.python.org/library/subprocess) replaces os.popen, os.system, os.spawn, popen2 and commands. A [simple example for piping](http://docs.python.org/library/subprocess#replacing-shell-pipe-line) would be: ``` p1 = Popen(["dmesg"], stdout=PIPE) p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PI...
How do you share data between a parent and forked child process in Python?
218,935
10
2008-10-20T15:57:05Z
219,066
7
2008-10-20T16:30:34Z
[ "python", "fork", "share" ]
I'm pretty sure one would do this using the os.plock(op) function, but I have no idea how. Also, if there's a better way, I'd be grateful to find out. Code snippets are very welcome.
Take a look at the [multiprocessing](http://docs.python.org/dev/library/multiprocessing.html) module new in python 2.6 (also available for earlier versions a [pyprocessing](http://pyprocessing.berlios.de/) Here's an example from the docs illustrating passing information using a pipe for instance: ``` from multiproces...
how can i use sharepoint (via soap?) from python?
218,987
9
2008-10-20T16:09:36Z
222,242
8
2008-10-21T15:13:46Z
[ "python", "sharepoint", "soap", "ntlm", "suds" ]
I want to use Sharepoint with python (C-Python) Has anyone tried this before ?
To get the wsdl : ``` import sys # we use suds -> https://fedorahosted.org/suds from suds import WebFault from suds.client import * import urllib2 # my 2 url conf # url_sharepoint,url_NTLM_authproxy import myconfig as my # build url wsdl = '_vti_bin/SiteData.asmx?WSDL' url = '/'.join([my.url_sharepoint,wsdl]) #...
how can i use sharepoint (via soap?) from python?
218,987
9
2008-10-20T16:09:36Z
5,403,203
9
2011-03-23T09:36:12Z
[ "python", "sharepoint", "soap", "ntlm", "suds" ]
I want to use Sharepoint with python (C-Python) Has anyone tried this before ?
I suspect that since this question was answered the SUDS library has been updated to take care of the required authentication itself. After jumping through various hoops, I found this to do the trick: ``` from suds import WebFault from suds.client import * from suds.transport.https import WindowsHttpAuthenticated us...
How Python web frameworks, WSGI and CGI fit together
219,110
127
2008-10-20T16:43:57Z
219,124
21
2008-10-20T16:49:17Z
[ "python", "apache", "cgi", "wsgi" ]
I have a [Bluehost](http://en.wikipedia.org/wiki/Bluehost) account where I can run Python scripts as CGI. I guess it's the simplest CGI, because to run I have to define the following in `.htaccess`: ``` Options +ExecCGI AddType text/html py AddHandler cgi-script .py ``` Now, whenever I look up web programming with Py...
You can [run WSGI over CGI as Pep333 demonstrates](http://www.python.org/dev/peps/pep-0333/#the-server-gateway-side) as an example. However every time there is a request a new Python interpreter is started and the whole context (database connections, etc.) needs to be build which all take time. The best if you want to...
How Python web frameworks, WSGI and CGI fit together
219,110
127
2008-10-20T16:43:57Z
505,534
49
2009-02-03T00:04:46Z
[ "python", "apache", "cgi", "wsgi" ]
I have a [Bluehost](http://en.wikipedia.org/wiki/Bluehost) account where I can run Python scripts as CGI. I guess it's the simplest CGI, because to run I have to define the following in `.htaccess`: ``` Options +ExecCGI AddType text/html py AddHandler cgi-script .py ``` Now, whenever I look up web programming with Py...
I think [Florian's answer](http://stackoverflow.com/questions/219110/how-python-web-frameworks-wsgi-and-cgi-fit-together/219124#219124) answers the part of your question about "what is WSGI", especially if you read [the PEP](http://www.python.org/dev/peps/pep-0333). As for the questions you pose towards the end: WSGI...
How Python web frameworks, WSGI and CGI fit together
219,110
127
2008-10-20T16:43:57Z
520,194
200
2009-02-06T13:04:12Z
[ "python", "apache", "cgi", "wsgi" ]
I have a [Bluehost](http://en.wikipedia.org/wiki/Bluehost) account where I can run Python scripts as CGI. I guess it's the simplest CGI, because to run I have to define the following in `.htaccess`: ``` Options +ExecCGI AddType text/html py AddHandler cgi-script .py ``` Now, whenever I look up web programming with Py...
**How WSGI, CGI, and the frameworks are all connected ?** Apache listens on port 80. It gets an HTTP request. It parses the request to find a way to respond. Apache has a LOT of choices for responding. One way to respond is to use CGI to run a script. Another way to respond is to simply serve a file. In the case of C...
I’m stunned: weird problem with python and sockets + threads
219,547
2
2008-10-20T19:19:45Z
219,671
7
2008-10-20T19:56:00Z
[ "python", "multithreading", "apache", "sockets" ]
I have a python script that is a http-server: <http://paste2.org/p/89701>, when benchmarking it against ApacheBench (ab) with a concurrency level (-c switch) that is lower then or equal to the value i specified in the socket.listen()-call in the sourcecode everything works fine, but as soon as put the concurrency level...
I cannot confirm your results, and your server is coded fishy. I whipped up my own server and do not have this problem either. Let's move the discussion to a simpler level: ``` import thread, socket, Queue connections = Queue.Queue() num_threads = 10 backlog = 10 def request(): while 1: conn = connection...
Ensure a single instance of an application in Linux
220,525
28
2008-10-21T01:58:30Z
220,542
21
2008-10-21T02:10:24Z
[ "python", "linux", "singleinstance" ]
I'm working on a GUI application in WxPython, and I am not sure how I can ensure that only one copy of my application is running at any given time on the machine. Due to the nature of the application, running more than once doesn't make any sense, and will fail quickly. Under Win32, I can simply make a named mutex and ...
There are several common techniques including using semaphores. The one I see used most often is to create a "pid lock file" on startup that contains the pid of the running process. If the file already exists when the program starts up, open it up and grab the pid inside, check to see if a process with that pid is runn...
Ensure a single instance of an application in Linux
220,525
28
2008-10-21T01:58:30Z
220,709
49
2008-10-21T03:43:36Z
[ "python", "linux", "singleinstance" ]
I'm working on a GUI application in WxPython, and I am not sure how I can ensure that only one copy of my application is running at any given time on the machine. Due to the nature of the application, running more than once doesn't make any sense, and will fail quickly. Under Win32, I can simply make a named mutex and ...
The Right Thing is advisory locking using `flock(LOCK_EX)`; in Python, this is found in the [`fcntl` module](http://docs.python.org/3/library/fcntl.html). Unlike pidfiles, these locks are always automatically released when your process dies for any reason, have no race conditions exist relating to file deletion (as th...
Ensure a single instance of an application in Linux
220,525
28
2008-10-21T01:58:30Z
221,159
20
2008-10-21T08:30:11Z
[ "python", "linux", "singleinstance" ]
I'm working on a GUI application in WxPython, and I am not sure how I can ensure that only one copy of my application is running at any given time on the machine. Due to the nature of the application, running more than once doesn't make any sense, and will fail quickly. Under Win32, I can simply make a named mutex and ...
Complete locking solution using the `fcntl` module: ``` import fcntl pid_file = 'program.pid' fp = open(pid_file, 'w') try: fcntl.lockf(fp, fcntl.LOCK_EX | fcntl.LOCK_NB) except IOError: # another instance is running sys.exit(1) ```
Ensure a single instance of an application in Linux
220,525
28
2008-10-21T01:58:30Z
476,133
8
2009-01-24T15:20:51Z
[ "python", "linux", "singleinstance" ]
I'm working on a GUI application in WxPython, and I am not sure how I can ensure that only one copy of my application is running at any given time on the machine. Due to the nature of the application, running more than once doesn't make any sense, and will fail quickly. Under Win32, I can simply make a named mutex and ...
wxWidgets offers a wxSingleInstanceChecker class for this purpose: [wxPython doc](http://www.wxpython.org/docs/api/wx.SingleInstanceChecker-class.html), or [wxWidgets doc](http://docs.wxwidgets.org/stable/wx_wxsingleinstancechecker.html). The wxWidgets doc has sample code in C++, but the python equivalent should be som...
Including PYDs/DLLs in py2exe builds
220,777
9
2008-10-21T04:40:57Z
224,274
11
2008-10-22T02:27:44Z
[ "python", "dll", "installation", "py2exe", "pyd" ]
One of the modules for my app uses functions from a .pyd file. There's an option to exclude dlls (exclude\_dlls) but is there one for including them? The build process doesn't seem to be copying the .pyd in my module despite copying the rest of the files (.py). I also need to include a .dll. How do I get py2exe to incl...
.pyd's and .DLL's are different here, in that a .pyd ought to be automatically found by modulefinder and so included (as long as you have the appropriate "import" statement) without needing to do anything. If one is missed, you do the same thing as if a .py file was missed (they're both just modules): use the "include"...
How can I write a method within a Django model to retrieve related objects?
221,328
2
2008-10-21T09:49:04Z
221,338
10
2008-10-21T09:54:58Z
[ "python", "django", "model-view-controller", "frameworks" ]
I have two models. We'll call them object A and object B. Their design looks something like this: ``` class Foo(models.Model): name = models.CharField() class Bar(models.Model): title = models.CharField() Foo= models.ForeignKey('myapp.Foo') ``` Now, suppose I want to make a method within Foo that retu...
You get this for free: <http://docs.djangoproject.com/en/dev/topics/db/queries/#backwards-related-objects> By default, you can access a Manager which gives you access to related items through a `RELATEDCLASSNAME_set` attribute: ``` some_foo.bar_set.all() ``` Or you can use the `related_name` argument to `ForeignKey...
Is it possible to implement Python code-completion in TextMate?
221,339
20
2008-10-21T09:54:58Z
248,819
9
2008-10-29T23:42:15Z
[ "python", "autocomplete", "text-editor", "textmate" ]
[PySmell](http://github.com/orestis/pysmell/tree/master) seems like a good starting point. I think it should be possible, PySmell's `idehelper.py` does a majority of the complex stuff, it should just be a case of giving it the current line, offering up the completions (the bit I am not sure about) and then replacing t...
EDIT: I've actually took your code above and integrated into a command. It will properly show a completion list for you to choose. You can grab it here: <http://github.com/orestis/pysmell/tree/master> (hit download and do python setup.py install). It's rough but it works. - please report any errors on <http://code.goo...
Putting Copyright Symbol into a Python File
221,376
11
2008-10-21T10:15:16Z
221,380
28
2008-10-21T10:17:32Z
[ "python", "encoding" ]
I need to include a copyright statement at the top of every Python source file I produce: ``` # Copyright: © 2008 etc. ``` However, when I then run such a file I get this message: SyntaxError: Non-ASCII character '\xa9' in file MyFile.py on line 3, but no encoding declared; see <http://www.python.org/peps/pep-026...
The copyright symbol in ASCII is spelled `(c)` or "`Copyright`". See circular 61, [Copyright Registration for Computer Programs](http://www.copyright.gov/circs/circ61.pdf). While it's true that the legal formalism (see Circular 1, [Copyright Basics](http://www.copyright.gov/circs/circ01.pdf)) is > The symbol © (the...
Putting Copyright Symbol into a Python File
221,376
11
2008-10-21T10:15:16Z
221,569
8
2008-10-21T11:50:53Z
[ "python", "encoding" ]
I need to include a copyright statement at the top of every Python source file I produce: ``` # Copyright: © 2008 etc. ``` However, when I then run such a file I get this message: SyntaxError: Non-ASCII character '\xa9' in file MyFile.py on line 3, but no encoding declared; see <http://www.python.org/peps/pep-026...
Contrary to the accepted answer, AFAIK, (c) is not an officially recognized alternative to the copyright symbol, although I'm not sure it's been tested in court. However, © is just an abreviation of the word Copyright. Saying "Copyright 2008 Robert Munro" is identical to saying "© 2008 Robert Munro" Your "Copyright...
Is it possible to set a timeout on a socket in Twisted?
221,745
8
2008-10-21T12:56:32Z
251,302
13
2008-10-30T18:52:01Z
[ "python", "networking", "sockets", "twisted" ]
I realize I'm probably just dumb and missing something big and important, but I can't figure out how to specify a timeout in twisted using reactor.listenUDP. My goal is to be able to specify a timeout, and after said amount of time, if DatagramProtocol.datagramReceived has not been executed, have it execute a callback ...
I think `reactor.callLater` would work better than `LoopingCall`. Something like this: ``` class Protocol(DatagramProtocol): def __init__(self, timeout): self.timeout = timeout def datagramReceived(self, datagram): self.timeout.cancel() # ... timeout = reactor.callLater(5, timedOut) r...
ElementTree XPath - Select Element based on attribute
222,375
34
2008-10-21T15:52:51Z
222,473
32
2008-10-21T16:16:06Z
[ "python", "elementtree" ]
I am having trouble using the attribute XPath Selector in ElementTree, which I should be able to do according to the [Documentation](http://effbot.org/zone/element-xpath.htm) Here's some sample code **XML** ``` <root> <target name="1"> <a></a> <b></b> </target> <target name="2"> <a></a> <b></b> <...
The syntax you're trying to use is new in **[ElementTree 1.3](http://effbot.org/zone/element-xpath.htm)**. Such version is shipped with **Python 2.7** or higher. If you have Python 2.6 or less you still have ElementTree 1.2.6 or less.
ElementTree XPath - Select Element based on attribute
222,375
34
2008-10-21T15:52:51Z
16,105,230
8
2013-04-19T13:00:16Z
[ "python", "elementtree" ]
I am having trouble using the attribute XPath Selector in ElementTree, which I should be able to do according to the [Documentation](http://effbot.org/zone/element-xpath.htm) Here's some sample code **XML** ``` <root> <target name="1"> <a></a> <b></b> </target> <target name="2"> <a></a> <b></b> <...
There are several problems in this code. 1. Python's buildin ElementTree (ET for short) has no real XPATH support; only a limited subset By example, it doesn't support *find-from-root* expressions like `//target`. Notice: the [documentation](http://docs.python.org/2/library/xml.etree.elementtree.html#supported-xpa...
What is the meaning of '(?i)password' in python regular expression?
222,536
4
2008-10-21T16:29:51Z
222,556
7
2008-10-21T16:34:50Z
[ "python", "regex", "pattern-matching" ]
Pexpect can be used to automate tasks in python (does not need TCL to be installed). One of the simplest routines of this class is the 'run()' routine. It accepts a dictionary of expected question patterns as keys and the responses as values. For example pexpect.run ('scp foo myname@host.example.com:.', events={'(?i)p...
<https://docs.python.org/library/re.html#regular-expression-syntax> > (?...) This is an extension > notation (a "?" following a "(" is not > meaningful otherwise). The first > character after the "?" determines > what the meaning and further syntax of > the construct is. Extensions usually > do not create a new group;...
Sorting a tuple that contains tuples
222,752
12
2008-10-21T17:40:51Z
222,762
21
2008-10-21T17:44:08Z
[ "python", "sorting", "tuples" ]
I have the following tuple, which contains tuples: ``` MY_TUPLE = ( ('A','Apple'), ('C','Carrot'), ('B','Banana'), ) ``` I'd like to sort this tuple based upon the **second** value contained in inner-tuples (i.e., sort Apple, Carrot, Banana rather than A, B, C). Any thoughts?
``` from operator import itemgetter MY_SORTED_TUPLE = tuple(sorted(MY_TUPLE, key=itemgetter(1))) ``` or without `itemgetter`: ``` MY_SORTED_TUPLE = tuple(sorted(MY_TUPLE, key=lambda item: item[1])) ```
Sorting a tuple that contains tuples
222,752
12
2008-10-21T17:40:51Z
222,776
7
2008-10-21T17:45:56Z
[ "python", "sorting", "tuples" ]
I have the following tuple, which contains tuples: ``` MY_TUPLE = ( ('A','Apple'), ('C','Carrot'), ('B','Banana'), ) ``` I'd like to sort this tuple based upon the **second** value contained in inner-tuples (i.e., sort Apple, Carrot, Banana rather than A, B, C). Any thoughts?
From [Sorting Mini-HOW TO](http://wiki.python.org/moin/HowTo/Sorting#head-d121eed08556ad7cb2a02a886788656dadb709bd) > Often there's a built-in that will > match your needs, such as str.lower(). > The operator module contains a number > of functions useful for this purpose. > For example, you can sort tuples based > on...
How to use 'super' in Python?
222,877
221
2008-10-21T18:13:15Z
222,922
156
2008-10-21T18:24:50Z
[ "python", "inheritance", "super" ]
Can someone explain to me the difference between doing: ``` class Child(SomeBaseClass): def __init__(self): super(Child, self).__init__() ``` and this: ``` class Child(SomeBaseClass): def __init__(self): SomeBaseClass.__init__(self) ``` I've seen `super` being used quite a lot in classes wit...
The benefits of `super()` in single-inheritance are minimal -- mostly, you don't have to hard-code the name of the base class into every method that uses its parent methods. However, it's almost impossible to use multiple-inheritance without `super()`. This includes common idioms like mixins, interfaces, abstract clas...
How to use 'super' in Python?
222,877
221
2008-10-21T18:13:15Z
224,020
23
2008-10-22T00:06:32Z
[ "python", "inheritance", "super" ]
Can someone explain to me the difference between doing: ``` class Child(SomeBaseClass): def __init__(self): super(Child, self).__init__() ``` and this: ``` class Child(SomeBaseClass): def __init__(self): SomeBaseClass.__init__(self) ``` I've seen `super` being used quite a lot in classes wit...
Doesn't all of this assume that the base class is inherited from `object`? ``` class A: def __init__(self): print "A.__init__()" class B(A): def __init__(self): print "B.__init__()" super(B, self).__init__() ``` Will not work. `class A` must be derived from `object`, i.e: `class A(obj...
How to use 'super' in Python?
222,877
221
2008-10-21T18:13:15Z
33,469,090
41
2015-11-02T00:53:24Z
[ "python", "inheritance", "super" ]
Can someone explain to me the difference between doing: ``` class Child(SomeBaseClass): def __init__(self): super(Child, self).__init__() ``` and this: ``` class Child(SomeBaseClass): def __init__(self): SomeBaseClass.__init__(self) ``` I've seen `super` being used quite a lot in classes wit...
> Can someone explain to me the difference between doing: > > ``` > class Child(SomeBaseClass): > def __init__(self): > super(Child, self).__init__() > ``` > > and this: > > ``` > class Child(SomeBaseClass): > def __init__(self): > SomeBaseClass.__init__(self) > ``` # Indirection with Forward C...
Using Variables for Class Names in Python?
223,559
27
2008-10-21T21:24:24Z
223,566
27
2008-10-21T21:26:09Z
[ "python", "dynamic-typing" ]
I want to know how to use variables for objects and function names in Python. In PHP, you can do this: ``` $className = "MyClass"; $newObject = new $className(); ``` How do you do this sort of thing in Python? Or, am I totally not appreciating some fundamental difference with Python, and if so, what is it?
In Python, ``` className = MyClass newObject = className() ``` The first line makes the variable `className` refer to the same thing as `MyClass`. Then the next line calls the `MyClass` constructor through the `className` variable. As a concrete example: ``` >>> className = list >>> newObject = className() >>> newO...
Using Variables for Class Names in Python?
223,559
27
2008-10-21T21:24:24Z
223,586
41
2008-10-21T21:33:05Z
[ "python", "dynamic-typing" ]
I want to know how to use variables for objects and function names in Python. In PHP, you can do this: ``` $className = "MyClass"; $newObject = new $className(); ``` How do you do this sort of thing in Python? Or, am I totally not appreciating some fundamental difference with Python, and if so, what is it?
Assuming that some\_module has a class named "class\_name": ``` import some_module klass = getattr(some_module, "class_name") some_object = klass() ``` I should note that you should be careful here: turning strings into code can be dangerous if the string came from the user, so you should keep security in mind in thi...
Using Variables for Class Names in Python?
223,559
27
2008-10-21T21:24:24Z
2,875,113
15
2010-05-20T15:14:38Z
[ "python", "dynamic-typing" ]
I want to know how to use variables for objects and function names in Python. In PHP, you can do this: ``` $className = "MyClass"; $newObject = new $className(); ``` How do you do this sort of thing in Python? Or, am I totally not appreciating some fundamental difference with Python, and if so, what is it?
If you need to create a dynamic class in Python (i.e. one whose name is a variable) you can use type() which takes 3 params: name, bases, attrs ``` >>> class_name = 'MyClass' >>> klass = type(class_name, (object,), {'msg': 'foobarbaz'}) <class '__main__.MyClass'> >>> inst = klass() >>> inst.msg foobarbaz ``` * Note...
Elegant structured text file parsing
223,866
19
2008-10-21T23:00:20Z
223,925
12
2008-10-21T23:25:53Z
[ "python", "ruby", "perl", "text-parsing" ]
I need to parse a transcript of a live chat conversation. My first thought on seeing the file was to throw regular expressions at the problem but I was wondering what other approaches people have used. I put elegant in the title as i've previously found that this type of task has a danger of getting hard to maintain j...
No and in fact, for the specific type of task you describe, I doubt there's a "cleaner" way to do it than regular expressions. It looks like your files have embedded line breaks so typically what we'll do here is make the line your unit of decomposition, applying per-line regexes. Meanwhile, you create a small state ma...
Elegant structured text file parsing
223,866
19
2008-10-21T23:00:20Z
224,344
11
2008-10-22T03:01:20Z
[ "python", "ruby", "perl", "text-parsing" ]
I need to parse a transcript of a live chat conversation. My first thought on seeing the file was to throw regular expressions at the problem but I was wondering what other approaches people have used. I put elegant in the title as i've previously found that this type of task has a danger of getting hard to maintain j...
With Perl, you can use [Parse::RecDescent](http://search.cpan.org/perldoc?Parse::RecDescent) It is simple, and your grammar will be maintainable later on.
How do I perform query filtering in django templates
223,990
50
2008-10-21T23:55:57Z
224,003
83
2008-10-22T00:00:27Z
[ "python", "django", "django-templates" ]
I need to perform a filtered query from within a django template, to get a set of objects equivalent to python code within a view: ``` queryset = Modelclass.objects.filter(somekey=foo) ``` In my template I would like to do ``` {% for object in data.somekey_set.FILTER %} ``` but I just can't seem to find out how to ...
You can't do this, which is by design. The Django framework authors intended a strict separation of presentation code from data logic. Filtering models is data logic, and outputting HTML is presentation logic. So you have several options. The easiest is to do the filtering, then pass the result to `render_to_response`...
How do I perform query filtering in django templates
223,990
50
2008-10-21T23:55:57Z
230,615
10
2008-10-23T17:22:35Z
[ "python", "django", "django-templates" ]
I need to perform a filtered query from within a django template, to get a set of objects equivalent to python code within a view: ``` queryset = Modelclass.objects.filter(somekey=foo) ``` In my template I would like to do ``` {% for object in data.somekey_set.FILTER %} ``` but I just can't seem to find out how to ...
I run into this problem on a regular basis and often use the "add a method" solution. However, there are definitely cases where "add a method" or "compute it in the view" don't work (or don't work well). E.g. when you are caching template fragments and need some non-trivial DB computation to produce it. You don't want ...
How do I perform query filtering in django templates
223,990
50
2008-10-21T23:55:57Z
14,010,929
7
2012-12-23T12:27:28Z
[ "python", "django", "django-templates" ]
I need to perform a filtered query from within a django template, to get a set of objects equivalent to python code within a view: ``` queryset = Modelclass.objects.filter(somekey=foo) ``` In my template I would like to do ``` {% for object in data.somekey_set.FILTER %} ``` but I just can't seem to find out how to ...
This can be solved with an assignment tag: ``` from django import template register = template.Library() @register.assignment_tag def query(qs, **kwargs): """ template tag which allows queryset filtering. Usage: {% query books author=author as mybooks %} {% for book in mybooks %} ...
How do I perform query filtering in django templates
223,990
50
2008-10-21T23:55:57Z
16,429,027
14
2013-05-07T21:41:18Z
[ "python", "django", "django-templates" ]
I need to perform a filtered query from within a django template, to get a set of objects equivalent to python code within a view: ``` queryset = Modelclass.objects.filter(somekey=foo) ``` In my template I would like to do ``` {% for object in data.somekey_set.FILTER %} ``` but I just can't seem to find out how to ...
I just add an extra template tag like this: ``` @register.filter def in_category(things, category): return things.filter(category=category) ``` Then I can do: ``` {% for category in categories %} {% for thing in things|in_category:category %} {{ thing }} {% endfor %} {% endfor %} ```
Javascript style dot notation for dictionary keys unpythonic?
224,026
25
2008-10-22T00:08:01Z
224,080
12
2008-10-22T00:40:31Z
[ "python", "coding-style" ]
I've started to use constructs like these: ``` class DictObj(object): def __init__(self): self.d = {} def __getattr__(self, m): return self.d.get(m, None) def __setattr__(self, m, v): super.__setattr__(self, m, v) ``` Update: based on this thread, I've revised the DictObj implement...
With regards to the `DictObj`, would the following work for you? A blank class will allow you to arbitrarily add to or replace stuff in a container object. ``` class Container(object): pass >>> myContainer = Container() >>> myContainer.spam = "in a can" >>> myContainer.eggs = "in a shell" ``` If you want to not ...
Javascript style dot notation for dictionary keys unpythonic?
224,026
25
2008-10-22T00:08:01Z
224,722
8
2008-10-22T07:06:02Z
[ "python", "coding-style" ]
I've started to use constructs like these: ``` class DictObj(object): def __init__(self): self.d = {} def __getattr__(self, m): return self.d.get(m, None) def __setattr__(self, m, v): super.__setattr__(self, m, v) ``` Update: based on this thread, I've revised the DictObj implement...
This is a simpler version of your DictObj class: ``` class DictObj(object): def __getattr__(self, attr): return self.__dict__.get(attr) >>> d = DictObj() >>> d.something = 'one' >>> print d.something one >>> print d.somethingelse None >>> ```
Javascript style dot notation for dictionary keys unpythonic?
224,026
25
2008-10-22T00:08:01Z
224,876
22
2008-10-22T08:29:47Z
[ "python", "coding-style" ]
I've started to use constructs like these: ``` class DictObj(object): def __init__(self): self.d = {} def __getattr__(self, m): return self.d.get(m, None) def __setattr__(self, m, v): super.__setattr__(self, m, v) ``` Update: based on this thread, I've revised the DictObj implement...
Your DictObj example is actually quite common. Object-style dot-notation access can be a win if you are dealing with ‘things that resemble objects’, ie. they have fixed property names containing only characters valid in Python identifiers. Stuff like database rows or form submissions can be usefully stored in this ...
RFC 1123 Date Representation in Python?
225,086
45
2008-10-22T09:59:21Z
225,106
66
2008-10-22T10:07:19Z
[ "python", "http", "datetime" ]
Is there a fairly easy way to convert a datetime object into an RFC 1123 (HTTP/1.1) date/time string, i.e. a string with the format ``` Sun, 06 Nov 1994 08:49:37 GMT ``` Using `strftime` does not work, since the strings are locale-dependant. Do I have to build the string by hand?
You can use wsgiref.handlers.format\_date\_time from the stdlib which does not rely on locale settings ``` from wsgiref.handlers import format_date_time from datetime import datetime from time import mktime now = datetime.now() stamp = mktime(now.timetuple()) print format_date_time(stamp) #--> Wed, 22 Oct 2008 10:52:...
RFC 1123 Date Representation in Python?
225,086
45
2008-10-22T09:59:21Z
225,177
26
2008-10-22T10:34:04Z
[ "python", "http", "datetime" ]
Is there a fairly easy way to convert a datetime object into an RFC 1123 (HTTP/1.1) date/time string, i.e. a string with the format ``` Sun, 06 Nov 1994 08:49:37 GMT ``` Using `strftime` does not work, since the strings are locale-dependant. Do I have to build the string by hand?
You can use the formatdate() function from the Python standard email module: ``` from email.utils import formatdate print formatdate(timeval=None, localtime=False, usegmt=True) ``` Gives the current time in the desired format: ``` Wed, 22 Oct 2008 10:32:33 GMT ``` In fact, this function does it "by hand" without us...
Parsing different date formats from feedparser in python?
225,274
8
2008-10-22T11:09:20Z
225,382
14
2008-10-22T11:35:42Z
[ "python", "datetime", "parsing", "rss", "feedparser" ]
I'm trying to get the dates from entries in two different RSS feeds through [feedparser](http://feedparser.org). Here is what I'm doing: ``` import feedparser as fp reddit = fp.parse("http://www.reddit.com/.rss") cc = fp.parse("http://contentconsumer.com/feed") print reddit.entries[0].date print cc.entries[0].date ``...
Parsing of dates is a pain with RSS feeds in-the-wild, and that's where `feedparser` can be a big help. If you use the `*_parsed` properties (like `updated_parsed`), `feedparser` will have done the work and will return a 9-tuple Python date in UTC. See <http://packages.python.org/feedparser/date-parsing.html> for mor...
"Pretty" Continuous Integration for Python
225,598
112
2008-10-22T12:49:54Z
225,788
10
2008-10-22T13:46:55Z
[ "python", "jenkins", "continuous-integration", "buildbot" ]
This is a slightly.. vain question, but BuildBot's output isn't particularly nice to look at.. For example, compared to.. * [phpUnderControl](http://phpundercontrol.org/about.html) * [Jenkins](http://jenkins-ci.org/content/about-jenkins-ci) + [Hudson](http://blogs.oracle.com/arungupta/entry/top_10_features_of_hudso...
Don't know if it would do : [Bitten](http://bitten.edgewall.org/) is made by the guys who write Trac and is integrated with Trac. [Apache Gump](http://gump.apache.org/) is the CI tool used by Apache. It is written in Python.
"Pretty" Continuous Integration for Python
225,598
112
2008-10-22T12:49:54Z
228,196
9
2008-10-23T01:30:17Z
[ "python", "jenkins", "continuous-integration", "buildbot" ]
This is a slightly.. vain question, but BuildBot's output isn't particularly nice to look at.. For example, compared to.. * [phpUnderControl](http://phpundercontrol.org/about.html) * [Jenkins](http://jenkins-ci.org/content/about-jenkins-ci) + [Hudson](http://blogs.oracle.com/arungupta/entry/top_10_features_of_hudso...
We've had great success with [TeamCity](http://www.jetbrains.com/teamcity/) as our CI server and using nose as our test runner. [Teamcity plugin for nosetests](http://pypi.python.org/pypi/teamcity-nose) gives you count pass/fail, readable display for failed test( that can be E-Mailed). You can even see details of the t...
"Pretty" Continuous Integration for Python
225,598
112
2008-10-22T12:49:54Z
667,800
40
2009-03-20T20:13:24Z
[ "python", "jenkins", "continuous-integration", "buildbot" ]
This is a slightly.. vain question, but BuildBot's output isn't particularly nice to look at.. For example, compared to.. * [phpUnderControl](http://phpundercontrol.org/about.html) * [Jenkins](http://jenkins-ci.org/content/about-jenkins-ci) + [Hudson](http://blogs.oracle.com/arungupta/entry/top_10_features_of_hudso...
You might want to check out [Nose](http://somethingaboutorange.com/mrl/projects/nose/) and [the Xunit output plugin](http://nose.readthedocs.org/en/latest/plugins/xunit.html). You can have it run your unit tests, and coverage checks with this command: ``` nosetests --with-xunit --enable-cover ``` That'll be helpful i...
"Pretty" Continuous Integration for Python
225,598
112
2008-10-22T12:49:54Z
2,026,520
8
2010-01-08T09:16:55Z
[ "python", "jenkins", "continuous-integration", "buildbot" ]
This is a slightly.. vain question, but BuildBot's output isn't particularly nice to look at.. For example, compared to.. * [phpUnderControl](http://phpundercontrol.org/about.html) * [Jenkins](http://jenkins-ci.org/content/about-jenkins-ci) + [Hudson](http://blogs.oracle.com/arungupta/entry/top_10_features_of_hudso...
Buildbot's waterfall page can be considerably prettified. Here's a nice example <http://build.chromium.org/buildbot/waterfall/waterfall>
Unexpected list comprehension behaviour in Python
225,675
6
2008-10-22T13:15:08Z
225,801
14
2008-10-22T13:50:47Z
[ "python", "list-comprehension", "language-implementation" ]
I believe I'm getting bitten by some combination of nested scoping rules and list comprehensions. [Jeremy Hylton's blog post](http://www.python.org/~jeremy/weblog/040204.html) is suggestive about the causes, but I don't really understand CPython's implementation well-enough to figure out how to get around this. Here i...
The problem is that with `return self.display` you return a *reference* to this list (not a copy). So what you end up with is a list where each element is a reference to self.display. To illustrate, look at the following: ``` >>> a = [1,2] >>> b = [a,a] >>> b [[1, 2], [1, 2]] >>> a.append(3) >>> b [[1, 2, 3], [1, 2, 3...
Batch Renaming of Files in a Directory
225,735
55
2008-10-22T13:33:23Z
227,125
64
2008-10-22T18:59:57Z
[ "python", "file-io", "rename", "batch-rename" ]
Is there an easy way to rename a group of files already contained in a directory, using Python? **Example:** I have a directory full of \*.doc files and I want to rename them in a consistent way. > X.doc -> "new(X).doc" > > Y.doc -> "new(Y).doc"
Such renaming is quite easy, for example with [os](http://docs.python.org/lib/module-os.html) and [glob](http://docs.python.org/lib/module-glob.html) modules: ``` import glob, os def rename(dir, pattern, titlePattern): for pathAndFilename in glob.iglob(os.path.join(dir, pattern)): title, ext = os.path.spl...
Batch Renaming of Files in a Directory
225,735
55
2008-10-22T13:33:23Z
227,209
12
2008-10-22T19:30:05Z
[ "python", "file-io", "rename", "batch-rename" ]
Is there an easy way to rename a group of files already contained in a directory, using Python? **Example:** I have a directory full of \*.doc files and I want to rename them in a consistent way. > X.doc -> "new(X).doc" > > Y.doc -> "new(Y).doc"
If you don't mind using regular expressions, then this function would give you much power in renaming files: ``` import re, glob, os def renamer(files, pattern, replacement): for pathname in glob.glob(files): basename= os.path.basename(pathname) new_filename= re.sub(pattern, replacement, basename)...
Batch Renaming of Files in a Directory
225,735
55
2008-10-22T13:33:23Z
7,917,798
54
2011-10-27T14:53:14Z
[ "python", "file-io", "rename", "batch-rename" ]
Is there an easy way to rename a group of files already contained in a directory, using Python? **Example:** I have a directory full of \*.doc files and I want to rename them in a consistent way. > X.doc -> "new(X).doc" > > Y.doc -> "new(Y).doc"
I prefer writing small one liners for each replace I have to do instead of making a more generic and complex code. E.g.: This replaces all underscores with hyphens in any non-hidden file in the current directory ``` import os [os.rename(f, f.replace('_', '-')) for f in os.listdir('.') if not f.startswith('.')] ```
Batch Renaming of Files in a Directory
225,735
55
2008-10-22T13:33:23Z
20,371,910
7
2013-12-04T09:46:49Z
[ "python", "file-io", "rename", "batch-rename" ]
Is there an easy way to rename a group of files already contained in a directory, using Python? **Example:** I have a directory full of \*.doc files and I want to rename them in a consistent way. > X.doc -> "new(X).doc" > > Y.doc -> "new(Y).doc"
I have this to simply rename all files in subfolders of folder ``` import os def replace(fpath, old_str, new_str): for path, subdirs, files in os.walk(fpath): for name in files: if(old_str.lower() in name.lower()): os.rename(os.path.join(path,name), os.path.join(path, ...
Django Forms - How to Use Prefix Parameter
226,510
16
2008-10-22T16:10:03Z
226,568
29
2008-10-22T16:27:38Z
[ "python", "html", "django", "forms" ]
Say I have a form like: ``` class GeneralForm(forms.Form): field1 = forms.IntegerField(required=False) field2 = forms. IntegerField(required=False) ``` And I want to show it twice on a page within one form tag each time with a different prefix e.g.,: ``` rest of page ... <form ..> GeneralForm(data,prefix="fo...
You process each form as you normally would, ensuring that you create instances which have the same prefixes as those used to generate the form initially. Here's a slightly awkward example using the form you've given, as I don't know what the exact use case is: ``` def some_view(request): if request.method == 'PO...
How does one put a link / url to the web-site's home page in Django?
226,528
17
2008-10-22T16:14:40Z
226,540
32
2008-10-22T16:19:44Z
[ "python", "django", "django-urls" ]
In Django templates, is there a variable in the context (e.g. `{{ BASE\_URL }}`, `{{ ROOT\_URL }}`, or `{{ MEDIA\_URL }}` that one can use to link to the `home` url of a project? I.e. if Django is running in the root of a project, the variable (let's call it R) `{{ R }}` in a template would be `/`. If the root url is ...
You could give the URL configuration which you're using to handle the home page a name and use that: urls.py: ``` from django.conf.urls.defaults import * urlpatterns = patterns('myproject.views', url(r'^$', 'index', name='index'), ) ``` Templates: ``` <a href="{% url index %}">... ``` This note in the Django ...
Python Disk-Based Dictionary
226,693
34
2008-10-22T17:00:11Z
226,796
18
2008-10-22T17:34:09Z
[ "python", "database", "dictionary", "disk-based" ]
I was running some dynamic programming code (trying to brute-force disprove the Collatz conjecture =P) and I was using a dict to store the lengths of the chains I had already computed. Obviously, it ran out of memory at some point. Is there any easy way to use some variant of a `dict` which will page parts of itself ou...
Hash-on-disk is generally addressed with Berkeley DB or something similar - several options are listed in the [Python Data Persistence documentation](http://docs.python.org/library/persistence.html). You can front it with an in-memory cache, but I'd test against native performance first; with operating system caching i...
Python Disk-Based Dictionary
226,693
34
2008-10-22T17:00:11Z
228,837
49
2008-10-23T07:22:01Z
[ "python", "database", "dictionary", "disk-based" ]
I was running some dynamic programming code (trying to brute-force disprove the Collatz conjecture =P) and I was using a dict to store the lengths of the chains I had already computed. Obviously, it ran out of memory at some point. Is there any easy way to use some variant of a `dict` which will page parts of itself ou...
The 3rd party [shove](http://pypi.python.org/pypi/shove) module is also worth taking a look at. It's very similar to shelve in that it is a simple dict-like object, however it can store to various backends (such as file, SVN, and S3), provides optional compression, and is even threadsafe. It's a very handy module ``` ...
How do you create a simple Google Talk Client using the Twisted Words Python library?
227,279
16
2008-10-22T19:48:33Z
228,959
7
2008-10-23T08:32:31Z
[ "python", "twisted", "xmpp", "google-talk" ]
I am interested in making a Google Talk client using Python and would like to use the Twisted libraries Words module. I have looked at the examples, but they don't work with the current implementation of Google Talk. Has anybody had any luck with this? Would you mind documenting a brief tutorial? As a simple task, I'...
I have written a simple Jabber bot (and thus Google talk bot) using the `xmpppy` library, which works well. The examples on [xmpppy](http://xmpppy.sourceforge.net/) should get you started (specifically [`bot.py`](http://xmpppy.sourceforge.net/examples/bot.py)) As for something actually implemented in twisted.Words: [...
How do you create a simple Google Talk Client using the Twisted Words Python library?
227,279
16
2008-10-22T19:48:33Z
327,229
14
2008-11-29T05:42:54Z
[ "python", "twisted", "xmpp", "google-talk" ]
I am interested in making a Google Talk client using Python and would like to use the Twisted libraries Words module. I have looked at the examples, but they don't work with the current implementation of Google Talk. Has anybody had any luck with this? Would you mind documenting a brief tutorial? As a simple task, I'...
wokkel is the future of twisted words. [metajack](http://metajack.im/) wrote a really nice [blog post](http://metajack.im/2008/09/25/an-xmpp-echo-bot-with-twisted-and-wokkel/) on getting started. If you want a nice, functional sample project to start with, check out my [whatsup](http://github.com/dustin/whatsup) bot.
Solving an inequality for minimum value
227,282
3
2008-10-22T19:48:55Z
227,319
11
2008-10-22T19:59:29Z
[ "python", "language-agnostic", "equation", "linear-programming", "inequality" ]
I'm working on a programming problem which boils down to a set of an equation and inequality: ``` x[0]*a[0] + x[1]*a[1] + ... x[n]*a[n] >= D x[0]*b[0] + x[1]*b[1] + ... x[n]*b[n] = C ``` I want to solve for the values of `X` that will give the absolute minimum of `C`, given the input `D` and lists and `A` and `B` co...
This looks like a [linear programming](http://en.wikipedia.org/wiki/Linear_programming) problem. The [Simplex algorithm](http://en.wikipedia.org/wiki/Simplex_algorithm) normally gives good results. It basically walks the boundaries of the subspace delimited by the inequalities, looking for the optimum. Think of it vis...
ASCII value of a character in Python
227,459
548
2008-10-22T20:39:57Z
227,466
34
2008-10-22T20:41:56Z
[ "python", "ascii" ]
How do I get the [ASCII](http://en.wikipedia.org/wiki/ASCII) value of a character as an int in [Python](http://en.wikipedia.org/wiki/Python_%28programming_language%29)?
You are looking for: ``` ord() ```
ASCII value of a character in Python
227,459
548
2008-10-22T20:39:57Z
227,472
705
2008-10-22T20:43:04Z
[ "python", "ascii" ]
How do I get the [ASCII](http://en.wikipedia.org/wiki/ASCII) value of a character as an int in [Python](http://en.wikipedia.org/wiki/Python_%28programming_language%29)?
From [here](http://mail.python.org/pipermail/python-win32/2005-April/003100.html): > function ord() would get the int value > of the char. And in case you want to > convert back after playing with the > number, function chr() does the trick. ``` >>> ord('a') 97 >>> chr(97) 'a' >>> chr(ord('a') + 3) 'd' >>> ``` There...
ASCII value of a character in Python
227,459
548
2008-10-22T20:39:57Z
227,889
113
2008-10-22T23:19:20Z
[ "python", "ascii" ]
How do I get the [ASCII](http://en.wikipedia.org/wiki/ASCII) value of a character as an int in [Python](http://en.wikipedia.org/wiki/Python_%28programming_language%29)?
Note that ord() doesn't give you the ASCII value per se; it gives you the numeric value of the character in whatever encoding it's in. Therefore the result of ord('ä') can be 228 if you're using Latin-1, or it can raise a TypeError if you're using UTF-8. It can even return the Unicode codepoint instead if you pass it ...
Open file, read it, process, and write back - shortest method in Python
227,461
13
2008-10-22T20:40:00Z
230,416
25
2008-10-23T16:28:39Z
[ "python", "coding-style" ]
I want to do some basic filtering on a file. Read it, do processing, write it back. I'm not looking for "golfing", but want the simplest and most elegant method to achieve this. I came up with: ``` from __future__ import with_statement filename = "..." # or sys.argv... with open(filename) as f: new_txt = # ...s...
Actually an easier way using fileinput is to use the inplace parameter: ``` import fileinput for line in fileinput.input (filenameToProcess, inplace=1): process (line) ``` If you use the inplace parameter it will redirect stdout to your file, so that if you do a print it will write back to your file. This exampl...
Passing a list while retaining the original
227,790
12
2008-10-22T22:38:49Z
227,802
10
2008-10-22T22:42:32Z
[ "python", "list" ]
So I'm teaching myself Python, and I'm having an issue with lists. I want to pass my function a list and pop items off it while retaining the original list. How do I make python "instance" the passed list rather that passing a pointer to the original one? Example: ``` def burninate(b): c = [] for i in range(3...
You can call `burninate()` with a copy of the list like this: `d = burninate(a[:])` or, `d = burninate(list(a))` The other alternative is to make a copy of the list in your method: ``` def burninate(b): c=[] b=b[:] for i in range(3): c.append(b.pop()) return c >>> a = range(6) >>> b = burn...
Passing a list while retaining the original
227,790
12
2008-10-22T22:38:49Z
227,855
14
2008-10-22T23:00:37Z
[ "python", "list" ]
So I'm teaching myself Python, and I'm having an issue with lists. I want to pass my function a list and pop items off it while retaining the original list. How do I make python "instance" the passed list rather that passing a pointer to the original one? Example: ``` def burninate(b): c = [] for i in range(3...
As other answers have suggested, you can provide your function with a copy of the list. As an alternative, your function could take a copy of the argument: ``` def burninate(b): c = [] b = list(b) for i in range(3): c.append(b.pop()) return c ``` Basically, you need to be clear in your mind (...
What's win32con module in python? Where can I find it?
227,928
17
2008-10-22T23:38:30Z
227,930
10
2008-10-22T23:40:26Z
[ "python", "module" ]
I'm building an open source project that uses python and c++ in Windows. I came to the following error message: ``` ImportError: No module named win32con ``` The same happened in a "prebuilt" code that it's working ( except in my computer :P ) I think this is kind of "popular" module in python because I've saw seve...
This module contains constants related to Win32 programming. It is not part of the Python 2.6 release, but should be part of the download of the pywin32 project. **Edit:** I imagine that the executable is an installation program, though the last time I downloaded pywin32 it was just a zip file.
Python debugger: Stepping into a function that you have called interactively
228,642
25
2008-10-23T05:35:32Z
228,653
17
2008-10-23T05:42:00Z
[ "python", "debugging", "pdb" ]
Python is quite cool, but unfortunately, its debugger is not as good as perl -d. One thing that I do very commonly when experimenting with code is to call a function from within the debugger, and step into that function, like so: ``` # NOTE THAT THIS PROGRAM EXITS IMMEDIATELY WITHOUT CALLING FOO() ~> cat -n /tmp/show...
And I've answered my own question! It's the "debug" command in pydb: ``` ~> cat -n /tmp/test_python.py 1 #!/usr/local/bin/python 2 3 def foo(): 4 print "hi" 5 print "bye" 6 7 exit(0) 8 ~> pydb /tmp/test_python.py (/tmp/test_python.py:7): <module> 7 exit(0) (Pydb...
Python debugger: Stepping into a function that you have called interactively
228,642
25
2008-10-23T05:35:32Z
229,380
14
2008-10-23T11:27:26Z
[ "python", "debugging", "pdb" ]
Python is quite cool, but unfortunately, its debugger is not as good as perl -d. One thing that I do very commonly when experimenting with code is to call a function from within the debugger, and step into that function, like so: ``` # NOTE THAT THIS PROGRAM EXITS IMMEDIATELY WITHOUT CALLING FOO() ~> cat -n /tmp/show...
You can interactively debug a function with pdb as well, provided the script you want to debug does not exit() at the end: ``` $ cat test.py #!/usr/bin/python def foo(f, g): h = f+g print h return 2*f ``` To debug, start an interactive python session and import pdb: ``` $ python Python 2.5.1...
How to get hex string from signed integer
228,702
7
2008-10-23T06:14:02Z
228,708
21
2008-10-23T06:17:15Z
[ "python" ]
Say I have the classic 4-byte signed integer, and I want something like print hex(-1) to give me something like >> 0xffffffff In reality, the above gives me -0x1. I'm dawdling about in some lower level language, and python commandline is quick n easy. So.. is there a way to do it?
This will do the trick: ``` >>> print hex (-1 & 0xffffffff) 0xffffffffL ``` or, in function form (and stripping off the trailing "L"): ``` >>> def hex2(n): ... return hex (n & 0xffffffff)[:-1] ... >>> print hex2(-1) 0xffffffff >>> print hex2(17) 0x11 ``` or, a variant that always returns fixed size (there may w...
How do I iterate through a string in Python?
228,730
39
2008-10-23T06:32:30Z
228,762
14
2008-10-23T06:49:27Z
[ "python" ]
As an example, lets say I wanted to list the frequency of each letter of the alphabet in a string. What would be the easiest way to do it? This is an example of what I'm thinking of... the question is how to make allTheLetters equal to said letters without something like allTheLetters = "abcdefg...xyz". In many other ...
> the question is how to make > allTheLetters equal to said letters > without something like allTheLetters = > "abcdefg...xyz" That's actually provided by the string module, it's not like you have to manually type it yourself ;) ``` import string allTheLetters = string.ascii_lowercase def alphCount(text): lowerTe...
How do I iterate through a string in Python?
228,730
39
2008-10-23T06:32:30Z
228,790
9
2008-10-23T07:04:14Z
[ "python" ]
As an example, lets say I wanted to list the frequency of each letter of the alphabet in a string. What would be the easiest way to do it? This is an example of what I'm thinking of... the question is how to make allTheLetters equal to said letters without something like allTheLetters = "abcdefg...xyz". In many other ...
If you just want to do a frequency count of a string, try this: ``` s = 'hi there' f = {} for c in s: f[c] = f.get(c, 0) + 1 print f ```
How do I iterate through a string in Python?
228,730
39
2008-10-23T06:32:30Z
228,850
72
2008-10-23T07:28:05Z
[ "python" ]
As an example, lets say I wanted to list the frequency of each letter of the alphabet in a string. What would be the easiest way to do it? This is an example of what I'm thinking of... the question is how to make allTheLetters equal to said letters without something like allTheLetters = "abcdefg...xyz". In many other ...
The question you've asked (how to iterate through the alphabet) is not the same question as the problem you're trying to solve (how to count the frequency of letters in a string). You can use string.lowercase, as other posters have suggested: ``` import string allTheLetters = string.lowercase ``` To do things the wa...
SQLite parameter substitution problem
228,912
45
2008-10-23T08:13:36Z
228,981
113
2008-10-23T08:41:23Z
[ "python", "sqlite" ]
Using SQLite3 with Python 2.5, I'm trying to iterate through a list and pull the weight of an item from the database based on the item's name. I tried using the "?" parameter substitution suggested to prevent SQL injections but it doesn't work. For example, when I use: ``` for item in self.inventory_names: self.c...
The `Cursor.execute()` method expects a sequence as second parameter. You are supplying a string which happens to be 8 characters long. Use the following form instead: ``` self.cursor.execute("SELECT weight FROM Equipment WHERE name = ?", [item]) ``` Python library reference 13.13.3: sqlite3 [Cursor Objects](http://...
SQLite parameter substitution problem
228,912
45
2008-10-23T08:13:36Z
597,198
28
2009-02-28T00:32:57Z
[ "python", "sqlite" ]
Using SQLite3 with Python 2.5, I'm trying to iterate through a list and pull the weight of an item from the database based on the item's name. I tried using the "?" parameter substitution suggested to prevent SQL injections but it doesn't work. For example, when I use: ``` for item in self.inventory_names: self.c...
I have spent half a day trying to figure out why something like this would give me an error: ``` cursor.execute("SELECT * from ? WHERE name = ?", (table_name, name)) ``` only to find out that table names *cannot be parametrized*. Hope this will help other people save some time.
SQLite parameter substitution problem
228,912
45
2008-10-23T08:13:36Z
7,305,758
21
2011-09-05T08:51:03Z
[ "python", "sqlite" ]
Using SQLite3 with Python 2.5, I'm trying to iterate through a list and pull the weight of an item from the database based on the item's name. I tried using the "?" parameter substitution suggested to prevent SQL injections but it doesn't work. For example, when I use: ``` for item in self.inventory_names: self.c...
The argument of `cursor.execute` that represents the values you need inserted in the database should be a tuple (sequence). However consider this example and see what's happening: ``` >>> ('jason') 'jason' >>> ('jason',) ('jason',) ``` The first example evaluates to a string instead; so the correct way of representi...
os.walk without digging into directories below
229,186
50
2008-10-23T10:03:59Z
229,219
108
2008-10-23T10:15:38Z
[ "python", "file", "os.walk" ]
How do I limit `os.walk` to only return files in the directory I provide it? ``` def _dir_list(self, dir_name, whitelist): outputList = [] for root, dirs, files in os.walk(dir_name): for f in files: if os.path.splitext(f)[1] in whitelist: outputList.append(os.path.join(root,...
Don't use os.walk. Example: ``` import os root = "C:\\" for item in os.listdir(root): if os.path.isfile(os.path.join(root, item)): print item ```
os.walk without digging into directories below
229,186
50
2008-10-23T10:03:59Z
229,293
11
2008-10-23T10:46:22Z
[ "python", "file", "os.walk" ]
How do I limit `os.walk` to only return files in the directory I provide it? ``` def _dir_list(self, dir_name, whitelist): outputList = [] for root, dirs, files in os.walk(dir_name): for f in files: if os.path.splitext(f)[1] in whitelist: outputList.append(os.path.join(root,...
The suggestion to use `listdir` is a good one. The direct answer to your question is `root, dirs, files = os.walk(dir_name).next()`
os.walk without digging into directories below
229,186
50
2008-10-23T10:03:59Z
234,329
54
2008-10-24T16:46:02Z
[ "python", "file", "os.walk" ]
How do I limit `os.walk` to only return files in the directory I provide it? ``` def _dir_list(self, dir_name, whitelist): outputList = [] for root, dirs, files in os.walk(dir_name): for f in files: if os.path.splitext(f)[1] in whitelist: outputList.append(os.path.join(root,...
Use the `walklevel` function. ``` import os def walklevel(some_dir, level=1): some_dir = some_dir.rstrip(os.path.sep) assert os.path.isdir(some_dir) num_sep = some_dir.count(os.path.sep) for root, dirs, files in os.walk(some_dir): yield root, dirs, files num_sep_this = root.count(os.pa...
os.walk without digging into directories below
229,186
50
2008-10-23T10:03:59Z
20,868,760
9
2014-01-01T12:44:22Z
[ "python", "file", "os.walk" ]
How do I limit `os.walk` to only return files in the directory I provide it? ``` def _dir_list(self, dir_name, whitelist): outputList = [] for root, dirs, files in os.walk(dir_name): for f in files: if os.path.splitext(f)[1] in whitelist: outputList.append(os.path.join(root,...
I think the solution is actually very simple. use ``` break ``` to only do first iteration of the for loop, there must be a more elegant way. ``` for root, dirs, files in os.walk(dir_name): ... ... break ``` The first time you call os.walk, it returns tulips for the current directory, then on next loop the...
Python Find Question
229,352
2
2008-10-23T11:15:42Z
229,401
9
2008-10-23T11:32:46Z
[ "python", "url" ]
I am using Python to extract the filename from a link using rfind like below: ``` url = "http://www.google.com/test.php" print url[url.rfind("/") +1 : ] ``` This works ok with links without a / at the end of them and returns "test.php". I have encountered links with / at the end like so "http://www.google.com/test.p...
Just removing the slash at the end won't work, as you can probably have a URL that looks like this: ``` http://www.google.com/test.php?filepath=tests/hey.xml ``` ...in which case you'll get back "hey.xml". Instead of manually checking for this, you can use **urlparse** to get rid of the parameters, then do the check ...
How to flush output of Python print?
230,751
605
2008-10-23T17:59:39Z
230,774
765
2008-10-23T18:04:59Z
[ "python", "printing", "flush" ]
How do I force Python's print function to output to the screen?
``` import sys sys.stdout.flush() ``` Print by default prints to `sys.stdout`. References: * <http://docs.python.org/reference/simple_stmts.html#the-print-statement> * <http://docs.python.org/library/sys.html> * <http://docs.python.org/library/stdtypes.html#file-objects>
How to flush output of Python print?
230,751
605
2008-10-23T17:59:39Z
230,780
229
2008-10-23T18:06:49Z
[ "python", "printing", "flush" ]
How do I force Python's print function to output to the screen?
Running `python -h`, I see a *command line option*: > -u : unbuffered binary stdout and stderr; also PYTHONUNBUFFERED=x > see man page for details on internal buffering relating to '-u' Here is the [relevant doc](http://docs.python.org/using/cmdline.html#cmdoption-u).
How to flush output of Python print?
230,751
605
2008-10-23T17:59:39Z
231,216
26
2008-10-23T19:54:26Z
[ "python", "printing", "flush" ]
How do I force Python's print function to output to the screen?
Using the `-u` command-line switch works, but it is a little bit clumsy. It would mean that the program would potentially behave incorrectly if the user invoked the script without the `-u` option. I usually use a custom `stdout`, like this: ``` class flushfile(file): def __init__(self, f): self.f = f def writ...
How to flush output of Python print?
230,751
605
2008-10-23T17:59:39Z
288,536
12
2008-11-13T22:15:25Z
[ "python", "printing", "flush" ]
How do I force Python's print function to output to the screen?
Dan's idea doesn't quite work: ``` #!/usr/bin/env python class flushfile(file): def __init__(self, f): self.f = f def write(self, x): self.f.write(x) self.f.flush() import sys sys.stdout = flushfile(sys.stdout) print "foo" ``` The result: ``` Traceback (most recent call last): Fil...
How to flush output of Python print?
230,751
605
2008-10-23T17:59:39Z
741,601
17
2009-04-12T10:57:58Z
[ "python", "printing", "flush" ]
How do I force Python's print function to output to the screen?
Why not try using an unbuffered file? ``` f = open('xyz.log', 'a', 0) ``` OR ``` sys.stdout = open('out.log', 'a', 0) ```
How to flush output of Python print?
230,751
605
2008-10-23T17:59:39Z
8,471,288
11
2011-12-12T07:46:41Z
[ "python", "printing", "flush" ]
How do I force Python's print function to output to the screen?
``` import sys print 'This will be output immediately.' sys.stdout.flush() ```
How to flush output of Python print?
230,751
605
2008-10-23T17:59:39Z
9,462,099
55
2012-02-27T08:38:27Z
[ "python", "printing", "flush" ]
How do I force Python's print function to output to the screen?
Also as suggested in [this blog](http://algorithmicallyrandom.blogspot.com/2009/10/python-tips-and-tricks-flushing-stdout.html) one can reopen `sys.stdout` in unbuffered mode: ``` sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0) ``` Each `stdout.write` and `print` operation will be automatically flushed afterwards...
How to flush output of Python print?
230,751
605
2008-10-23T17:59:39Z
23,142,556
143
2014-04-17T20:10:31Z
[ "python", "printing", "flush" ]
How do I force Python's print function to output to the screen?
Since Python 3.3, you can force the normal `print()` function to flush without the need to use `sys.stdout.flush()`; just set the "flush" keyword argument to true. From [the documentation](https://docs.python.org/3.3/library/functions.html#print): > **print(\*objects, sep=' ', end='\n', file=sys.stdout, flush=False)**...
How to flush output of Python print?
230,751
605
2008-10-23T17:59:39Z
33,265,549
8
2015-10-21T17:23:32Z
[ "python", "printing", "flush" ]
How do I force Python's print function to output to the screen?
``` print("Foo", flush=True) ``` Like that
How to flush output of Python print?
230,751
605
2008-10-23T17:59:39Z
35,467,658
11
2016-02-17T21:01:03Z
[ "python", "printing", "flush" ]
How do I force Python's print function to output to the screen?
> # How to flush output of Python print? ## Python 3.3+ Using Python 3.3 or higher, you can just provide `flush=True` as a keyword argument to the `print` function: ``` print('foo', flush=True) ``` ## Python 2 (or < 3.3) They did not backport the `flush` argument to Python 2.7 So if you're using Python 2 (or less ...
Make python enter password when running a csh script
230,845
5
2008-10-23T18:22:33Z
230,986
7
2008-10-23T18:58:34Z
[ "python", "scripting", "passwords", "root", "csh" ]
I'm writing a python script that executes a csh script in Solaris 10. The csh script prompts the user for the root password (which I know) but I'm not sure how to make the python script answer the prompt with the password. Is this possible? Here is what I'm using to execute the csh script: ``` import commands command...
Have a look at the [pexpect](http://www.noah.org/wiki/Pexpect) module. It is designed to deal with interactive programs, which seems to be your case. Oh, and remember that hard-encoding root's password in a shell or python script is potentially a security hole :D
Given a list of variable names in Python, how do I a create a dictionary with the variable names as keys (to the variables' values)?
230,896
13
2008-10-23T18:33:51Z
231,368
14
2008-10-23T20:29:33Z
[ "python", "list", "dictionary" ]
I have a list of variable names, like this: ``` ['foo', 'bar', 'baz'] ``` (I originally asked how I convert a list of variables. See Greg Hewgill's answer below.) How do I convert this to a dictionary where the keys are the variable names (as strings) and the values are the values of the variables? ``` {'foo': foo,...
Forget filtering `locals()`! The dictionary you give to the formatting string is allowed to contain unused keys: ``` >>> name = 'foo' >>> zip = 123 >>> unused = 'whoops!' >>> locals() {'name': 'foo', 'zip': 123, ... 'unused': 'whoops!', ...} >>> '%(name)s %(zip)i' % locals() 'foo 123' ```
What does the "yield" keyword do?
231,767
5,524
2008-10-23T22:21:11Z
231,778
141
2008-10-23T22:24:03Z
[ "python", "iterator", "generator", "yield", "coroutine" ]
What is the use of the `yield` keyword in Python? What does it do? For example, I'm trying to understand this code**1**: ``` def _get_child_candidates(self, distance, min_dist, max_dist): if self._leftchild and distance - max_dist < self._median: yield self._leftchild if self._rightchild and distance ...
`yield` is just like `return` - it returns whatever you tell it to. The only difference is that the next time you call the function, execution starts from the last call to the `yield` statement. In the case of your code, the function `get_child_candidates` is acting like an iterator so that when you extend your list, ...
What does the "yield" keyword do?
231,767
5,524
2008-10-23T22:21:11Z
231,788
78
2008-10-23T22:26:06Z
[ "python", "iterator", "generator", "yield", "coroutine" ]
What is the use of the `yield` keyword in Python? What does it do? For example, I'm trying to understand this code**1**: ``` def _get_child_candidates(self, distance, min_dist, max_dist): if self._leftchild and distance - max_dist < self._median: yield self._leftchild if self._rightchild and distance ...
It's returning a generator. I'm not particularly familiar with Python, but I believe it's the same kind of thing as [C#'s iterator blocks](http://csharpindepth.com/Articles/Chapter11/StreamingAndIterators.aspx) if you're familiar with those. There's an [IBM article](http://www.ibm.com/developerworks/library/l-pycon.ht...
What does the "yield" keyword do?
231,767
5,524
2008-10-23T22:21:11Z
231,801
236
2008-10-23T22:28:41Z
[ "python", "iterator", "generator", "yield", "coroutine" ]
What is the use of the `yield` keyword in Python? What does it do? For example, I'm trying to understand this code**1**: ``` def _get_child_candidates(self, distance, min_dist, max_dist): if self._leftchild and distance - max_dist < self._median: yield self._leftchild if self._rightchild and distance ...
Think of it this way: An iterator is just a fancy sounding term for an object that has a next() method. So a yield-ed function ends up being something like this: Original version: ``` def some_function(): for i in xrange(4): yield i for i in some_function(): print i ``` This is basically what the p...
What does the "yield" keyword do?
231,767
5,524
2008-10-23T22:21:11Z
231,855
8,384
2008-10-23T22:48:44Z
[ "python", "iterator", "generator", "yield", "coroutine" ]
What is the use of the `yield` keyword in Python? What does it do? For example, I'm trying to understand this code**1**: ``` def _get_child_candidates(self, distance, min_dist, max_dist): if self._leftchild and distance - max_dist < self._median: yield self._leftchild if self._rightchild and distance ...
To understand what `yield` does, you must understand what *generators* are. And before generators come *iterables*. ## Iterables When you create a list, you can read its items one by one. Reading its items one by one is called iteration: ``` >>> mylist = [1, 2, 3] >>> for i in mylist: ... print(i) 1 2 3 ``` `myl...
What does the "yield" keyword do?
231,767
5,524
2008-10-23T22:21:11Z
232,111
72
2008-10-24T00:36:05Z
[ "python", "iterator", "generator", "yield", "coroutine" ]
What is the use of the `yield` keyword in Python? What does it do? For example, I'm trying to understand this code**1**: ``` def _get_child_candidates(self, distance, min_dist, max_dist): if self._leftchild and distance - max_dist < self._median: yield self._leftchild if self._rightchild and distance ...
An example in plain language. I will provide a correspondence between high-level human concepts to low-level python concepts. I want to operate on a sequence of numbers, but I don't want to bother my self with the creation of that sequence, I want only to focus on the operation I want to do. So, I do the following: *...