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.6 msec per loop ```
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 uncomment line **(B)**, I get an *UnboundLocalError: 'c' not assigned* at line **(A)**. The values of *a* and *b* are printed correctly. This has me completely baffled for two reasons: 1. Why is there a runtime error thrown at line **(A)** because of a later statement on line **(B)**? 2. Why are variables *a* and *b* printed as expected, while *c* raises an error? The only explanation I can come up with is that a **local** variable *c* is created by the assignment `c+=1`, which takes precedent over the "global" variable *c* even before the local variable is created. Of course, it doesn't make sense for a variable to "steal" scope before it exists. Could someone please explain this behavior?
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 has been assigned to it. If you want the variable c to refer to the global c put ``` global c ``` as the first line of the function. As of python 3, there is now ``` nonlocal c ``` that you can use to refer to the nearest enclosing (not necessarily global) scope.
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 uncomment line **(B)**, I get an *UnboundLocalError: 'c' not assigned* at line **(A)**. The values of *a* and *b* are printed correctly. This has me completely baffled for two reasons: 1. Why is there a runtime error thrown at line **(A)** because of a later statement on line **(B)**? 2. Why are variables *a* and *b* printed as expected, while *c* raises an error? The only explanation I can come up with is that a **local** variable *c* is created by the assignment `c+=1`, which takes precedent over the "global" variable *c* even before the local variable is created. Of course, it doesn't make sense for a variable to "steal" scope before it exists. Could someone please explain this behavior?
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 print(a) print(b) print(c) # (A) c+=1 # (B) ``` Also, the reason you are getting this error is because you can also declare a new variable inside that function with the same name as a 'global' one, and it would be completely separate. The interpreter thinks you are trying to make a new variable in this scope called 'c' and modify it all in one operation, which isn't allowed in python because this new 'c' wasn't initialized.
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 uncomment line **(B)**, I get an *UnboundLocalError: 'c' not assigned* at line **(A)**. The values of *a* and *b* are printed correctly. This has me completely baffled for two reasons: 1. Why is there a runtime error thrown at line **(A)** because of a later statement on line **(B)**? 2. Why are variables *a* and *b* printed as expected, while *c* raises an error? The only explanation I can come up with is that a **local** variable *c* is created by the assignment `c+=1`, which takes precedent over the "global" variable *c* even before the local variable is created. Of course, it doesn't make sense for a variable to "steal" scope before it exists. Could someone please explain this behavior?
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 name in the dictionary, so Python looks up the list and finds them in the clobal dictionary. Now we get to `c+=1`, which is, of course, equivalent to `c=c+1`. When Python scans that line, it says "ahah, there's a variable named c, I'll put it into my local scope dictionary." Then when it goes looking for a value for c for the c on the right hand side of the assignment, it finds its *local variable named c*, which has no value yet, and so throws the error. The statement `global c` mentioned above simply tells the parser that it uses the c from the global scope and so doesn't need a new one. The reason it says there's an issue on the line it does is because it is effectively looking for the names before it tries to generate code, and so in some sense doesn't think it's really doing that line yet. I'd argue that is a useability bug, but it's generally a good practice to just learn not to take a compiler's messages *too* seriously. If it's any comfort, I spent probably a day digging and experimenting with this same issue before I found something Guido had written about the dictionaries that Explained Everything. ### Update, see comments: It doesn't scan the code twice, but it does scan the code in two phases, lexing and parsing. Consider how the parse of this cline of code works. The lexer reads the source text and breaks it into lexemes, the "smallest components" of the grammar. So when it hits the line ``` c+=1 ``` it breaks it up into something like ``` SYMBOL(c) OPERATOR(+=) DIGIT(1) ``` The parser eventually wants to make this into a parse tree and execute it, but since it's an assignment, before it does, it looks for the name c in the local dictionary, doesn't see it, and inserts it in the dictionary, marking it as uninitialized. In a fullly compiled language, it would just go into the symbol table and wait for the parse, but since it WON'T have the luxury of a second pass, the lexer does a little extra work to make life easier later on. Only, then it sees the OPERATOR, sees that the rules say "if you have an operator += the left hand side must have been initialized" and says "whoops!" The point here is that it *hasn't really started the parse of the line yet*. This is all happening sort of preparatory to the actual parse, so the line counter hasn't advanced to the next line. Thus when it signals the error, it still thinks its on the previous line. As I say, you could argue it's a usability bug, but its actually a fairly common thing. Some compilers are more honest about it and say "error on or around line XXX", but this one doesn't.
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 uncomment line **(B)**, I get an *UnboundLocalError: 'c' not assigned* at line **(A)**. The values of *a* and *b* are printed correctly. This has me completely baffled for two reasons: 1. Why is there a runtime error thrown at line **(A)** because of a later statement on line **(B)**? 2. Why are variables *a* and *b* printed as expected, while *c* raises an error? The only explanation I can come up with is that a **local** variable *c* is created by the assignment `c+=1`, which takes precedent over the "global" variable *c* even before the local variable is created. Of course, it doesn't make sense for a variable to "steal" scope before it exists. Could someone please explain this behavior?
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) 8 PRINT_ITEM 9 PRINT_NEWLINE 4 10 LOAD_CONST 1 (1) 13 STORE_FAST 0 (a) 16 LOAD_CONST 0 (None) 19 RETURN_VALUE ``` As you can see, the bytecode for accessing a is `LOAD_FAST`, and for b, `LOAD_GLOBAL`. This is because the compiler has identified that a is assigned to within the function, and classified it as a local variable. The access mechanism for locals is fundamentally different for globals - they are statically assigned an offset in the frame's variables table, meaning lookup is a quick index, rather than the more expensive dict lookup as for globals. Because of this, Python is reading the `print a` line as "get the value of local variable 'a' held in slot 0, and print it", and when it detects that this variable is still uninitialised, raises an exception.
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 towards game development (cursors, sprites, joystick/gamepad support)** *Pyglet is more general purpose (though it has a Sprite class)* I found also this discussion on pyglet-users mailing list: [from pygame+pyopengl to pyglet](http://www.mail-archive.com/[email protected]/msg00482.html) Disclaimer: I did not use either yet, only tried some tutorials ;-)
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 straightforward and readable example going very quickly, and it uses decorators to good effect for event handling. It also didn't force a particular program structure, which made it easy for me to mix in the physics modelling of Pymunk (<http://code.google.com/p/pymunk/>). While it is based on OpenGL and you can use those features for special effects, I was able to do just fine without any knowledge of them. It also works well with py2exe and py2app, which is important because a lot of people do not have a Python interpreter installed. On the downside, there is less information about it on the web because it is newer, as well as fewer sample games to look at. Also, it changed quite a bit from previous versions, so some of the tutorials which are there are now out of date (there is the "new style event loop" and the Sprite class as major additions.) I would recommend downloading the examples (there is a nice Asteroids clone called Astraea included) and seeing if you like the style.
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 have to generate graphics on-the-fly, and then save them, either as a variable or as a file, then pyglet becomes considerably more complicated because you start having to muck around with the low-level OpenGL functions. In those scenarios, pygame is much more user-friendly, with it's software rendering and Surface class. Or you could use Python Imaging Library and interface it with pyglet. Obviously, for 3D games, you're going to have to muck around with OpenGL functions anyway, in which case I recommend pyglet over pygame + PyOpenGL.
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 web site but maybe I'm just looking wrong...
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 can simply adapt from. Think also about installing this development plugin: <http://trac-hacks.org/wiki/TracDeveloperPlugin> It makes it much easier to debug your plugin with it
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 not a well-formed number") ``` I could also call `isinstance(mydata, (float, int, long) )` but the list of "all these could be numbers" seems a bit inelegant to me. What's the most pythonic way of going about it? Is there another option I overlooked?
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 calculations will end upp calling add, mul etc for the types, and if they break, they will throw the correct exception anyway. By enforcing your own checks, you may invalidate otherwise working input. Thus, the best option is to leave the type checking up to Python. If the calculation fails, Python's type checking will give an exception, so if you do it yourself, you just duplicate code which means more work on your behalf.
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.test2=21 def __getattribute__(self,name): if name=='test': return 0. else: return self.__dict__[name] >>> print D().test 0.0 >>> print D().test2 ... RuntimeError: maximum recursion depth exceeded in cmp ```
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. else: return object.__getattribute__(self, name) ``` This works because `object` (in this example) is the base class. By calling the base version of `__getattribute__` you avoid the recursive hell you were in before. Ipython output with code in foo.py: ``` In [1]: from foo import * In [2]: d = D() In [3]: d.test Out[3]: 0.0 In [4]: d.test2 Out[4]: 21 ``` **Update:** There's something in the section titled [*More attribute access for new-style classes*](http://docs.python.org/reference/datamodel.html#more-attribute-access-for-new-style-classes) in the current documentation, where they recommend doing exactly this to avoid the infinite recursion.
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.test2=21 def __getattribute__(self,name): if name=='test': return 0. else: return self.__dict__[name] >>> print D().test 0.0 >>> print D().test2 ... RuntimeError: maximum recursion depth exceeded in cmp ```
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 self.test2 = 21 @property def test(self): return 0 ``` Edit: Note that an instance of `D` would have different values of `test` in each case. In the first case `d.test` would be 20, in the second it would be 0. I'll leave it to you to work out why. Edit2: Greg pointed out that example 2 will fail because the property is read only and the `__init__` method tried to set it to 20. A more complete example for that would be: ``` class D(object): def __init__(self): self.test = 20 self.test2 = 21 _test = 0 def get_test(self): return self._test def set_test(self, value): self._test = value test = property(get_test, set_test) ``` Obviously, as a class this is almost entirely useless, but it gives you an idea to move on from.
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.test2=21 def __getattribute__(self,name): if name=='test': return 0. else: return self.__dict__[name] >>> print D().test 0.0 >>> print D().test2 ... RuntimeError: maximum recursion depth exceeded in cmp ```
[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__(self, name)`. Meaning: ``` def __getattribute__(self,name): ... return self.__dict__[name] ``` You're calling for an attribute called `__dict__`. Because it's an attribute, `__getattribute__` gets called in search for `__dict__` which calls `__getattribute__` which calls ... yada yada yada ``` return object.__getattribute__(self, name) ``` Using the base classes `__getattribute__` helps finding the real attribute.
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.test2=21 def __getattribute__(self,name): if name=='test': return 0. else: return self.__dict__[name] >>> print D().test 0.0 >>> print D().test2 ... RuntimeError: maximum recursion depth exceeded in cmp ```
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 attribute name. This method should return the (computed) attribute value or raise an AttributeError exception. > Note that if the attribute is found through the normal mechanism, `__getattr__()` is not called. (This is an intentional asymmetry between `__getattr__()` and `__setattr__()`.) This is done both for efficiency reasons and because otherwise `__setattr__()` would have no way to access other attributes of the instance. Note that at least for instance variables, you can fake total control by not inserting any values in the instance attribute dictionary (but instead inserting them in another object). See the `__getattribute__()` method below for a way to actually get total control in new-style classes. Note: for this to work, the instance should *not* have a `test` attribute, so the line `self.test=20` should be removed.
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 information.
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](http://docs.python.org/reference/lexical_analysis.html#implicit-line-joining): Mr. Gamble's answer is correct for indentation.
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 do [exist](http://www.python.org/dev/peps/pep-3119/) (<http://docs.python.org/library/abc.html>). And allow you to specify methods that must be implemented in subclasses. I don't much like the syntax, but the feature is there. Most of the time it's probably better to use duck typing from the 'using' client side.
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 collections module), numbers > (in the numbers module), and streams > (in the io module). You can create > your own ABC with the abc module. There is also the [Zope Interface](http://pypi.python.org/pypi/zope.interface) module, which is used by projects outside of zope, like twisted. I'm not really familiar with it, but there's a wiki page [here](http://wiki.zope.org/Interfaces/FrontPage) that might help. In general, you don't need the concept of abstract classes, or interfaces in python (edited - see S.Lott's answer for details).
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 doesn't need) a formal Interface contract, the Java-style distinction between abstraction and interface doesn't exist. If someone goes through the effort to define a formal interface, it will also be an abstract class. The only differences would be in the stated intent in the docstring. And the difference between abstract and interface is a hairsplitting thing when you have duck typing. Java uses interfaces because it doesn't have multiple inheritance. Because Python has multiple inheritance, you may also see something like this ``` class SomeAbstraction( object ): pass # lots of stuff - but missing something class Mixin1( object ): def something( self ): pass # one implementation class Mixin2( object ): def something( self ): pass # another class Concrete1( SomeAbstraction, Mixin1 ): pass class Concrete2( SomeAbstraction, Mixin2 ): pass ``` This uses a kind of abstract superclass with mixins to create concrete subclasses that are disjoint.
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 class variables in addition to none or more methods, or to exploit the single-inheritance model to limit the range of classes that could use a set of methods. Languages that support the multiple-inheritance model tend to use only classes or abstract base classes and not interfaces. Since Python supports multiple inheritance, it does not use interfaces and you would want to use base classes or abstract base classes. <http://docs.python.org/library/abc.html>
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 practical difference in Python, but on the planning level for a large project, it could be more common to talk about interfaces, since there's no code. Especially if you're working with Java programmers who are accustomed to the term.
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.Set): pass ``` If we try to use it, we get an `TypeError` because the class we created does not support the expected behavior of sets: ``` >>> MySet() Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: Can't instantiate abstract class MySet with abstract methods __contains__, __iter__, __len__ ``` So we are required to implement at *least* `__contains__`, `__iter__`, and `__len__`. Let's use this implementation example from the [documentation](https://docs.python.org/2/library/collections.html#collections-abstract-base-classes): ``` class ListBasedSet(collections.Set): ''' Alternate set implementation favoring space over speed and not requiring the set elements to be hashable. ''' def __init__(self, iterable): self.elements = lst = [] for value in iterable: if value not in lst: lst.append(value) def __iter__(self): return iter(self.elements) def __contains__(self, value): return value in self.elements def __len__(self): return len(self.elements) s1 = ListBasedSet('abcdef') s2 = ListBasedSet('defghi') overlap = s1 & s2 ``` ## Implementation: Creating an Abstract Base Class We can create our own Abstract Base Class by setting the metaclass to `abc.ABCMeta` and using the `abc.abstractmethod` decorator on relevant methods. The metaclass will be add the decorated functions to the `__abstractmethods__` attribute, preventing instantiation until those are defined. ``` import abc ``` For example, "effable" is defined as something that can be expressed in words. Say we wanted to define an abstract base class that is effable, in Python 2: ``` class Effable(object): __metaclass__ = abc.ABCMeta @abc.abstractmethod def __str__(self): raise NotImplementedError('users must define __str__ to use this base class') ``` Or in Python 3, with the slight change in metaclass declaration: ``` class Effable(object, metaclass=abc.ABCMeta): @abc.abstractmethod def __str__(self): raise NotImplementedError('users must define __str__ to use this base class') ``` Now if we try to create an effable object without implementing the interface: ``` class MyEffable(Effable): pass ``` and attempt to instantiate it: ``` >>> MyEffable() Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: Can't instantiate abstract class MyEffable with abstract methods __str__ ``` We are told that we haven't finished the job. Now if we comply by providing the expected interface: ``` class MyEffable(Effable): def __str__(self): return 'expressable!' ``` we are then able to use the concrete version of the class derived from the abstract one: ``` >>> me = MyEffable() >>> print(me) expressable! ``` There are other things we could do with this, like register virtual subclasses that already implement these interfaces, but I think that is beyond the scope of this question. The other methods demonstrated here would have to adapt this method using the `abc` module to do so, however. ## Conclusion We have demonstrated that the creation of an Abstract Base Class defines an interface in Python, thus they are one and the same.
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 in some way match a character such as that? Thanks for your help
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 update the timeout on my ServerProxy object? I can't see a clear way to get access to the socket to update it.
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.setdefaulttimeout(None) #sets the default back ```
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 update the timeout on my ServerProxy object? I can't see a clear way to get access to the socket to update it.
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 set_timeout(self, timeout): self._conn.timeout = timeout class TimeoutTransport(xmlrpclib.Transport): def __init__(self, timeout=10, *l, **kw): xmlrpclib.Transport.__init__(self, *l, **kw) self.timeout = timeout def make_connection(self, host): conn = TimeoutHTTP(host) conn.set_timeout(self.timeout) return conn class TimeoutServerProxy(xmlrpclib.ServerProxy): def __init__(self, uri, timeout=10, *l, **kw): kw['transport'] = TimeoutTransport( timeout=timeout, use_datetime=kw.get('use_datetime', 0)) xmlrpclib.ServerProxy.__init__(self, uri, *l, **kw) if __name__ == "__main__": s = TimeoutServerProxy('http://127.0.0.1:9090', timeout=2) s.dummy() ```
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 resultset numrows = int(cursor.rowcount) # get and display one row at a time. for x in range(0,numrows): row = cursor.fetchone() print row[0], "-->", row[1] ``` From [here](http://it.toolbox.com/blogs/lim/connecting-to-mysql-from-python-4529).
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", passwd = "testpass", db = "test") cursor = conn.cursor () cursor.execute ("SELECT VERSION()") row = cursor.fetchone () print "server version:", row[0] cursor.close () conn.close () ```
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\_install. For Windows user, you can get an [exe of MySQLdb](http://sourceforge.net/project/showfiles.php?group_id=22307). For Linux, this is a casual package (python-mysqldb). (You can use `sudo apt-get install python-mysqldb` (for debian based distros), `yum install mysql-python` (for rpm-based), or `dnf install python-mysql` (for modern fedora distro) in command line to download.) For Mac, you can [install MySQLdb using Macport](http://stackoverflow.com/questions/1448429/how-to-install-mysqldb-python-data-access-library-to-mysql-on-mac-os-x#1448476). **2 - Usage** After installing, reboot. This is not mandatory, but will prevent me from answering 3 or 4 other questions in this post if something goes wrong. So please reboot. Then it is just like using another package : ``` #!/usr/bin/python import MySQLdb db = MySQLdb.connect(host="localhost", # your host, usually localhost user="john", # your username passwd="megajonhy", # your password db="jonhydb") # name of the data base # you must create a Cursor object. It will let # you execute all the queries you need cur = db.cursor() # Use all the SQL you like cur.execute("SELECT * FROM YOUR_TABLE_NAME") # print all the first cell of all the rows for row in cur.fetchall(): print row[0] db.close() ``` Of course, there are thousand of possibilities and options; this is a very basic example. You will have to look at the documentation. [A good starting point](http://www.mikusa.com/python-mysql-docs/). **3 - More advanced usage** Once you know how it works, you may want to use an [ORM](https://en.wikipedia.org/wiki/Object-Relational_Mapping) to avoid writting SQL manually and manipulate your tables as they were Python objects. The most famous ORM in the Python community is [SQLAlchemy](http://www.sqlalchemy.org/). I strongly advise you to use it: your life is going to be much easier. I recently discovered another jewel in the Python world: [peewee](http://peewee.readthedocs.org/en/latest/index.html). It's a very lite ORM, really easy and fast to setup then use. It makes my day for small projects or stand alone apps, where using big tools like SQLAlchemy or Django is overkill : ``` import peewee from peewee import * db = MySQLDatabase('jonhydb', user='john',passwd='megajonhy') class Book(peewee.Model): author = peewee.CharField() title = peewee.TextField() class Meta: database = db Book.create_table() book = Book(author="me", title='Peewee is cool') book.save() for book in Book.filter(author="me"): print book.title Peewee is cool ``` This example works out of the box. Nothing other than having peewee (`pip install peewee` :-)) is required. No complicated setup. It's really cool.
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 database and streamed out of the database, instead of requiring everything to be buffered in the client. > * oursql can both insert rows lazily and fetch rows lazily. > * oursql has unicode support on by default. > * oursql supports python 2.4 through 2.7 without any deprecation warnings on 2.6+ (see PEP 218) and without completely failing on 2.7 (see PEP 328). > * oursql runs natively on python 3.x. ### So how to connect to mysql with oursql? Very similar to mysqldb: ``` import oursql db_connection = oursql.connect(host='127.0.0.1',user='foo',passwd='foobar',db='db_name') cur=db_connection.cursor() cur.execute("SELECT * FROM `tbl_name`") for row in cur.fetchall(): print row[0] ``` The [tutorial in the documentation](http://packages.python.org/oursql/tutorial.html) is pretty decent. And of course for ORM SQLAlchemy is a good choice, as already mentioned in the other answers.
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, confirm license agreement and go. There is no need for Xcode, MacPorts, compiling, restarting … Then you connect like: ``` import mysql.connector cnx = mysql.connector.connect(user='scott', password='tiger', host='127.0.0.1', database='employees') try: cursor = cnx.cursor() cursor.execute(""" select 3 from your_table """) result = cursor.fetchall() print result finally: cnx.close() ```
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 systems consistent and easy. `pymysql` is a drop in replacement for MySQLDb and IMHO there is no reason to ever use MySQLDb for anything... EVER! - *`PTSD from installing MySQLDb on Mac OSX and *Nix systems`* but that's just me. **Installation** `pip install pymysql` > That's it... you are ready to play. **Example usage from pymysql Github repo** ``` import pymysql.cursors import pymysql # Connect to the database connection = pymysql.connect(host='localhost', user='user', password='passwd', db='db', charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor) try: with connection.cursor() as cursor: # Create a new record sql = "INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)" cursor.execute(sql, ('[email protected]', 'very-secret')) # connection is not autocommit by default. So you must commit to save # your changes. connection.commit() with connection.cursor() as cursor: # Read a single record sql = "SELECT `id`, `password` FROM `users` WHERE `email`=%s" cursor.execute(sql, ('[email protected]',)) result = cursor.fetchone() print(result) finally: connection.close() ```
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 case if you've installed universal MacPython, which you'd probably want to do on Tiger). But Peter's answer with the Carbon way of doing this will probably be quite a bit faster, since importing anything from AppKit in Python takes a while, or more accurately, importing something from AppKit for the first time in a Python process takes a while. If you need this inside a PyObjC app, what I describe will work great and fast, since you only experience the lag of importing AppKit once. If you need this to work as a command-line tool, you'll notice the performance hit. If that's relevant to you, you're probably better off building a 10 line Foundation command line tool in Xcode using Peter's code as a starting point.
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 see the `\d` verbatim. In this case you are lucky that `\d` is not interpreted by the Python escaping, but something like `\b` (which has completely different meanings in Python escaping and in regular expressions) would be. See the [`re` module documentation](http://python.org/doc/2.5/lib/module-re.html) for more information.
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 other solutions, if there is a string of 37 contiguous hexadecimals the pattern would match the first 32 and call it a match, or if there is a string of 64 hexadecimals it would split it in half and match each half as an independent match. Excluding these is accomplished via the lookahead and lookbehind assertions, which are non-capturing and will not affect the contents of the match. Note also the (?i) flag which will makes the pattern case-insensitive which saves a little bit of typing, and that wrapping the entire pattern in parentheses is superfluous.
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: ``` 0 2 * * 7 /usr/bin/run-backup # run the backups at 0200 on Every Sunday 0 9-17/2 * * 1-5 /usr/bin/purge-temps # run the purge temps command, every 2 hours between 9am and 5pm on Mondays to Fridays. ``` The cron time expression syntax is less important, but I would like to have something with this sort of flexibility. If there isn't something that does this for me out-the-box, any suggestions for the building blocks to make something like this would be gratefully received. **Edit** I'm not interested in launching processes, just "jobs" also written in Python - python functions. By necessity I think this would be a different thread, but not in a different process. To this end, I'm looking for the expressivity of the cron time expression, but in Python. Cron *has* been around for years, but I'm trying to be as portable as possible. I cannot rely on its presence.
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: ``` 0 2 * * 7 /usr/bin/run-backup # run the backups at 0200 on Every Sunday 0 9-17/2 * * 1-5 /usr/bin/purge-temps # run the purge temps command, every 2 hours between 9am and 5pm on Mondays to Fridays. ``` The cron time expression syntax is less important, but I would like to have something with this sort of flexibility. If there isn't something that does this for me out-the-box, any suggestions for the building blocks to make something like this would be gratefully received. **Edit** I'm not interested in launching processes, just "jobs" also written in Python - python functions. By necessity I think this would be a different thread, but not in a different process. To this end, I'm looking for the expressivity of the cron time expression, but in Python. Cron *has* been around for years, but I'm trying to be as portable as possible. I cannot rely on its presence.
[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: ``` 0 2 * * 7 /usr/bin/run-backup # run the backups at 0200 on Every Sunday 0 9-17/2 * * 1-5 /usr/bin/purge-temps # run the purge temps command, every 2 hours between 9am and 5pm on Mondays to Fridays. ``` The cron time expression syntax is less important, but I would like to have something with this sort of flexibility. If there isn't something that does this for me out-the-box, any suggestions for the building blocks to make something like this would be gratefully received. **Edit** I'm not interested in launching processes, just "jobs" also written in Python - python functions. By necessity I think this would be a different thread, but not in a different process. To this end, I'm looking for the expressivity of the cron time expression, but in Python. Cron *has* been around for years, but I'm trying to be as portable as possible. I cannot rely on its presence.
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__(self, item): return True allMatch = AllMatch() def conv_to_set(obj): # Allow single integer to be provided if isinstance(obj, (int,long)): return set([obj]) # Single item if not isinstance(obj, set): obj = set(obj) return obj # The actual Event class class Event(object): def __init__(self, action, min=allMatch, hour=allMatch, day=allMatch, month=allMatch, dow=allMatch, args=(), kwargs={}): self.mins = conv_to_set(min) self.hours= conv_to_set(hour) self.days = conv_to_set(day) self.months = conv_to_set(month) self.dow = conv_to_set(dow) self.action = action self.args = args self.kwargs = kwargs def matchtime(self, t): """Return True if this event should trigger at the specified datetime""" return ((t.minute in self.mins) and (t.hour in self.hours) and (t.day in self.days) and (t.month in self.months) and (t.weekday() in self.dow)) def check(self, t): if self.matchtime(t): self.action(*self.args, **self.kwargs) ``` (Note: Not thoroughly tested) Then your CronTab can be specified in normal python syntax as: ``` c = CronTab( Event(perform_backup, 0, 2, dow=6 ), Event(purge_temps, 0, range(9,18,2), dow=range(0,5)) ) ``` This way you get the full power of Python's argument mechanics (mixing positional and keyword args, and can use symbolic names for names of weeks and months) The CronTab class would be defined as simply sleeping in minute increments, and calling check() on each event. (There are probably some subtleties with daylight savings time / timezones to be wary of though). Here's a quick implementation: ``` class CronTab(object): def __init__(self, *events): self.events = events def run(self): t=datetime(*datetime.now().timetuple()[:5]) while 1: for e in self.events: e.check(t) t += timedelta(minutes=1) while datetime.now() < t: time.sleep((t - datetime.now()).seconds) ``` A few things to note: Python's weekdays / months are zero indexed (unlike cron), and that range excludes the last element, hence syntax like "1-5" becomes range(0,5) - ie [0,1,2,3,4]. If you prefer cron syntax, parsing it shouldn't be too difficult however.
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: ``` 0 2 * * 7 /usr/bin/run-backup # run the backups at 0200 on Every Sunday 0 9-17/2 * * 1-5 /usr/bin/purge-temps # run the purge temps command, every 2 hours between 9am and 5pm on Mondays to Fridays. ``` The cron time expression syntax is less important, but I would like to have something with this sort of flexibility. If there isn't something that does this for me out-the-box, any suggestions for the building blocks to make something like this would be gratefully received. **Edit** I'm not interested in launching processes, just "jobs" also written in Python - python functions. By necessity I think this would be a different thread, but not in a different process. To this end, I'm looking for the expressivity of the cron time expression, but in Python. Cron *has* been around for years, but I'm trying to be as portable as possible. I cannot rely on its presence.
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, long)): return set([obj]) # Single item if not isinstance(obj, set): obj = set(obj) return obj class AllMatch(set): """Universal set - match everything""" def __contains__(self, item): return True allMatch = AllMatch() class Event(object): """The Actual Event Class""" def __init__(self, action, minute=allMatch, hour=allMatch, day=allMatch, month=allMatch, daysofweek=allMatch, args=(), kwargs={}): self.mins = conv_to_set(minute) self.hours = conv_to_set(hour) self.days = conv_to_set(day) self.months = conv_to_set(month) self.daysofweek = conv_to_set(daysofweek) self.action = action self.args = args self.kwargs = kwargs def matchtime(self, t1): """Return True if this event should trigger at the specified datetime""" return ((t1.minute in self.mins) and (t1.hour in self.hours) and (t1.day in self.days) and (t1.month in self.months) and (t1.weekday() in self.daysofweek)) def check(self, t): """Check and run action if needed""" if self.matchtime(t): self.action(*self.args, **self.kwargs) class CronTab(object): """The crontab implementation""" def __init__(self, *events): self.events = events def _check(self): """Check all events in separate greenlets""" t1 = datetime(*datetime.now().timetuple()[:5]) for event in self.events: gevent.spawn(event.check, t1) t1 += timedelta(minutes=1) s1 = (t1 - datetime.now()).seconds + 1 print "Checking again in %s seconds" % s1 job = gevent.spawn_later(s1, self._check) def run(self): """Run the cron forever""" self._check() while True: gevent.sleep(60) import os def test_task(): """Just an example that sends a bell and asd to all terminals""" os.system('echo asd | wall') cron = CronTab( Event(test_task, 22, 1 ), Event(test_task, 0, range(9,18,2), daysofweek=range(0,5)), ) cron.run() ```
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: ``` 0 2 * * 7 /usr/bin/run-backup # run the backups at 0200 on Every Sunday 0 9-17/2 * * 1-5 /usr/bin/purge-temps # run the purge temps command, every 2 hours between 9am and 5pm on Mondays to Fridays. ``` The cron time expression syntax is less important, but I would like to have something with this sort of flexibility. If there isn't something that does this for me out-the-box, any suggestions for the building blocks to make something like this would be gratefully received. **Edit** I'm not interested in launching processes, just "jobs" also written in Python - python functions. By necessity I think this would be a different thread, but not in a different process. To this end, I'm looking for the expressivity of the cron time expression, but in Python. Cron *has* been around for years, but I'm trying to be as portable as possible. I cannot rely on its presence.
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: ``` 0 2 * * 7 /usr/bin/run-backup # run the backups at 0200 on Every Sunday 0 9-17/2 * * 1-5 /usr/bin/purge-temps # run the purge temps command, every 2 hours between 9am and 5pm on Mondays to Fridays. ``` The cron time expression syntax is less important, but I would like to have something with this sort of flexibility. If there isn't something that does this for me out-the-box, any suggestions for the building blocks to make something like this would be gratefully received. **Edit** I'm not interested in launching processes, just "jobs" also written in Python - python functions. By necessity I think this would be a different thread, but not in a different process. To this end, I'm looking for the expressivity of the cron time expression, but in Python. Cron *has* been around for years, but I'm trying to be as portable as possible. I cannot rely on its presence.
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: ``` 0 2 * * 7 /usr/bin/run-backup # run the backups at 0200 on Every Sunday 0 9-17/2 * * 1-5 /usr/bin/purge-temps # run the purge temps command, every 2 hours between 9am and 5pm on Mondays to Fridays. ``` The cron time expression syntax is less important, but I would like to have something with this sort of flexibility. If there isn't something that does this for me out-the-box, any suggestions for the building blocks to make something like this would be gratefully received. **Edit** I'm not interested in launching processes, just "jobs" also written in Python - python functions. By necessity I think this would be a different thread, but not in a different process. To this end, I'm looking for the expressivity of the cron time expression, but in Python. Cron *has* been around for years, but I'm trying to be as portable as possible. I cannot rely on its presence.
*"... 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: ``` 0 2 * * 7 /usr/bin/run-backup # run the backups at 0200 on Every Sunday 0 9-17/2 * * 1-5 /usr/bin/purge-temps # run the purge temps command, every 2 hours between 9am and 5pm on Mondays to Fridays. ``` The cron time expression syntax is less important, but I would like to have something with this sort of flexibility. If there isn't something that does this for me out-the-box, any suggestions for the building blocks to make something like this would be gratefully received. **Edit** I'm not interested in launching processes, just "jobs" also written in Python - python functions. By necessity I think this would be a different thread, but not in a different process. To this end, I'm looking for the expressivity of the cron time expression, but in Python. Cron *has* been around for years, but I'm trying to be as portable as possible. I cannot rely on its presence.
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() time.sleep(1) ``` *Disclosure*: I'm the author of that library.
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, 16, 13, 0) ``` I.e., in English, get the current time (in UTC), convert it to some other timezone, set the time to midnight, then convert back to UTC. I'm not just using now() or localtime() as that would use the server's timezone, not the user's timezone. I can't help feeling I'm missing something, any ideas?
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 in your code: it will give the wrong result on the day of the switch to or from Daylight Saving Time. The reason for this is that neither the datetime constructors nor `replace()` take DST changes into account. For example: ``` >>> now = datetime(2012, 4, 1, 5, 0, 0, 0, tzinfo=pytz.timezone("Australia/Melbourne")) >>> print now 2012-04-01 05:00:00+10:00 >>> print now.replace(hour=0) 2012-04-01 00:00:00+10:00 # wrong! midnight was at 2012-04-01 00:00:00+11:00 >>> print datetime(2012, 3, 1, 0, 0, 0, 0, tzinfo=tz) 2012-03-01 00:00:00+10:00 # wrong again! ``` However, the documentation for `tz.localize()` states: > This method should be used to construct localtimes, rather > than passing a tzinfo argument to a datetime constructor. Thus, your problem is solved like so: ``` >>> import pytz >>> from datetime import datetime, date, time >>> tz = pytz.timezone("Australia/Melbourne") >>> the_date = date(2012, 4, 1) # use date.today() here >>> midnight_without_tzinfo = datetime.combine(the_date, time()) >>> print midnight_without_tzinfo 2012-04-01 00:00:00 >>> midnight_with_tzinfo = tz.localize(midnight_without_tzinfo) >>> print midnight_with_tzinfo 2012-04-01 00:00:00+11:00 >>> print midnight_with_tzinfo.astimezone(pytz.utc) 2012-03-31 13:00:00+00:00 ``` No guarantees for dates before 1582, though.
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, 16, 13, 0) ``` I.e., in English, get the current time (in UTC), convert it to some other timezone, set the time to midnight, then convert back to UTC. I'm not just using now() or localtime() as that would use the server's timezone, not the user's timezone. I can't help feeling I'm missing something, any ideas?
[@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).date() midnight = tz.localize(datetime.combine(today, time(0, 0)), is_dst=None) utc_dt = midnight.astimezone(pytz.utc) ``` The same with comments: ``` #!/usr/bin/env python from datetime import datetime, time import pytz # pip instal pytz tz = pytz.timezone("Australia/Melbourne") # choose timezone # 1. get correct date for the midnight using given timezone. today = datetime.now(tz).date() # 2. get midnight in the correct timezone (taking into account DST) #NOTE: tzinfo=None and tz.localize() # assert that there is no dst transition at midnight (`is_dst=None`) midnight = tz.localize(datetime.combine(today, time(0, 0)), is_dst=None) # 3. convert to UTC (no need to call `utc.normalize()` due to UTC has no # DST transitions) fmt = '%Y-%m-%d %H:%M:%S %Z%z' print midnight.astimezone(pytz.utc).strftime(fmt) ```
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_L, basestring): string_L = [string_L] try: split_char = split_chars[0] except IndexError: return string_L res = [] for s in string_L: res.extend(s.split(split_char)) return my_split(res, split_chars[1:]) print my_split("a b.c", [' ', '.']) ``` Horrible! Any better suggestions?
``` >>> 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 = paramiko.SSHClient() ssh.connect(server, username=username, password=password) ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command("psql -U factory -d factory -f /tmp/data.sql") ``` Does anyone know how this can addressed? Thank you.
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 standard Python file object, so `ssh_stdin.write` should work so long as the channel is still open. I've never needed to write to stdin, but the docs suggest that a channel is closed as soon as a command exits, so using the standard `stdin.write` method to send a password up probably won't work. There are lower level paramiko commands on the channel itself that give you more control - see how the [`SSHClient.exec_command`](http://docs.paramiko.org/paramiko.SSHClient-class.html#exec_command) method is implemented for all the gory details.
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-generate the python code you're looking for from C++ headers. ctypeslib:<http://pypi.python.org/pypi/ctypeslib/0.5.4a> h2xml.py will require another tool called gccxml: <http://www.gccxml.org/HTML/Index.html> it's best to check out (via CVS) the latest version of gccxml and build it yourself (actually easier done than said). The pre-packaged version is old.
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 bit. I need help from u people.
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.pack("=B",i) ## uint8_t res = struct.pack("=b",i) ## int8_t res = struct.pack("=H",i) ## uint16_t res = struct.pack("=h",i) ## int16_t res = struct.pack("=I",i) ## uint32_t res = struct.pack("=i",i) ## int32_t res = struct.pack("=Q",i) ## uint64_t res = struct.pack("=q",i) ## int64_t res = struct.pack("=f",i) ## float res = struct.pack("=d",i) ## double ``` `struct` produces a byte-string containing the number in binary. EDIT: From the comments it sounds like you just want to convert the string (of decimal digits) into an integer. Just use `int()` for that, however you won't get all the complicated overflow/underflow semantics of the specified types. You can't reproduce that in python, at least not without writing a whole lot of code. I think if you want any more help you'll have to be more precise about what you want to achieve.
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 order m=m+1, until m=n. I am on my way to write a solution of the form: ``` def findsubsets(S, m): subsets = set([]) ... return subsets ``` But knowing Python I expected a solution to be already there. What is the best way to accomplish this?
[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 order m=m+1, until m=n. I am on my way to write a solution of the form: ``` def findsubsets(S, m): subsets = set([]) ... return subsets ``` But knowing Python I expected a solution to be already there. What is the best way to accomplish this?
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, 2), (0, 1, 2)] ```
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 order m=m+1, until m=n. I am on my way to write a solution of the form: ``` def findsubsets(S, m): subsets = set([]) ... return subsets ``` But knowing Python I expected a solution to be already there. What is the best way to accomplish this?
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 than a list return chain.from_iterable( combinations(xs,n) for n in range(len(xs)+1) ) ``` Used like: ``` >>> list(powerset("abc")) [(), ('a',), ('b',), ('c',), ('a', 'b'), ('a', 'c'), ('b', 'c'), ('a', 'b', 'c')] >>> list(powerset(set([1,2,3]))) [(), (1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3)] ``` map to sets if you want so you can use union, intersection, etc...: ``` >>> map(set, powerset(set([1,2,3]))) [set([]), set([1]), set([2]), set([3]), set([1, 2]), set([1, 3]), set([2, 3]), set([1, 2, 3])] >>> reduce(lambda x,y: x.union(y), map(set, powerset(set([1,2,3])))) set([1, 2, 3]) ```
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 `.readline`? I'd like this to be portable or at least work under Windows and Linux. here is how I do it for now (It's blocking on the `.readline` if no data is avaible): ``` p = subprocess.Popen('myprogram.exe', stdout = subprocess.PIPE) output_str = p.stdout.readline() ```
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 output to a file and wait for the process to finish using **p.wait()**. ``` f = open('myprogram_output.txt','w') p = subprocess.Popen('myprogram.exe', stdout=f) p.wait() f.close() str = open('myprogram_output.txt','r').read() ```
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 `.readline`? I'd like this to be portable or at least work under Windows and Linux. here is how I do it for now (It's blocking on the `.readline` if no data is avaible): ``` p = subprocess.Popen('myprogram.exe', stdout = subprocess.PIPE) output_str = p.stdout.readline() ```
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 output out = myProc.read() if out != "": print out ``` The module takes care of all the threading as suggested by S.Lott.
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 `.readline`? I'd like this to be portable or at least work under Windows and Linux. here is how I do it for now (It's blocking on the `.readline` if no data is avaible): ``` p = subprocess.Popen('myprogram.exe', stdout = subprocess.PIPE) output_str = p.stdout.readline() ```
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 `readline()` blocks and has no timeout. If the primary functionality is complete and there is no longer any need to wait for further user input I typically want my program to exit, but it can't because `readline()` is still blocking in the other thread waiting for a line. A solution I have found to this problem is to make stdin a non-blocking file using the fcntl module: ``` import fcntl import os import sys # make stdin a non-blocking file fd = sys.stdin.fileno() fl = fcntl.fcntl(fd, fcntl.F_GETFL) fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK) # user input handling thread while mainThreadIsRunning: try: input = sys.stdin.readline() except: continue handleInput(input) ``` In my opinion this is a bit cleaner than using the select or signal modules to solve this problem but then again it only works on UNIX...
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 `.readline`? I'd like this to be portable or at least work under Windows and Linux. here is how I do it for now (It's blocking on the `.readline` if no data is avaible): ``` p = subprocess.Popen('myprogram.exe', stdout = subprocess.PIPE) output_str = p.stdout.readline() ```
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)) ``` For readline()-like: ``` lines = [''] while not p.poll(): lines = readAllSoFar(p, lines[-1]).split('\n') for a in range(len(lines)-1): print a lines = readAllSoFar(p, lines[-1]).split('\n') for a in range(len(lines)-1): print a ```
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 `.readline`? I'd like this to be portable or at least work under Windows and Linux. here is how I do it for now (It's blocking on the `.readline` if no data is avaible): ``` p = subprocess.Popen('myprogram.exe', stdout = subprocess.PIPE) output_str = p.stdout.readline() ```
[`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/437888#437888) won't help in this case. A reliable way to read a stream without blocking regardless of operating system is to use [`Queue.get_nowait()`](http://docs.python.org/library/queue.html#Queue.Queue.get): ``` import sys from subprocess import PIPE, Popen from threading import Thread try: from Queue import Queue, Empty except ImportError: from queue import Queue, Empty # python 3.x ON_POSIX = 'posix' in sys.builtin_module_names def enqueue_output(out, queue): for line in iter(out.readline, b''): queue.put(line) out.close() p = Popen(['myprogram.exe'], stdout=PIPE, bufsize=1, close_fds=ON_POSIX) q = Queue() t = Thread(target=enqueue_output, args=(p.stdout, q)) t.daemon = True # thread dies with the program t.start() # ... do other things here # read line without blocking try: line = q.get_nowait() # or q.get(timeout=.1) except Empty: print('no output yet') else: # got line # ... do something with line ```
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 `.readline`? I'd like this to be portable or at least work under Windows and Linux. here is how I do it for now (It's blocking on the `.readline` if no data is avaible): ``` p = subprocess.Popen('myprogram.exe', stdout = subprocess.PIPE) output_str = p.stdout.readline() ```
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()` method. Twisted (depending upon the reactor used) is usually just a big `select()` loop with callbacks installed to handle data from different file descriptors (often network sockets). So the `outReceived()` method is simply installing a callback for handling data coming from `STDOUT`. A simple example demonstrating this behavior is as follows: ``` from twisted.internet import protocol, reactor class MyProcessProtocol(protocol.ProcessProtocol): def outReceived(self, data): print data proc = MyProcessProtocol() reactor.spawnProcess(proc, './myprogram', ['./myprogram', 'arg1', 'arg2', 'arg3']) reactor.run() ``` The [Twisted documentation](http://twistedmatrix.com/documents/current/core/howto/process.html) has some good information on this. If you build your entire application around Twisted, it makes asynchronous communication with other processes, local or remote, really elegant like this. On the other hand, if your program isn't built on top of Twisted, this isn't really going to be that helpful. Hopefully this can be helpful to other readers, even if it isn't applicable for your particular application.
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 `.readline`? I'd like this to be portable or at least work under Windows and Linux. here is how I do it for now (It's blocking on the `.readline` if no data is avaible): ``` p = subprocess.Popen('myprogram.exe', stdout = subprocess.PIPE) output_str = p.stdout.readline() ```
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 ``` now you can do something like this: ``` import tornado_subprocess import tornado.ioloop def print_res( status, stdout, stderr ) : print status, stdout, stderr if status == 0: print "OK:" print stdout else: print "ERROR:" print stderr t = tornado_subprocess.Subprocess( print_res, timeout=30, args=[ "cat", "/etc/passwd" ] ) t.start() tornado.ioloop.IOLoop.instance().start() ``` you can also use it with a RequestHandler ``` class MyHandler(tornado.web.RequestHandler): def on_done(self, status, stdout, stderr): self.write( stdout ) self.finish() @tornado.web.asynchronous def get(self): t = tornado_subprocess.Subprocess( self.on_done, timeout=30, args=[ "cat", "/etc/passwd" ] ) t.start() ```
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 `.readline`? I'd like this to be portable or at least work under Windows and Linux. here is how I do it for now (It's blocking on the `.readline` if no data is avaible): ``` p = subprocess.Popen('myprogram.exe', stdout = subprocess.PIPE) output_str = p.stdout.readline() ```
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 methods are called as soon as data is ready: ``` #!/usr/bin/env python3 import asyncio import os class SubprocessProtocol(asyncio.SubprocessProtocol): def pipe_data_received(self, fd, data): if fd == 1: # got stdout data (bytes) print(data) def connection_lost(self, exc): loop.stop() # end loop.run_forever() if os.name == 'nt': loop = asyncio.ProactorEventLoop() # for subprocess' pipes on Windows asyncio.set_event_loop(loop) else: loop = asyncio.get_event_loop() try: loop.run_until_complete(loop.subprocess_exec(SubprocessProtocol, "myprogram.exe", "arg1", "arg2")) loop.run_forever() finally: loop.close() ``` See ["Subprocess" in the docs](https://docs.python.org/3/library/asyncio-subprocess.html). There is a high-level interface `asyncio.create_subprocess_exec()` that returns [`Process` objects](https://docs.python.org/3/library/asyncio-subprocess.html#process) that allows to read a line asynchroniosly using [`StreamReader.readline()` coroutine](https://docs.python.org/3/library/asyncio-stream.html#asyncio.StreamReader) (with [`async`/`await` Python 3.5+ syntax](https://www.python.org/dev/peps/pep-0492/)): ``` #!/usr/bin/env python3.5 import asyncio import locale import sys from asyncio.subprocess import PIPE from contextlib import closing async def readline_and_kill(*args): # start child process process = await asyncio.create_subprocess_exec(*args, stdout=PIPE) # read line (sequence of bytes ending with b'\n') asynchronously async for line in process.stdout: print("got line:", line.decode(locale.getpreferredencoding(False))) break process.kill() return await process.wait() # wait for the child process to exit if sys.platform == "win32": loop = asyncio.ProactorEventLoop() asyncio.set_event_loop(loop) else: loop = asyncio.get_event_loop() with closing(loop): sys.exit(loop.run_until_complete(readline_and_kill( "myprogram.exe", "arg1", "arg2"))) ``` `readline_and_kill()` performs the following tasks: * start subprocess, redirect its stdout to a pipe * read a line from subprocess' stdout asynchronously * kill subprocess * wait for it to exit Each step could be limited by timeout seconds if necessary.
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, wx.ID_ANY) f = open("test.jpg", "rb") image = wx.ImageFromStream(f) bitmap = wx.BitmapFromImage(image) static_bitmap.SetBitmap(bitmap) ``` But, what I really want to be able to do is create the image from data in memory. So, if I write ``` f = open("test.jpg", "rb") data = f.read() ``` how can I create a `wx.Image` object from `data`? Thanks for your help!
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 this can be done because I have seen it, but my googling for this has not yet been fruitful.
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 this can be done because I have seen it, but my googling for this has not yet been fruitful.
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: ``` DOMAIN = 'http://stackoverflow.com' QUESTIONS = '/questions' def so_question_uri_sub(q_num): return "%s%s/%d" % (DOMAIN, QUESTIONS, q_num) def so_question_uri_cat(q_num): return DOMAIN + QUESTIONS + '/' + str(q_num) ``` Edit: There have also been suggestions about joining a list of strings and for using named substitution. These are variants on the central theme, which is, which way is the Right Way to do it at which time? Thanks for the responses!
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 >>> def so_q_sub(n): ... return "%s%s/%d" % (DOMAIN, QUESTIONS, n) ... >>> so_q_sub(1000) 'http://stackoverflow.com/questions/1000' >>> def so_q_cat(n): ... return DOMAIN + QUESTIONS + '/' + str(n) ... >>> so_q_cat(1000) 'http://stackoverflow.com/questions/1000' >>> t1 = timeit.Timer('so_q_sub(1000)','from __main__ import so_q_sub') >>> t2 = timeit.Timer('so_q_cat(1000)','from __main__ import so_q_cat') >>> t1.timeit(number=10000000) 12.166618871951641 >>> t2.timeit(number=10000000) 5.7813972166853773 >>> t1.timeit(number=1) 1.103492206766532e-05 >>> t2.timeit(number=1) 8.5206360154188587e-06 >>> def so_q_tmp(n): ... return "{d}{q}/{n}".format(d=DOMAIN,q=QUESTIONS,n=n) ... >>> so_q_tmp(1000) 'http://stackoverflow.com/questions/1000' >>> t3= timeit.Timer('so_q_tmp(1000)','from __main__ import so_q_tmp') >>> t3.timeit(number=10000000) 14.564135316080637 >>> def so_q_join(n): ... return ''.join([DOMAIN,QUESTIONS,'/',str(n)]) ... >>> so_q_join(1000) 'http://stackoverflow.com/questions/1000' >>> t4= timeit.Timer('so_q_join(1000)','from __main__ import so_q_join') >>> t4.timeit(number=10000000) 9.4431309007150048 ```
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: ``` DOMAIN = 'http://stackoverflow.com' QUESTIONS = '/questions' def so_question_uri_sub(q_num): return "%s%s/%d" % (DOMAIN, QUESTIONS, q_num) def so_question_uri_cat(q_num): return DOMAIN + QUESTIONS + '/' + str(q_num) ``` Edit: There have also been suggestions about joining a list of strings and for using named substitution. These are variants on the central theme, which is, which way is the Right Way to do it at which time? Thanks for the responses!
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 `q_num` parameter. To do the same thing, you would have to write `return DOMAIN + QUESTIONS + "/" + str(q_num)` in that example. * Interpolation makes it easier to format numerics; `"%d of %d (%2.2f%%)" % (current, total, total/current)` would be much less readable in concatenation form. * Concatenation is useful when you don't have a fixed number of items to string-ize. Also, know that Python 2.6 introduces a new version of string interpolation, called [string templating](http://docs.python.org/dev/3.0/whatsnew/2.6.html#pep-3101): ``` def so_question_uri_template(q_num): return "{domain}/{questions}/{num}".format(domain=DOMAIN, questions=QUESTIONS, num=q_num) ``` String templating is slated to eventually replace %-interpolation, but that won't happen for quite a while, I think.
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: ``` DOMAIN = 'http://stackoverflow.com' QUESTIONS = '/questions' def so_question_uri_sub(q_num): return "%s%s/%d" % (DOMAIN, QUESTIONS, q_num) def so_question_uri_cat(q_num): return DOMAIN + QUESTIONS + '/' + str(q_num) ``` Edit: There have also been suggestions about joining a list of strings and for using named substitution. These are variants on the central theme, which is, which way is the Right Way to do it at which time? Thanks for the responses!
"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 operations are the performance limiters, I'll stick with things that are obvious. Mostly, that's substitution when it's one line or less, concatenation when it makes sense, and a template tool (like Mako) when it's large.
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: ``` DOMAIN = 'http://stackoverflow.com' QUESTIONS = '/questions' def so_question_uri_sub(q_num): return "%s%s/%d" % (DOMAIN, QUESTIONS, q_num) def so_question_uri_cat(q_num): return DOMAIN + QUESTIONS + '/' + str(q_num) ``` Edit: There have also been suggestions about joining a list of strings and for using named substitution. These are variants on the central theme, which is, which way is the Right Way to do it at which time? Thanks for the responses!
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: ``` DOMAIN = 'http://stackoverflow.com' QUESTIONS = '/questions' def so_question_uri_sub(q_num): return "%s%s/%d" % (DOMAIN, QUESTIONS, q_num) def so_question_uri_cat(q_num): return DOMAIN + QUESTIONS + '/' + str(q_num) ``` Edit: There have also been suggestions about joining a list of strings and for using named substitution. These are variants on the central theme, which is, which way is the Right Way to do it at which time? Thanks for the responses!
**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 quadratic algorithm down to linear. Best to use the primitive (`join`?) that takes an entire list of strings, does a single allocation, and concatenates them all in one go.
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 imagine it's `launchmissiles`)
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"].split(os.pathsep): path = path.strip('"') exe_file = os.path.join(path, program) if is_exe(exe_file): return exe_file return None ``` **Edit**: Updated code sample to include logic for handling case where provided argument is already a full path to the executable, i.e. "which /bin/ls". This mimics the behavior of the UNIX 'which' command. **Edit**: Updated to use os.path.isfile() instead of os.path.exists() per comments.
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 imagine it's `launchmissiles`)
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 parameter of access() to determine if path can be executed. **EDIT:** The suggested `which()` implementations are missing one clue - using [`os.path.join()`](http://docs.python.org/library/os.path.html#os.path.join) to build full file names.
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 imagine it's `launchmissiles`)
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 system will do it for you as part of `popen` call & will raise an exception if the executable is not found. All you need to do is catch the correct exception for given OS. Note that on Windows, `subprocess.Popen(exe, shell=True)` will fail silently if `exe` is not found. --- Incorporating `PATHEXT` into the above implementation of `which` (in Jay's answer): ``` def which(program): def is_exe(fpath): return os.path.exists(fpath) and os.access(fpath, os.X_OK) def ext_candidates(fpath): yield fpath for ext in os.environ.get("PATHEXT", "").split(os.pathsep): yield fpath + ext fpath, fname = os.path.split(program) if fpath: if is_exe(program): return program else: for path in os.environ["PATH"].split(os.pathsep): exe_file = os.path.join(path, program) for candidate in ext_candidates(exe_file): if is_exe(candidate): return candidate return None ```
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 imagine it's `launchmissiles`)
## 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 ``` What we're doing here is using the builtin command `type` and checking the exit code. If there's no such command, `type` will exit with 1 (or a non-zero status code anyway). The bit about stdout and stderr is just to silence the output of the `type` command, since we're only interested in the exit status code. Example usage: ``` >>> cmd_exists("jsmin") True >>> cmd_exists("cssmin") False >>> cmd_exists("ls") True >>> cmd_exists("dir") False >>> cmd_exists("node") True >>> cmd_exists("steam") False ```
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 imagine it's `launchmissiles`)
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/shutil.html).
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 imagine it's `launchmissiles`)
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 advantage of multicore CPUs? In normal Python you have the GIL being constantly present and to make (true) use of multiple cores you need to use several processes, is this true for [Stackless](http://www.stackless.com/) also?
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 Stackless uses a round-robin scheduler to schedule every [tasklet](http://www.stackless.com/wiki/Tasklets) (micro threads), but no tasklet can be run concurrent with another one. This means that if one tasklet is busy, the others must wait until that tasklet relinquishes control. By default the scheduler will not stop a tasklet and give processor time to another. It is the tasklet's responsibility to schedule itself back in the end of the schedule queue using Stackless.schedule(), or by finishing its calculations. **all tasklets are thus executed in a sequential manner**, even when multiplpe cores are available. The reason why Stackless does not have multi-core support is because this makes threads a whole lot easier. And this is just what stackless is all about: [from the official stackless website](http://www.stackless.com/) > Stackless Python is an enhanced > version of the Python programming > language. It allows programmers to > reap the benefits of thread-based > programming without the performance > and complexity problems associated > with conventional threads. The > microthreads that Stackless adds to > Python are a cheap and lightweight > convenience which can if used > properly, give the following benefits: > > * Improved program structure. > * More readable code. > * Increased programmer productivity. Here is a [link](http://www.stackless.com/pipermail/stackless/2007-August/001963.html) to some more information about multiple cores and stackless.
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='monkeys') [<User: cms>, <User: dewey>] ```
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__(mess) ``` but when the program got to the call to `BaseException.__init__()`, I got this traceback: ``` BaseException.__init__(mess) TypeError: descriptor '__init__' requires a 'exceptions.BaseException' object but received a 'str' ``` I thought that BaseException would take any set of arguments. Also, how I am supposed to pass an 'exceptions.BaseException' object into exceptions.BaseException's constructor?
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 base class method of the same name. There is a simple way to call the base class method directly: just call `BaseClassName.methodname(self, arguments)`. This is occasionally useful to clients as well. (Note that this only works if the base class is defined or imported directly in the global scope.) As mentioned by Tony Arkles and in [the documentation](http://docs.python.org/library/exceptions.html#exceptions.Exception), > All built-in, non-system-exiting exceptions are derived from this class. All user-defined exceptions should also be derived from [`Exception`]. so you shouldn't inherit from `BaseException`, anyway...
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 return characters in your script, but I wrote my test script right from the shell with pico. Also, when I run the file from the command line it executes just fine. " So far the only change I have made to apache is to add the .py to the "AddHandler cgi-script" line. Thanks! --- Thanks for the quick responses. Here is the latest version of the test code. I added a couple new lines before the output as suggested but still get the same error: ``` #!/usr/local/bin/python print "Content-type: text/html\n" print "\n\n" print "<HTML>" print "<HEAD>" print "<TITLE>Test</TITLE>" print "</HEAD>" print "<BODY>" print "<H2>Hi there.</h2>" print "</BODY>" print "</HTML>" ``` Some other details: I am running Apache 1.3 and don't have mod\_python. I set apache to recognize .py as mentioned above. I am running the script from the main public\_html folder. --- An update. It doesn't seem to matter what I put in the shebang line. I tried all of the suggestions and even if I leave it blank the same error is showing up in the errors log and I'm getting a 500 error. I'm running Apache/1.3.41 on linux (red hat 3.4) with WHM/Cpanel installed.
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 using older Python versions, you must use '[dispatch.generic()]' instead of '@dispatch.generic()'. OK, so it apparently is a way to get decorator-like behavior in pre-decorator versions of Python, but how the heck can it possibly work?
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 change in 2.2, 2.3, or 2.4, so don't worry about it too much. This is really a trick to get "early access" to decorators, and the 2.4 lifecycle will be plenty long enough to get our code switched over to 2.4 syntax. Somewhere around Python 2.5 or 2.6, add\_assignment\_advisor() can drop the magic part and just be a backward compatibility wrapper for the decorators that use it. """ <http://dirtsimple.org/2004/11/using-24-decorators-with-22-and-23.html> So it sounds like these work by wrapping the actual decorator in some magic that hooks into special code for debuggers to manipulate what actually gets assigned for the function. The python docs say this about settrace """ Note The settrace() function is intended only for implementing debuggers, profilers, coverage tools and the like. Its behavior is part of the implementation platform, rather than part of the language definition, and thus may not be available in all Python implementations. """
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 protocol. @param ampChild: a L{ampoule.child.AMPChild} subclass. @type ampChild: L{ampoule.child.AMPChild} subclass """ ``` What are these tags, which tool uses it.
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 protocol. @param ampChild: a L{ampoule.child.AMPChild} subclass. @type ampChild: L{ampoule.child.AMPChild} subclass """ ``` What are these tags, which tool uses it.
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` subclass. :type ampChild: :class:`ampoule.child.AMPChild` subclass """ ```
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.60000000000002, 999.20000000000005] >>> ``` It is only good if they're all the same type.
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 >>> parseStr = lambda x: x.isalpha() and x or x.isdigit() and \ ... int(x) or x.isalnum() and x or \ ... len(set(string.punctuation).intersection(x)) == 1 and \ ... x.count('.') == 1 and float(x) or x >>> parseStr('123') 123 >>> parseStr('123.3') 123.3 >>> parseStr('3HC1') '3HC1' >>> parseStr('12.e5') 1200000.0 >>> parseStr('12$5') '12$5' >>> parseStr('12.2.2') '12.2.2' ```
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' ``` >>> import ast >>> ast.literal_eval("545.2222") 545.2222 >>> ast.literal_eval("31") 31 ```
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 = "31" >>> result = yaml.load(b) >>> result 31 >>> type(result) <type 'int'> >>> c = "HI" >>> result = yaml.load(c) >>> result 'HI' >>> type(result) <type 'str'> ```