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
Difference between dict.clear() and assigning {} in Python
369,898
104
2008-12-15T22:23:18Z
369,928
21
2008-12-15T22:32:02Z
[ "python", "dictionary" ]
In python, is there a difference between calling `clear()` and assigning `{}` to a dictionary? If yes, what is it? Example: ``` d = {"stuff":"things"} d.clear() #this way d = {} #vs this way ```
`d = {}` will create a new instance for `d` but all other references will still point to the old contents. `d.clear()` will reset the contents, but all references to the same instance will still be correct.
Difference between dict.clear() and assigning {} in Python
369,898
104
2008-12-15T22:23:18Z
371,045
13
2008-12-16T11:31:10Z
[ "python", "dictionary" ]
In python, is there a difference between calling `clear()` and assigning `{}` to a dictionary? If yes, what is it? Example: ``` d = {"stuff":"things"} d.clear() #this way d = {} #vs this way ```
In addition to the differences mentioned in other answers, there also is a speed difference. d = {} is over twice as fast: ``` python -m timeit -s "d = {}" "for i in xrange(500000): d.clear()" 10 loops, best of 3: 127 msec per loop python -m timeit -s "d = {}" "for i in xrange(500000): d = {}" 10 loops, best of 3: 53...
command-line world clock?
370,075
4
2008-12-15T23:39:23Z
370,105
13
2008-12-15T23:50:55Z
[ "python", "timezone", "command-line-interface" ]
Is there a script to display a simple world clock (time in various places around the world) on a \*nix terminal? I was thinking of writing a quick Python script, but I have a feeling that's gonna be more work than I think (e.g. due to config and output format) - not to mention reinventing the wheel...
I have this bourne shell script: ``` #!/bin/sh PT=`env TZ=US/Pacific date` CT=`env TZ=US/Central date` AT=`env TZ=Australia/Melbourne date` echo "Santa Clara $PT" echo "Central $CT" echo "Melbourne $AT" ```
Python variable scope error
370,357
136
2008-12-16T03:06:52Z
370,363
150
2008-12-16T03:12:56Z
[ "python", "variables", "scope" ]
I've been programming for many years, and recently started learning Python. The following code works as expected in both python 2.5 and 3.0 (on OS X if that matters): ``` a, b, c = (1, 2, 3) print(a, b, c) def test(): print(a) print(b) print(c) # (A) #c+=1 # (B) test() ``` However, when I u...
Python treats variables in functions differently depending on whether you assign values to them from within the function or not. If you assign any value to a variable, it is treated by default as a local variable. Therefore, when you uncomment the line, you are attempting to reference a local variable before any value ...
Python variable scope error
370,357
136
2008-12-16T03:06:52Z
370,364
8
2008-12-16T03:12:59Z
[ "python", "variables", "scope" ]
I've been programming for many years, and recently started learning Python. The following code works as expected in both python 2.5 and 3.0 (on OS X if that matters): ``` a, b, c = (1, 2, 3) print(a, b, c) def test(): print(a) print(b) print(c) # (A) #c+=1 # (B) test() ``` However, when I u...
Python has rather interesting behavior when you try traditional global variable semantics. I don't remember the details, but you can read the value of a variable declared in 'global' scope just fine, if you want to modify it, you have to use the global keyword. Try changing test() to this: ``` def test(): global c...
Python variable scope error
370,357
136
2008-12-16T03:06:52Z
370,380
54
2008-12-16T03:25:29Z
[ "python", "variables", "scope" ]
I've been programming for many years, and recently started learning Python. The following code works as expected in both python 2.5 and 3.0 (on OS X if that matters): ``` a, b, c = (1, 2, 3) print(a, b, c) def test(): print(a) print(b) print(c) # (A) #c+=1 # (B) test() ``` However, when I u...
okay, here's the deal. Python is a little weird, in that it keeps everything in a dictionary for the various scopes. The original a,b,c are in the uppermost scope and so in that uppermost dictionary. The function has its own dictionary. When you reach the `print(a)` and `print(b)` statements, there's nothing by that na...
Python variable scope error
370,357
136
2008-12-16T03:06:52Z
370,830
38
2008-12-16T09:49:28Z
[ "python", "variables", "scope" ]
I've been programming for many years, and recently started learning Python. The following code works as expected in both python 2.5 and 3.0 (on OS X if that matters): ``` a, b, c = (1, 2, 3) print(a, b, c) def test(): print(a) print(b) print(c) # (A) #c+=1 # (B) test() ``` However, when I u...
Taking a look at the disassembly may clarify what is happening: ``` >>> def f(): ... print a ... print b ... a = 1 >>> import dis >>> dis.dis(f) 2 0 LOAD_FAST 0 (a) 3 PRINT_ITEM 4 PRINT_NEWLINE 3 5 LOAD_GLOBAL 0 (b) ...
Differences between Python game libraries Pygame and Pyglet?
370,680
33
2008-12-16T07:55:22Z
371,249
25
2008-12-16T13:08:52Z
[ "python", "pygame", "pyglet" ]
I've had some experience with Pygame, but there seems to be a lot of buzz around Pyglet these days. How do these two libraries compare? What would be the advantage of using one over the other, both in features and ease of use? Finally, would you say that one is more Pythonic than the other?
**Pygame: LGPL license** *Pyglet: BSD license* **Pygame relies on SDL libraries heavily** *Pyglet is a pure python library with fewer dependencies, I think it requires better understanding of OpenGL* **Pygame is around here for a long time, a lot of people used it** *Pyglet is a new lib* **Pygame is geared toward...
Differences between Python game libraries Pygame and Pyglet?
370,680
33
2008-12-16T07:55:22Z
397,025
21
2008-12-29T02:40:06Z
[ "python", "pygame", "pyglet" ]
I've had some experience with Pygame, but there seems to be a lot of buzz around Pyglet these days. How do these two libraries compare? What would be the advantage of using one over the other, both in features and ease of use? Finally, would you say that one is more Pythonic than the other?
I was considering both Pygame and Pyglet for a small 2D shooter, and after looking at source code and some tutorials went with Pyglet. I was very happy with the results. Pyglet worked immediately and was enjoyable to work with, and conceptually very clean. It certainly had a Pythonic feel to me: you could get a straig...
Differences between Python game libraries Pygame and Pyglet?
370,680
33
2008-12-16T07:55:22Z
4,520,448
9
2010-12-23T16:08:56Z
[ "python", "pygame", "pyglet" ]
I've had some experience with Pygame, but there seems to be a lot of buzz around Pyglet these days. How do these two libraries compare? What would be the advantage of using one over the other, both in features and ease of use? Finally, would you say that one is more Pythonic than the other?
Pyglet is good (for 2D games) if you never intend to draw any vector graphics or primitives within the game itself, and just stick to loading images from disk. It's also much cleaner because there's no need to write you're own game loop and have to worry about speed and timing and responsiveness. However, if you ever ...
Trac documentation?
370,733
12
2008-12-16T08:50:10Z
370,755
11
2008-12-16T08:58:33Z
[ "python", "documentation", "trac" ]
I'm trying to write my first little plugin for [Trac](http://trac.edgewall.org) and am kind of lost as to what the API exactly is. For example, exactly which fields are offered for "ticket" objects, among many other things. Does anyone know of a good place to look for Trac API documentation? Can't find anything on the...
The component architecture is important, but the real starting page for development is: <http://trac.edgewall.org/wiki/TracDev> Have also a look at the trac-hacks web site <http://trac-hacks.org/> This is really a good source of examples, and many times you will find something close to what you want to do, that you ca...
What's the most pythonic way of testing that inputs are well-formed numbers
371,419
2
2008-12-16T14:15:10Z
371,461
12
2008-12-16T14:26:45Z
[ "python", "idioms" ]
I have a function that expects real numbers (either integers or floats) as its input, and I'm trying to validate this input before doing mathematical operations on it. My first instinct is to cast inputs as floats from within a try-except block. ``` try: myinput = float(input) except: raise ValueError("input is...
To quote myself from [How much input validation should I be doing on my python functions/methods?](http://stackoverflow.com/questions/367560/how-much-input-validation-should-i-be-doing-on-my-python-functionsmethods#368072): > For calculations like sum, factorial etc, pythons built-in type checks will do fine. The calc...
Python - Using __getattribute__ method
371,753
50
2008-12-16T16:04:38Z
371,833
73
2008-12-16T16:26:37Z
[ "python", "oop", "class", "recursion" ]
I want to override access to one variable in a class, but return all others normally. How do I accomplish this with `__getattribute__`? I tried the following (which should also illustrate what I'm trying to do) but I get a recursion error: ``` class D(object): def __init__(self): self.test=20 self...
You get a recursion error because you call the same function, your `__getattribute__`. If you use `object`'s `__getattribute__` instead, it works: ``` class D(object): def __init__(self): self.test=20 self.test2=21 def __getattribute__(self,name): if name=='test': return 0. ...
Python - Using __getattribute__ method
371,753
50
2008-12-16T16:04:38Z
371,844
13
2008-12-16T16:32:36Z
[ "python", "oop", "class", "recursion" ]
I want to override access to one variable in a class, but return all others normally. How do I accomplish this with `__getattribute__`? I tried the following (which should also illustrate what I'm trying to do) but I get a recursion error: ``` class D(object): def __init__(self): self.test=20 self...
Are you sure you want to use `__getattribute__`? What are you actually trying to achieve? The easiest way to do what you ask is: ``` class D(object): def __init__(self): self.test = 20 self.test2 = 21 test = 0 ``` or: ``` class D(object): def __init__(self): self.test = 20 ...
Python - Using __getattribute__ method
371,753
50
2008-12-16T16:04:38Z
371,864
15
2008-12-16T16:39:23Z
[ "python", "oop", "class", "recursion" ]
I want to override access to one variable in a class, but return all others normally. How do I accomplish this with `__getattribute__`? I tried the following (which should also illustrate what I'm trying to do) but I get a recursion error: ``` class D(object): def __init__(self): self.test=20 self...
[Python language reference:](http://docs.python.org/reference/datamodel.html#object.__getattribute__) > In order to avoid infinite recursion > in this method, its implementation > should always call the base class > method with the same name to access > any attributes it needs, for example, > `object.__getattribute__(...
Python - Using __getattribute__ method
371,753
50
2008-12-16T16:04:38Z
372,919
19
2008-12-16T22:01:38Z
[ "python", "oop", "class", "recursion" ]
I want to override access to one variable in a class, but return all others normally. How do I accomplish this with `__getattribute__`? I tried the following (which should also illustrate what I'm trying to do) but I get a recursion error: ``` class D(object): def __init__(self): self.test=20 self...
Actually, I believe you want to use the `__getattr__` special method instead. Quote from the Python docs: > `__getattr__( self, name)` > > Called when an attribute lookup has not found the attribute in the usual places (i.e. it is not an instance attribute nor is it found in the class tree for self). name is the attr...
When is white space not important in Python?
372,007
3
2008-12-16T17:21:05Z
372,025
14
2008-12-16T17:26:39Z
[ "python", "whitespace" ]
When is white space not important in Python? It seems to be ignored inside a list, for example: ``` for x in range(5): list += [x, 1 ,2,3, 4,5] ```
White space is only important for indentation of statements. You have a single statement across several lines, and only the indentation of the beginning of the statement on the first line is significant. See *[Python: Myths about Indentation](http://www.secnetix.de/~olli/Python/block_indentation.hawk)* for more informa...
When is white space not important in Python?
372,007
3
2008-12-16T17:21:05Z
372,108
7
2008-12-16T17:52:23Z
[ "python", "whitespace" ]
When is white space not important in Python? It seems to be ignored inside a list, for example: ``` for x in range(5): list += [x, 1 ,2,3, 4,5] ```
Your question is really about when Python implicitly joins lines of code. Python will implicitly join lines that are contained within (parentheses), {braces}, and [brackets], as in your example code. You can also explicitly join lines with a backslash (\) at the end of a line. More here on [implicit line continuation...
Difference between abstract class and interface in Python
372,042
302
2008-12-16T17:32:27Z
372,066
29
2008-12-16T17:38:22Z
[ "python", "interface", "abstract-class" ]
What is the difference between abstract class and interface in Python?
Python doesn't really have either concept. It uses duck typing, which removed the need for interfaces (at least for the computer :-)) Python <= 2.5: Base classes obviously exist, but there is no explicit way to mark a method as 'pure virtual', so the class isn't really abstract. Python >= 2.6: Abstract base classes ...
Difference between abstract class and interface in Python
372,042
302
2008-12-16T17:32:27Z
372,107
85
2008-12-16T17:51:35Z
[ "python", "interface", "abstract-class" ]
What is the difference between abstract class and interface in Python?
Python >= 2.6 has [Abstract Base Classes](http://docs.python.org/library/abc.html). > Abstract Base Classes (abbreviated > ABCs) complement duck-typing by > providing a way to define interfaces > when other techniques like hasattr() > would be clumsy. Python comes with > many builtin ABCs for data structures > (in the...
Difference between abstract class and interface in Python
372,042
302
2008-12-16T17:32:27Z
372,121
355
2008-12-16T17:59:23Z
[ "python", "interface", "abstract-class" ]
What is the difference between abstract class and interface in Python?
What you'll see sometimes is the following: ``` class Abstract1( object ): """Some description that tells you it's abstract, often listing the methods you're expected to supply.""" def aMethod( self ): raise NotImplementedError( "Should have implemented this" ) ``` Because Python doesn't have (and...
Difference between abstract class and interface in Python
372,042
302
2008-12-16T17:32:27Z
372,188
12
2008-12-16T18:19:55Z
[ "python", "interface", "abstract-class" ]
What is the difference between abstract class and interface in Python?
In general, interfaces are used only in languages that use the single-inheritance class model. In these single-inheritance languages, interfaces are typically used if any class could use a particular method or set of methods. Also in these single-inheritance languages, abstract classes are used to either have defined c...
Difference between abstract class and interface in Python
372,042
302
2008-12-16T17:32:27Z
16,447,106
21
2013-05-08T17:51:11Z
[ "python", "interface", "abstract-class" ]
What is the difference between abstract class and interface in Python?
In a more basic way to explain: An interface is sort of like an empty muffin pan. It's a class file with a set of method definitions that have no code. An abstract class is the same thing, but not all functions need to be empty. Some can have code. It's not strictly empty. Why differentiate: There's not much practica...
Difference between abstract class and interface in Python
372,042
302
2008-12-16T17:32:27Z
31,439,126
37
2015-07-15T19:15:20Z
[ "python", "interface", "abstract-class" ]
What is the difference between abstract class and interface in Python?
> # What is the difference between abstract class and interface in Python? In Python, there is none! An abstract class defines an interface. ## Using an Abstract Base Class For example, say we want to use one of the abstract base classes from the `collections` module: ``` import collections class MySet(collections....
UTF in Python Regex
372,102
7
2008-12-16T17:49:12Z
372,128
7
2008-12-16T18:01:19Z
[ "python", "regex" ]
I'm aware that Python 3 fixes a lot of UTF issues, I am not however able to use Python 3, I am using 2.5.1 I'm trying to regex a document but the document has UTF hyphens in it – rather than -. Python can't match these and if I put them in the regex it throws a wobbly. How can I force Python to use a UTF string or ...
You have to escape the character in question (–) and put a u in front of the string literal to make it a unicode string. So, for example, this: ``` re.compile("–") ``` becomes this: ``` re.compile(u"\u2013") ```
Set timeout for xmlrpclib.ServerProxy
372,365
14
2008-12-16T19:22:27Z
1,766,187
16
2009-11-19T20:09:22Z
[ "python", "xml-rpc" ]
I am using xmlrpclib.ServerProxy to make RPC calls to a remote server. If there is not a network connection to the server it takes the default 10 seconds to return a socket.gaierror to my program. This is annoying when doing development without a network connection, or if the remote server is down. Is there a way to u...
An more straightforward solution is at: <http://www.devpicayune.com/entry/200609191448> ``` import xmlrpclib import socket x = xmlrpclib.ServerProxy('http:1.2.3.4') socket.setdefaulttimeout(10) #set the timeout to 10 seconds x.func_name(args) #times out after 10 seconds socket.setdefaultt...
Set timeout for xmlrpclib.ServerProxy
372,365
14
2008-12-16T19:22:27Z
2,116,786
14
2010-01-22T11:10:29Z
[ "python", "xml-rpc" ]
I am using xmlrpclib.ServerProxy to make RPC calls to a remote server. If there is not a network connection to the server it takes the default 10 seconds to return a socket.gaierror to my program. This is annoying when doing development without a network connection, or if the remote server is down. Is there a way to u...
clean non global version. ``` import xmlrpclib import httplib class TimeoutHTTPConnection(httplib.HTTPConnection): def connect(self): httplib.HTTPConnection.connect(self) self.sock.settimeout(self.timeout) class TimeoutHTTP(httplib.HTTP): _connection_class = TimeoutHTTPConnection def s...
How do I connect to a MySQL Database in Python?
372,885
674
2008-12-16T21:49:09Z
372,896
118
2008-12-16T21:51:56Z
[ "python", "mysql" ]
How do I connect to a MySQL database using a python program?
Here's one way to do it. ``` #!/usr/bin/python import MySQLdb # connect db = MySQLdb.connect(host="localhost", user="appuser", passwd="", db="onco") cursor = db.cursor() # execute SQL select statement cursor.execute("SELECT * FROM LOCATION") # commit your changes db.commit() # get the number of rows in the result...
How do I connect to a MySQL Database in Python?
372,885
674
2008-12-16T21:49:09Z
372,899
15
2008-12-16T21:52:49Z
[ "python", "mysql" ]
How do I connect to a MySQL database using a python program?
Try using MySQLdb There is a how to page here: <http://www.kitebird.com/articles/pydbapi.html> --- From the page: ``` # server_version.py - retrieve and display database server version import MySQLdb conn = MySQLdb.connect (host = "localhost", user = "testuser", pas...
How do I connect to a MySQL Database in Python?
372,885
674
2008-12-16T21:49:09Z
622,308
837
2009-03-07T18:57:34Z
[ "python", "mysql" ]
How do I connect to a MySQL database using a python program?
## Connecting to MYSQL with Python in 3 steps **1 - Setting** You must install a MySQL driver before doing anything. Unlike PHP, only the SQLite driver is installed by default with Python. The most used package to do so is [MySQLdb](http://pypi.python.org/pypi/MySQL-python/) but it's hard to install it using easy\_in...
How do I connect to a MySQL Database in Python?
372,885
674
2008-12-16T21:49:09Z
12,904,258
16
2012-10-15T21:25:05Z
[ "python", "mysql" ]
How do I connect to a MySQL database using a python program?
As a db driver, there is also [oursql](http://packages.python.org/oursql/index.html). Some of the reasons listed on that link, which say why oursql is better: > * oursql has real parameterization, sending the SQL and data to MySQL completely separately. > * oursql allows text or binary data to be streamed into the dat...
How do I connect to a MySQL Database in Python?
372,885
674
2008-12-16T21:49:09Z
16,796,108
70
2013-05-28T15:39:22Z
[ "python", "mysql" ]
How do I connect to a MySQL database using a python program?
Oracle (MySQL) now supports a pure Python connector. That means no binaries to install: it's just a Python library. It's called "Connector/Python". <http://dev.mysql.com/downloads/connector/python/>
How do I connect to a MySQL Database in Python?
372,885
674
2008-12-16T21:49:09Z
20,959,654
64
2014-01-06T21:32:15Z
[ "python", "mysql" ]
How do I connect to a MySQL database using a python program?
If you do not need MySQLdb, but would accept any library, I would very, very much recommend MySQL Connector/Python from MySQL: <http://dev.mysql.com/downloads/connector/python/>. It is one package (around 110k), pure Python, so it is system independent, and dead simple to install. You just download, double-click, conf...
How do I connect to a MySQL Database in Python?
372,885
674
2008-12-16T21:49:09Z
34,503,728
18
2015-12-29T02:52:13Z
[ "python", "mysql" ]
How do I connect to a MySQL database using a python program?
> Stop Using MySQLDb if you want to avoid installing mysql headers just to access mysql from python. Use [pymysql](https://github.com/PyMySQL/PyMySQL) it does all of what MySQLDb does but it was implemented purely in python with ***NO External Dependencies***. This makes the installation process on all operating syste...
Finding the Current Active Window in Mac OS X using Python
373,020
12
2008-12-16T22:33:02Z
373,310
18
2008-12-17T00:44:22Z
[ "python", "objective-c", "cocoa", "osx" ]
Is there a way to find the application name of the current active window at a given time on Mac OS X using Python?
This should work: ``` #!/usr/bin/python from AppKit import NSWorkspace activeAppName = NSWorkspace.sharedWorkspace().activeApplication()['NSApplicationName'] print activeAppName ``` Only works on Leopard, or on Tiger if you have PyObjC installed and happen to point at the right python binary in line one (not the cas...
Finding the Current Active Window in Mac OS X using Python
373,020
12
2008-12-16T22:33:02Z
25,214,024
8
2014-08-09T00:20:52Z
[ "python", "objective-c", "cocoa", "osx" ]
Is there a way to find the application name of the current active window at a given time on Mac OS X using Python?
The method in the accepted answer was deprecated in OS X 10.7+. The current recommended version would be the following: ``` from AppKit import NSWorkspace active_app_name = NSWorkspace.sharedWorkspace().frontmostApplication().localizedName() print active_app_name ```
Python regex for MD5 hash
373,194
15
2008-12-16T23:45:02Z
373,207
40
2008-12-16T23:51:02Z
[ "python", "regex", "md5" ]
I've come up with: ``` re.findall("([a-fA-F\d]*)", data) ``` but it's not very fool proof, is there a better way to grab all MD5-hash codes?
Well, since md5 is just a string of 32 hex digits, about all you could add to your expression is a check for "32 digits", perhaps something like this? ``` re.findall(r"([a-fA-F\d]{32})", data) ```
Python regex for MD5 hash
373,194
15
2008-12-16T23:45:02Z
373,286
11
2008-12-17T00:31:29Z
[ "python", "regex", "md5" ]
I've come up with: ``` re.findall("([a-fA-F\d]*)", data) ``` but it's not very fool proof, is there a better way to grab all MD5-hash codes?
When using regular expressions in Python, you should almost always use the raw string syntax `r"..."`: ``` re.findall(r"([a-fA-F\d]{32})", data) ``` This will ensure that the backslash in the string is not interpreted by the normal Python escaping, but is instead passed through to the `re.findall` function so it can ...
Python regex for MD5 hash
373,194
15
2008-12-16T23:45:02Z
376,889
7
2008-12-18T04:13:35Z
[ "python", "regex", "md5" ]
I've come up with: ``` re.findall("([a-fA-F\d]*)", data) ``` but it's not very fool proof, is there a better way to grab all MD5-hash codes?
Here's a better way to do it than some of the other solutions: ``` re.findall(r'(?i)(?<![a-z0-9])[a-f0-9]{32}(?![a-z0-9])', data) ``` This ensures that the match must be a string of 32 hexadecimal digit characters, *but which is not contained within a larger string of other alphanumeric characters.* With all the othe...
How do I get a Cron like scheduler in Python?
373,335
137
2008-12-17T00:56:31Z
373,410
10
2008-12-17T01:45:17Z
[ "python", "cron" ]
I'm looking for a library in Python which will provide `at` and `cron` like functionality. I'd quite like have a pure Python solution, rather than relying on tools installed on the box; this way I run on machines with no cron. For those unfamiliar with `cron`: you can schedule tasks based upon an expression like: ``...
One thing that in my searches I've seen is python's [`sched`](http://docs.python.org/library/sched.html) module which might be the kind of thing you're looking for.
How do I get a Cron like scheduler in Python?
373,335
137
2008-12-17T00:56:31Z
373,789
9
2008-12-17T06:23:28Z
[ "python", "cron" ]
I'm looking for a library in Python which will provide `at` and `cron` like functionality. I'd quite like have a pure Python solution, rather than relying on tools installed on the box; this way I run on machines with no cron. For those unfamiliar with `cron`: you can schedule tasks based upon an expression like: ``...
[TurboGears](http://turbogears.com/) ships with scheduled task capability based on [Kronos](http://www.razorvine.net/download/kronos.py) I've never used Kronos directly, but the scheduling in TG has a decent set of features and is solid.
How do I get a Cron like scheduler in Python?
373,335
137
2008-12-17T00:56:31Z
374,207
48
2008-12-17T10:48:11Z
[ "python", "cron" ]
I'm looking for a library in Python which will provide `at` and `cron` like functionality. I'd quite like have a pure Python solution, rather than relying on tools installed on the box; this way I run on machines with no cron. For those unfamiliar with `cron`: you can schedule tasks based upon an expression like: ``...
You could just use normal Python argument passing syntax to specify your crontab. For example, suppose we define an Event class as below: ``` from datetime import datetime, timedelta import time # Some utility classes / functions first class AllMatch(set): """Universal set - match everything""" def __contains...
How do I get a Cron like scheduler in Python?
373,335
137
2008-12-17T00:56:31Z
2,946,908
9
2010-06-01T02:01:21Z
[ "python", "cron" ]
I'm looking for a library in Python which will provide `at` and `cron` like functionality. I'd quite like have a pure Python solution, rather than relying on tools installed on the box; this way I run on machines with no cron. For those unfamiliar with `cron`: you can schedule tasks based upon an expression like: ``...
More or less same as above but concurrent using gevent :) ``` """Gevent based crontab implementation""" from datetime import datetime, timedelta import gevent # Some utility classes / functions first def conv_to_set(obj): """Converts to set allowing single integer to be provided""" if isinstance(obj, (int, ...
How do I get a Cron like scheduler in Python?
373,335
137
2008-12-17T00:56:31Z
3,292,913
17
2010-07-20T18:03:41Z
[ "python", "cron" ]
I'm looking for a library in Python which will provide `at` and `cron` like functionality. I'd quite like have a pure Python solution, rather than relying on tools installed on the box; this way I run on machines with no cron. For those unfamiliar with `cron`: you can schedule tasks based upon an expression like: ``...
Check out [Celery](http://celery.readthedocs.org/en/latest/userguide/periodic-tasks.html), they have periodic tasks like cron.
How do I get a Cron like scheduler in Python?
373,335
137
2008-12-17T00:56:31Z
5,256,822
28
2011-03-10T07:46:32Z
[ "python", "cron" ]
I'm looking for a library in Python which will provide `at` and `cron` like functionality. I'd quite like have a pure Python solution, rather than relying on tools installed on the box; this way I run on machines with no cron. For those unfamiliar with `cron`: you can schedule tasks based upon an expression like: ``...
maybe this has come up only after the question was asked; I thought I just mention it for completeness sake: <https://apscheduler.readthedocs.org/en/latest/>
How do I get a Cron like scheduler in Python?
373,335
137
2008-12-17T00:56:31Z
13,831,944
13
2012-12-12T02:39:58Z
[ "python", "cron" ]
I'm looking for a library in Python which will provide `at` and `cron` like functionality. I'd quite like have a pure Python solution, rather than relying on tools installed on the box; this way I run on machines with no cron. For those unfamiliar with `cron`: you can schedule tasks based upon an expression like: ``...
*"... Crontab module for read and writing crontab files and accessing the system cron automatically and simply using a direct API. ..."* <http://pypi.python.org/pypi/python-crontab> and also APScheduler, a python package. Already written & debugged. <http://packages.python.org/APScheduler/cronschedule.html>
How do I get a Cron like scheduler in Python?
373,335
137
2008-12-17T00:56:31Z
16,786,600
153
2013-05-28T07:48:31Z
[ "python", "cron" ]
I'm looking for a library in Python which will provide `at` and `cron` like functionality. I'd quite like have a pure Python solution, rather than relying on tools installed on the box; this way I run on machines with no cron. For those unfamiliar with `cron`: you can schedule tasks based upon an expression like: ``...
If you're looking for something lightweight checkout [schedule](https://github.com/dbader/schedule): ``` import schedule import time def job(): print("I'm working...") schedule.every(10).minutes.do(job) schedule.every().hour.do(job) schedule.every().day.at("10:30").do(job) while 1: schedule.run_pending() ...
How do I get the UTC time of "midnight" for a given timezone?
373,370
20
2008-12-17T01:11:07Z
381,788
29
2008-12-19T18:29:13Z
[ "python", "datetime", "timezone", "utc", "pytz" ]
The best I can come up with for now is this monstrosity: ``` >>> datetime.utcnow() \ ... .replace(tzinfo=pytz.UTC) \ ... .astimezone(pytz.timezone("Australia/Melbourne")) \ ... .replace(hour=0,minute=0,second=0,microsecond=0) \ ... .astimezone(pytz.UTC) \ ... .replace(tzinfo=None) datetime.datetime(2008, 12,...
I think you can shave off a few method calls if you do it like this: ``` >>> from datetime import datetime >>> datetime.now(pytz.timezone("Australia/Melbourne")) \ .replace(hour=0, minute=0, second=0, microsecond=0) \ .astimezone(pytz.utc) ``` BUT… there is a bigger problem than aesthetics i...
How do I get the UTC time of "midnight" for a given timezone?
373,370
20
2008-12-17T01:11:07Z
11,236,372
20
2012-06-27T23:57:46Z
[ "python", "datetime", "timezone", "utc", "pytz" ]
The best I can come up with for now is this monstrosity: ``` >>> datetime.utcnow() \ ... .replace(tzinfo=pytz.UTC) \ ... .astimezone(pytz.timezone("Australia/Melbourne")) \ ... .replace(hour=0,minute=0,second=0,microsecond=0) \ ... .astimezone(pytz.UTC) \ ... .replace(tzinfo=None) datetime.datetime(2008, 12,...
[@hop's answer](http://stackoverflow.com/a/381788/4279) is wrong on the day of transition from Daylight Saving Time (DST) e.g., Apr 1, 2012. To fix it [`tz.localize()`](http://pytz.sourceforge.net/#localized-times-and-date-arithmetic) could be used: ``` tz = pytz.timezone("Australia/Melbourne") today = datetime.now(tz...
split string on a number of different characters
373,459
11
2008-12-17T02:06:01Z
373,474
37
2008-12-17T02:16:43Z
[ "python", "string", "split" ]
I'd like to split a string using one or more separator characters. E.g. "a b.c", split on " " and "." would give the list ["a", "b", "c"]. At the moment, I can't see anything in the standard library to do this, and my own attempts are a bit clumsy. E.g. ``` def my_split(string, split_chars): if isinstance(string...
``` >>> import re >>> re.split('[ .]', 'a b.c') ['a', 'b', 'c'] ```
Running interactive commands in Paramiko
373,639
20
2008-12-17T04:16:02Z
373,870
22
2008-12-17T07:12:19Z
[ "python", "ssh", "paramiko" ]
I'm trying to run an interactive command through paramiko. The cmd execution tries to prompt for a password but I do not know how to supply the password through paramiko's exec\_command and the execution hangs. Is there a way to send values to the terminal if a cmd execution expects input interactively? ``` ssh = para...
The full paramiko distribution ships with a lot of good [demos](https://github.com/paramiko/paramiko/tree/master/demos). In the demos subdirectory, `demo.py` and `interactive.py` have full interactive TTY examples which would probably be overkill for your situation. In your example above `ssh_stdin` acts like a stand...
Convert C++ Header Files To Python
374,217
7
2008-12-17T10:53:00Z
375,270
11
2008-12-17T17:06:54Z
[ "c++", "python", "data-structures", "enums", "header" ]
I have a C++ header that contains #define statements, Enums and Structures. I have tried using the h2py.py script that is included with Python to no avail (except giving me the #defines converted). Any help would be greatly appreciated.
I don't know h2py, but you may want to look at 'ctypes' and 'ctypeslib'. ctypes is included with python 2.5+, and is targeted at creating binary compatibility with c-structs. If you add ctypeslib, you get a sub-tool called codegen, which has a 'h2xml.py' script, and a 'xml2py.py', the combination of which will auto-ge...
conversion of unicode string in python
374,318
3
2008-12-17T11:52:51Z
374,335
10
2008-12-17T11:58:56Z
[ "python", "string", "unicode", "unsigned", "signed" ]
I need to convert unicode strings in Python to other types such as unsigned and signed int 8 bits,unsigned and signed int 16 bits,unsigned and signed int 32 bits,unsigned and signed int 64 bits,double,float,string,unsigned and signed 8 bit,unsigned and signed 16 bit, unsigned and signed 32 bit,unsigned and signed 64 bi...
use [`int()`](http://docs.python.org/library/functions.html#int) to convert the string to an integer. Python doesn't have different fixed-width integers so you'll just get one type of thing out. Then use [`struct`](http://docs.python.org/library/struct.html) to pack the integer into a fixed width: ``` res = struct.pa...
How can I find all the subsets of a set, with exactly n elements?
374,626
30
2008-12-17T14:09:18Z
374,645
73
2008-12-17T14:15:07Z
[ "python" ]
I am writing a program in Python, and I realized that a problem I need to solve requires me, given a set `S` with `n` elements (|S|=n), to test a function on all possible subsets of a certain order `m` (i.e. with *m* number of elements). To use the answer to produce a partial solution, and then try again with the next ...
[itertools.combinations](http://docs.python.org/library/itertools.html#itertools.combinations) is your friend if you have Python 2.6 or greater. Otherwise, check the link for an implementation of an equivalent function. ``` import itertools def findsubsets(S,m): return set(itertools.combinations(S, m)) ```
How can I find all the subsets of a set, with exactly n elements?
374,626
30
2008-12-17T14:09:18Z
14,285,114
16
2013-01-11T19:16:23Z
[ "python" ]
I am writing a program in Python, and I realized that a problem I need to solve requires me, given a set `S` with `n` elements (|S|=n), to test a function on all possible subsets of a certain order `m` (i.e. with *m* number of elements). To use the answer to produce a partial solution, and then try again with the next ...
Here's a one-liner that gives you all subsets of the integers [0..n], not just the subsets of a given length: ``` from itertools import combinations, chain allsubsets = lambda n: list(chain(*[combinations(range(n), ni) for ni in range(n+1)])) ``` so e.g. ``` >> allsubsets(3) [(), (0,), (1,), (2,), (0, 1), (0, 2), (1...
How can I find all the subsets of a set, with exactly n elements?
374,626
30
2008-12-17T14:09:18Z
16,915,734
26
2013-06-04T10:41:13Z
[ "python" ]
I am writing a program in Python, and I realized that a problem I need to solve requires me, given a set `S` with `n` elements (|S|=n), to test a function on all possible subsets of a certain order `m` (i.e. with *m* number of elements). To use the answer to produce a partial solution, and then try again with the next ...
Using the canonical function to get the [powerset](http://en.wikipedia.org/wiki/Power_set) from the [the itertools recipe](http://docs.python.org/2/library/itertools.html#recipes) page: ``` from itertools import chain, combinations def powerset(iterable): xs = list(iterable) # note we return an iterator rather th...
How do I get the time a file was last modified in Python?
375,154
30
2008-12-17T16:33:41Z
375,168
30
2008-12-17T16:38:08Z
[ "python", "file", "time" ]
Assuming the file exists (using `os.path.exists(filename)` to first make sure that it does), how do I display the time a file was last modified? This is on Linux if that makes any difference.
[os.stat()](http://docs.python.org/library/os.html#os.stat) ``` import os filename = "/etc/fstab" statbuf = os.stat(filename) print "Modification time:",statbuf.st_mtime ``` Linux does not record the creation time of a file ([for most fileystems](http://unix.stackexchange.com/q/24441/61642)).
How do I get the time a file was last modified in Python?
375,154
30
2008-12-17T16:33:41Z
375,186
79
2008-12-17T16:41:59Z
[ "python", "file", "time" ]
Assuming the file exists (using `os.path.exists(filename)` to first make sure that it does), how do I display the time a file was last modified? This is on Linux if that makes any difference.
``` >>> import os >>> f = os.path.getmtime('test1.jpg') >>> f 1223995325.0 ``` since the beginning of (epoch)
Non-blocking read on a subprocess.PIPE in python
375,427
327
2008-12-17T17:56:34Z
375,503
8
2008-12-17T18:16:48Z
[ "python", "io", "subprocess", "nonblocking" ]
I'm using the [subprocess module](http://docs.python.org/library/subprocess.html) to start a subprocess and connect to it's output stream (stdout). I want to be able to execute non-blocking reads on its stdout. Is there a way to make .readline non-blocking or to check if there is data on the stream before I invoke `.re...
One solution is to make another process to perform your read of the process, or make a thread of the process with a timeout. Here's the threaded version of a timeout function: <http://code.activestate.com/recipes/473878/> However, do you need to read the stdout as it's coming in? Another solution may be to dump the ...
Non-blocking read on a subprocess.PIPE in python
375,427
327
2008-12-17T17:56:34Z
437,888
19
2009-01-13T03:36:16Z
[ "python", "io", "subprocess", "nonblocking" ]
I'm using the [subprocess module](http://docs.python.org/library/subprocess.html) to start a subprocess and connect to it's output stream (stdout). I want to be able to execute non-blocking reads on its stdout. Is there a way to make .readline non-blocking or to check if there is data on the stream before I invoke `.re...
Try the [asyncproc](http://www.lysator.liu.se/~bellman/download/asyncproc.py) module. For example: ``` import os from asyncproc import Process myProc = Process("myprogram.app") while True: # check to see if process has ended poll = myProc.wait(os.WNOHANG) if poll != None: break # print any new...
Non-blocking read on a subprocess.PIPE in python
375,427
327
2008-12-17T17:56:34Z
1,810,703
56
2009-11-27T21:33:52Z
[ "python", "io", "subprocess", "nonblocking" ]
I'm using the [subprocess module](http://docs.python.org/library/subprocess.html) to start a subprocess and connect to it's output stream (stdout). I want to be able to execute non-blocking reads on its stdout. Is there a way to make .readline non-blocking or to check if there is data on the stream before I invoke `.re...
I have often had a similar problem; Python programs I write frequently need to have the ability to execute some primary functionality while simultaneously accepting user input from the command line (stdin). Simply putting the user input handling functionality in another thread doesn't solve the problem because `readlin...
Non-blocking read on a subprocess.PIPE in python
375,427
327
2008-12-17T17:56:34Z
4,800,541
12
2011-01-26T01:02:08Z
[ "python", "io", "subprocess", "nonblocking" ]
I'm using the [subprocess module](http://docs.python.org/library/subprocess.html) to start a subprocess and connect to it's output stream (stdout). I want to be able to execute non-blocking reads on its stdout. Is there a way to make .readline non-blocking or to check if there is data on the stream before I invoke `.re...
Use select & read(1). ``` import subprocess #no new requirements def readAllSoFar(proc, retVal=''): while (select.select([proc.stdout],[],[],0)[0]!=[]): retVal+=proc.stdout.read(1) return retVal p = subprocess.Popen(['/bin/ls'], stdout=subprocess.PIPE) while not p.poll(): print (readAllSoFar(p)) ``` ...
Non-blocking read on a subprocess.PIPE in python
375,427
327
2008-12-17T17:56:34Z
4,896,288
263
2011-02-04T09:14:38Z
[ "python", "io", "subprocess", "nonblocking" ]
I'm using the [subprocess module](http://docs.python.org/library/subprocess.html) to start a subprocess and connect to it's output stream (stdout). I want to be able to execute non-blocking reads on its stdout. Is there a way to make .readline non-blocking or to check if there is data on the stream before I invoke `.re...
[`fcntl`](http://stackoverflow.com/questions/375427/non-blocking-read-on-a-stream-in-python/4025909#4025909), [`select`](http://stackoverflow.com/questions/375427/non-blocking-read-on-a-stream-in-python/375511#375511), [`asyncproc`](http://stackoverflow.com/questions/375427/non-blocking-read-on-a-stream-in-python/43788...
Non-blocking read on a subprocess.PIPE in python
375,427
327
2008-12-17T17:56:34Z
5,750,194
15
2011-04-21T21:54:55Z
[ "python", "io", "subprocess", "nonblocking" ]
I'm using the [subprocess module](http://docs.python.org/library/subprocess.html) to start a subprocess and connect to it's output stream (stdout). I want to be able to execute non-blocking reads on its stdout. Is there a way to make .readline non-blocking or to check if there is data on the stream before I invoke `.re...
You can do this really easily in [Twisted](http://twistedmatrix.com/trac/). Depending upon your existing code base, this might not be that easy to use, but if you are building a twisted application, then things like this become almost trivial. You create a `ProcessProtocol` class, and override the `outReceived()` metho...
Non-blocking read on a subprocess.PIPE in python
375,427
327
2008-12-17T17:56:34Z
11,362,426
7
2012-07-06T12:42:26Z
[ "python", "io", "subprocess", "nonblocking" ]
I'm using the [subprocess module](http://docs.python.org/library/subprocess.html) to start a subprocess and connect to it's output stream (stdout). I want to be able to execute non-blocking reads on its stdout. Is there a way to make .readline non-blocking or to check if there is data on the stream before I invoke `.re...
Disclaimer: this works only for tornado You can do this by setting the fd to be nonblocking and then use ioloop to register callbacks. I have packaged this in an egg called [tornado\_subprocess](http://pypi.python.org/pypi/tornado_subprocess/0.1.3) and you can install it via PyPI: ``` easy_install tornado_subprocess ...
Non-blocking read on a subprocess.PIPE in python
375,427
327
2008-12-17T17:56:34Z
20,697,159
24
2013-12-20T05:50:15Z
[ "python", "io", "subprocess", "nonblocking" ]
I'm using the [subprocess module](http://docs.python.org/library/subprocess.html) to start a subprocess and connect to it's output stream (stdout). I want to be able to execute non-blocking reads on its stdout. Is there a way to make .readline non-blocking or to check if there is data on the stream before I invoke `.re...
Python 3.4 introduces new [provisional API](http://www.python.org/dev/peps/pep-0411/) for asynchronous IO -- [`asyncio` module](http://docs.python.org/3/library/asyncio.html). The approach is similar to [`twisted`-based answer by @Bryan Ward](http://stackoverflow.com/a/5750194/4279) -- define a protocol and its method...
How do I create a wx.Image object from in-memory data?
375,820
4
2008-12-17T19:54:46Z
375,852
8
2008-12-17T20:08:11Z
[ "python", "wxpython", "wxwidgets" ]
I'm writing a GUI application in Python using wxPython and I want to display an image in a static control (`wx.StaticBitmap`). I can use [`wx.ImageFromStream`](http://www.wxpython.org/docs/api/wx-module.html#ImageFromStream) to load an image from a file, and this works OK: ``` static_bitmap = wx.StaticBitmap(parent, ...
You should be able to use `StringIO` to wrap the buffer in a memory file object. ``` ... import StringIO buf = open("test.jpg", "rb").read() # buf = get_image_data() sbuf = StringIO.StringIO(buf) image = wx.ImageFromStream(sbuf) ... ``` `buf` can be replaced with any data string.
How do you override vim options via comments in a python source code file?
376,111
15
2008-12-17T21:37:46Z
376,200
23
2008-12-17T22:02:51Z
[ "python", "vim" ]
I would like to set some vim options in one file in the comments section. For example, I would like to set this option in one file ``` set syntax=python ``` The file does not have a .py extension and I am not interested in making my vim installation recognise all files with this extension as python files. I know th...
You're wanting a [modeline](http://vim.wikia.com/wiki/Modeline_magic) The linked article should explain far better than I can.
How do you override vim options via comments in a python source code file?
376,111
15
2008-12-17T21:37:46Z
376,225
9
2008-12-17T22:13:05Z
[ "python", "vim" ]
I would like to set some vim options in one file in the comments section. For example, I would like to set this option in one file ``` set syntax=python ``` The file does not have a .py extension and I am not interested in making my vim installation recognise all files with this extension as python files. I know th...
I haven't used vim much, but I think what you want is to add a line like the following to the end of your file: ``` # vim: set syntax=python: ```
String concatenation vs. string substitution in Python
376,461
81
2008-12-17T23:39:39Z
376,508
42
2008-12-18T00:07:44Z
[ "python", "string", "string-concatenation" ]
In Python, the where and when of using string concatenation versus string substitution eludes me. As the string concatenation has seen large boosts in performance, is this (becoming more) a stylistic decision rather than a practical one? For a concrete example, how should one handle construction of flexible URIs: ```...
Concatenation is (significantly) faster according to my machine. But stylistically, I'm willing to pay the price of substitution if performance is not critical. Well, and if I need formatting, there's no need to even ask the question... there's no option but to use interpolation/templating. ``` >>> import timeit >>> d...
String concatenation vs. string substitution in Python
376,461
81
2008-12-17T23:39:39Z
376,512
7
2008-12-18T00:10:09Z
[ "python", "string", "string-concatenation" ]
In Python, the where and when of using string concatenation versus string substitution eludes me. As the string concatenation has seen large boosts in performance, is this (becoming more) a stylistic decision rather than a practical one? For a concrete example, how should one handle construction of flexible URIs: ```...
What you want to concatenate/interpolate and how you want to format the result should drive your decision. * String interpolation allows you to easily add formatting. In fact, your string interpolation version doesn't do the same thing as your concatenation version; it actually adds an extra forward slash before the `...
String concatenation vs. string substitution in Python
376,461
81
2008-12-17T23:39:39Z
376,523
11
2008-12-18T00:18:13Z
[ "python", "string", "string-concatenation" ]
In Python, the where and when of using string concatenation versus string substitution eludes me. As the string concatenation has seen large boosts in performance, is this (becoming more) a stylistic decision rather than a practical one? For a concrete example, how should one handle construction of flexible URIs: ```...
"As the string concatenation has seen large boosts in performance..." If performance matters, this is good to know. However, performance problems I've seen have never come down to string operations. I've generally gotten in trouble with I/O, sorting and O(*n*2) operations being the bottlenecks. Until string operatio...
String concatenation vs. string substitution in Python
376,461
81
2008-12-17T23:39:39Z
376,530
27
2008-12-18T00:22:59Z
[ "python", "string", "string-concatenation" ]
In Python, the where and when of using string concatenation versus string substitution eludes me. As the string concatenation has seen large boosts in performance, is this (becoming more) a stylistic decision rather than a practical one? For a concrete example, how should one handle construction of flexible URIs: ```...
Don't forget about named substitution: ``` def so_question_uri_namedsub(q_num): return "%(domain)s%(questions)s/%(q_num)d" % locals() ```
String concatenation vs. string substitution in Python
376,461
81
2008-12-17T23:39:39Z
376,924
10
2008-12-18T04:40:07Z
[ "python", "string", "string-concatenation" ]
In Python, the where and when of using string concatenation versus string substitution eludes me. As the string concatenation has seen large boosts in performance, is this (becoming more) a stylistic decision rather than a practical one? For a concrete example, how should one handle construction of flexible URIs: ```...
**Be wary of concatenating strings in a loop!** The cost of string concatenation is proportional to the length of the result. Looping leads you straight to the land of N-squared. Some languages will optimize concatenation to the most recently allocated string, but it's risky to count on the compiler to optimize your qu...
Test if executable exists in Python?
377,017
181
2008-12-18T05:55:36Z
377,028
233
2008-12-18T06:05:29Z
[ "python", "path" ]
In Python, is there a portable and simple way to test if an executable program exists? By simple I mean something like the `which` command which would be just perfect. I don't want to search PATH manually or something involving trying to execute it with `Popen` & al and see if it fails (that's what I'm doing now, but ...
Easiest way I can think of: ``` def which(program): import os def is_exe(fpath): return os.path.isfile(fpath) and os.access(fpath, os.X_OK) fpath, fname = os.path.split(program) if fpath: if is_exe(program): return program else: for path in os.environ["PATH"].sp...
Test if executable exists in Python?
377,017
181
2008-12-18T05:55:36Z
377,032
7
2008-12-18T06:08:00Z
[ "python", "path" ]
In Python, is there a portable and simple way to test if an executable program exists? By simple I mean something like the `which` command which would be just perfect. I don't want to search PATH manually or something involving trying to execute it with `Popen` & al and see if it fails (that's what I'm doing now, but ...
See [os.path](http://docs.python.org/library/os.path.html#module-os.path) module for some useful functions on pathnames. To check if an existing file is executable, use [os.access(path, mode)](http://docs.python.org/library/os.html#os.access), with the os.X\_OK mode. > os.X\_OK > > Value to include in the mode paramet...
Test if executable exists in Python?
377,017
181
2008-12-18T05:55:36Z
379,535
10
2008-12-18T22:25:15Z
[ "python", "path" ]
In Python, is there a portable and simple way to test if an executable program exists? By simple I mean something like the `which` command which would be just perfect. I don't want to search PATH manually or something involving trying to execute it with `Popen` & al and see if it fails (that's what I'm doing now, but ...
Just remember to specify the file extension on windows. Otherwise, you have to write a much complicated `is_exe` for windows using `PATHEXT` environment variable. You may just want to use [FindPath](http://www.raboof.com/projects/findpath/). OTOH, why are you even bothering to search for the executable? The operating ...
Test if executable exists in Python?
377,017
181
2008-12-18T05:55:36Z
11,069,822
10
2012-06-17T08:01:46Z
[ "python", "path" ]
In Python, is there a portable and simple way to test if an executable program exists? By simple I mean something like the `which` command which would be just perfect. I don't want to search PATH manually or something involving trying to execute it with `Popen` & al and see if it fails (that's what I'm doing now, but ...
## For \*nix platforms (Linux and OS X) This seems to be working for me: **Edited** to work on Linux, thanks to [Mestreion](http://stackoverflow.com/users/624066/mestrelion) ``` def cmd_exists(cmd): return subprocess.call("type " + cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) == 0 ``...
Test if executable exists in Python?
377,017
181
2008-12-18T05:55:36Z
12,611,523
180
2012-09-26T22:40:30Z
[ "python", "path" ]
In Python, is there a portable and simple way to test if an executable program exists? By simple I mean something like the `which` command which would be just perfect. I don't want to search PATH manually or something involving trying to execute it with `Popen` & al and see if it fails (that's what I'm doing now, but ...
I know this is an ancient question, but you can use `distutils.spawn.find_executable`. This has been [documented since python 2.4](http://docs.python.org/release/2.4/dist/module-distutils.spawn.html) and has existed since python 1.6. Also, Python 3.3 now offers [`shutil.which()`](http://docs.python.org/dev/library/shut...
Test if executable exists in Python?
377,017
181
2008-12-18T05:55:36Z
13,936,916
76
2012-12-18T16:05:19Z
[ "python", "path" ]
In Python, is there a portable and simple way to test if an executable program exists? By simple I mean something like the `which` command which would be just perfect. I don't want to search PATH manually or something involving trying to execute it with `Popen` & al and see if it fails (that's what I'm doing now, but ...
Python 3.3 now offers [shutil.which()](http://docs.python.org/dev/library/shutil.html#shutil.which).
Stackless python and multicores?
377,254
23
2008-12-18T08:51:22Z
377,366
38
2008-12-18T09:43:07Z
[ "python", "multithreading", "concurrency", "multicore", "python-stackless" ]
So, I'm toying around with [Stackless Python](http://www.stackless.com/) and a question popped up in my head, maybe this is "assumed" or "common" knowledge, but I couldn't find it actually written anywhere on the [stackless site](http://www.stackless.com/). Does [Stackless Python](http://www.stackless.com/) take advan...
Stackless python does *not* make use of any kind of multi-core environment it runs on. This is a common misconception about Stackless, as it allows the programmer to take advantage of thread-based programming. For many people these two are closely intertwined, but are, in fact two separate things. Internally Stackle...
How do I get my python program to sleep for 50 milliseconds?
377,454
231
2008-12-18T10:20:24Z
377,460
28
2008-12-18T10:23:03Z
[ "python", "timer", "sleep" ]
How do I get my python program to sleep for 50 milliseconds?
``` import time time.sleep (50.0 / 1000.0); ```
How do I get my python program to sleep for 50 milliseconds?
377,454
231
2008-12-18T10:20:24Z
377,463
327
2008-12-18T10:23:50Z
[ "python", "timer", "sleep" ]
How do I get my python program to sleep for 50 milliseconds?
``` Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52) [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from time import sleep >>> sleep(0.05) >>> ```
How do I get my python program to sleep for 50 milliseconds?
377,454
231
2008-12-18T10:20:24Z
377,546
36
2008-12-18T11:16:30Z
[ "python", "timer", "sleep" ]
How do I get my python program to sleep for 50 milliseconds?
Note that if you rely on sleep taking *exactly* 50ms, you won't get that. It will just be about it.
How to get a list of all users with a specific permission group in Django
378,303
36
2008-12-18T16:00:49Z
378,837
33
2008-12-18T19:03:38Z
[ "python", "django", "dictionary", "permissions" ]
I want to get a list of all Django auth user with a specific permission group, something like this: ``` user_dict = { 'queryset': User.objects.filter(permisson='blogger') } ``` I cannot find out how to do this. How are the permissions groups saved in the user model?
This would be the easiest ``` from django.contrib.auth import models group = models.Group.objects.get(name='blogger') users = group.user_set.all() ```
How to get a list of all users with a specific permission group in Django
378,303
36
2008-12-18T16:00:49Z
378,867
14
2008-12-18T19:11:08Z
[ "python", "django", "dictionary", "permissions" ]
I want to get a list of all Django auth user with a specific permission group, something like this: ``` user_dict = { 'queryset': User.objects.filter(permisson='blogger') } ``` I cannot find out how to do this. How are the permissions groups saved in the user model?
I think for group permissions, permissions are stored against groups, and then users have groups linked to them. So you can just resolve the user - groups relation. e.g. ``` 518$ python manage.py shell (InteractiveConsole) >>> from django.contrib.auth.models import User, Group >>> User.objects.filter(groups__name='m...
How to get a list of all users with a specific permission group in Django
378,303
36
2008-12-18T16:00:49Z
992,329
48
2009-06-14T07:02:33Z
[ "python", "django", "dictionary", "permissions" ]
I want to get a list of all Django auth user with a specific permission group, something like this: ``` user_dict = { 'queryset': User.objects.filter(permisson='blogger') } ``` I cannot find out how to do this. How are the permissions groups saved in the user model?
If you want to get list of users by permission, look at this variant: ``` from django.contrib.auth.models import User, Permission from django.db.models import Q perm = Permission.objects.get(codename='blogger') users = User.objects.filter(Q(groups__permissions=perm) | Q(user_permissions=perm)).distinct() ```
Problem sub-classing BaseException in Python
378,493
5
2008-12-18T17:00:56Z
378,514
8
2008-12-18T17:11:05Z
[ "python", "exception", "inheritance" ]
I wanted to create my own Python exception class, like this: ``` class MyException(BaseException): def __init__(self, errno, address): if errno == 10048: mess = str(address) + ' is already in use' else: mess = 'Unable to open ' + str(address) BaseException.__init__(m...
You have to call the method of the base class with the instance as the first argument: ``` BaseException.__init__(self, mess) ``` To quote from the [tutorial](http://docs.python.org/tutorial/classes.html#inheritance): > An overriding method in a derived class may in fact want to extend rather than simply replace the...
Getting python to work, Internal Server Error
378,811
6
2008-12-18T18:53:14Z
378,974
10
2008-12-18T19:42:48Z
[ "python" ]
I'm trying to get Python scripts, called from a web browser, to work. I keep getting the error: ``` 500 Internal Server Error ``` When I check my error logs I see the message ``` Premature end of script headers ``` The only documentation of this error online says that it can be the result of having improper line re...
This is the exact behavior you would get if your Python script does not have the executable permission set. Try: ``` chmod a+x foo.py ``` (where foo.py is your script name). See the [Apache tutorial](http://httpd.apache.org/docs/1.3/howto/cgi.html#filepermissions) for more information.
What does the []-esque decorator syntax in Python mean?
379,291
8
2008-12-18T21:14:04Z
379,409
11
2008-12-18T21:44:07Z
[ "python", "syntax", "decorator" ]
Here's a snippet of code from within TurboGears 1.0.6: ``` [dispatch.generic(MultiorderGenericFunction)] def run_with_transaction(func, *args, **kw): pass ``` I can't figure out how putting a list before a function definition can possibly affect it. In dispatch.generic's docstring, it mentions: > Note that when...
The decorator syntax is provided by PyProtocols. """ Finally, it's important to note that these "magic" decorators use a very sneaky hack: they abuse the sys.settrace() debugger hook to track whether assignments are taking place. Guido takes a very dim view of this, but the hook's existing functionality isn't going to...
What are these tags @ivar @param and @type in python docstring?
379,346
13
2008-12-18T21:26:39Z
379,415
12
2008-12-18T21:45:41Z
[ "python", "documentation", "javadoc" ]
The ampoule project uses some tags in docstring, like the javadoc ones. For example from [pool.py](http://bazaar.launchpad.net/~dialtone/ampoule/main/annotate/26?file_id=pool.py-20080501191749-jqawtxogk4i0quu3-12) line 86: ``` def start(self, ampChild=None): """ Starts the ProcessPool with a given child proto...
Markup for a documentation tool, probably [epydoc](http://epydoc.sourceforge.net/).
What are these tags @ivar @param and @type in python docstring?
379,346
13
2008-12-18T21:26:39Z
380,737
11
2008-12-19T11:34:22Z
[ "python", "documentation", "javadoc" ]
The ampoule project uses some tags in docstring, like the javadoc ones. For example from [pool.py](http://bazaar.launchpad.net/~dialtone/ampoule/main/annotate/26?file_id=pool.py-20080501191749-jqawtxogk4i0quu3-12) line 86: ``` def start(self, ampChild=None): """ Starts the ProcessPool with a given child proto...
Just for fun I'll note that the Python standard library is using Sphinx/reStructuredText, whose [info field lists](http://sphinx-doc.org/domains.html) are similar. ``` def start(self, ampChild=None): """Starts the ProcessPool with a given child protocol. :param ampChild: a :class:`ampoule.child.AMPChild` subc...
Parse String to Float or Int
379,906
1,130
2008-12-19T01:52:26Z
379,909
8
2008-12-19T01:54:11Z
[ "python", "string", "parsing", "floating-point", "integer" ]
In Python, how can I parse a numeric string like `"545.2222"` to its corresponding float value, `542.2222`? Or parse the string `"31"` to an integer, `31`? I just want to know how to parse a float string to a float, and (separately) an int string to an int.
`float("545.2222")` and `int(float("545.2222"))`
Parse String to Float or Int
379,906
1,130
2008-12-19T01:52:26Z
379,910
1,372
2008-12-19T01:54:51Z
[ "python", "string", "parsing", "floating-point", "integer" ]
In Python, how can I parse a numeric string like `"545.2222"` to its corresponding float value, `542.2222`? Or parse the string `"31"` to an integer, `31`? I just want to know how to parse a float string to a float, and (separately) an int string to an int.
``` >>> a = "545.2222" >>> float(a) 545.22220000000004 >>> int(float(a)) 545 ```
Parse String to Float or Int
379,906
1,130
2008-12-19T01:52:26Z
379,932
13
2008-12-19T02:09:03Z
[ "python", "string", "parsing", "floating-point", "integer" ]
In Python, how can I parse a numeric string like `"545.2222"` to its corresponding float value, `542.2222`? Or parse the string `"31"` to an integer, `31`? I just want to know how to parse a float string to a float, and (separately) an int string to an int.
Users *codelogic* and *harley* are correct, but keep in mind if you know the string is an integer (for example, 545) you can call int("545") without first casting to float. If your strings are in a list, you could use the map function as well. ``` >>> x = ["545.0", "545.6", "999.2"] >>> map(float, x) [545.0, 545.6000...
Parse String to Float or Int
379,906
1,130
2008-12-19T01:52:26Z
379,966
340
2008-12-19T02:31:23Z
[ "python", "string", "parsing", "floating-point", "integer" ]
In Python, how can I parse a numeric string like `"545.2222"` to its corresponding float value, `542.2222`? Or parse the string `"31"` to an integer, `31`? I just want to know how to parse a float string to a float, and (separately) an int string to an int.
``` def num(s): try: return int(s) except ValueError: return float(s) ```
Parse String to Float or Int
379,906
1,130
2008-12-19T01:52:26Z
379,968
67
2008-12-19T02:32:06Z
[ "python", "string", "parsing", "floating-point", "integer" ]
In Python, how can I parse a numeric string like `"545.2222"` to its corresponding float value, `542.2222`? Or parse the string `"31"` to an integer, `31`? I just want to know how to parse a float string to a float, and (separately) an int string to an int.
``` float(x) if '.' in x else int(x) ```
Parse String to Float or Int
379,906
1,130
2008-12-19T01:52:26Z
7,588,720
11
2011-09-28T19:45:18Z
[ "python", "string", "parsing", "floating-point", "integer" ]
In Python, how can I parse a numeric string like `"545.2222"` to its corresponding float value, `542.2222`? Or parse the string `"31"` to an integer, `31`? I just want to know how to parse a float string to a float, and (separately) an int string to an int.
The question seems a little bit old. But let me suggest a function, parseStr, which makes something similar, that is, returns integer or float and if a given ASCII string cannot be converted to none of them it returns it untouched. The code of course might be adjusted to do only what you want: ``` >>> import string...
Parse String to Float or Int
379,906
1,130
2008-12-19T01:52:26Z
9,510,585
75
2012-03-01T04:23:15Z
[ "python", "string", "parsing", "floating-point", "integer" ]
In Python, how can I parse a numeric string like `"545.2222"` to its corresponding float value, `542.2222`? Or parse the string `"31"` to an integer, `31`? I just want to know how to parse a float string to a float, and (separately) an int string to an int.
This is another method which deserves to be mentioned here, [ast.literal\_eval](http://docs.python.org/library/ast.html#ast.literal_eval): > This can be used for safely evaluating strings containing Python expressions from untrusted sources without the need to parse the values oneself. That is, a safe 'eval' ``` >>>...
Parse String to Float or Int
379,906
1,130
2008-12-19T01:52:26Z
16,028,076
7
2013-04-16T03:03:11Z
[ "python", "string", "parsing", "floating-point", "integer" ]
In Python, how can I parse a numeric string like `"545.2222"` to its corresponding float value, `542.2222`? Or parse the string `"31"` to an integer, `31`? I just want to know how to parse a float string to a float, and (separately) an int string to an int.
The [YAML](http://en.wikipedia.org/wiki/YAML) parser can help you figure out what datatype your string is. Use `yaml.load()`, and then you can use `type(result)` to test for type: ``` >>> import yaml >>> a = "545.2222" >>> result = yaml.load(a) >>> result 545.22220000000004 >>> type(result) <type 'float'> >>> b = "3...