content stringlengths 85 101k | title stringlengths 0 150 | question stringlengths 15 48k | answers list | answers_scores list | non_answers list | non_answers_scores list | tags list | name stringlengths 35 137 |
|---|---|---|---|---|---|---|---|---|
Q:
Referring to class names through strings?
I need to parse some text file, create objects for various entities encountered in the text, and put them in some data structure (e.g., a list) for further processing. Example of the text:
laptop
17" dell, weight: 12 lb
desktop
24" hp
I know in advance which entities may exist in the text, and what attributes they are supposed to have. In this example, I would already have classes laptop and desktop defined (probably subclasses of class computer). The parser would just need to create objects laptop('dell', 17, 12), and dekstop('hp', 24).
If I follow this route, I would need to retrieve class names from strings, and create objects of those classes. Is it the Pythonic way of doing things? If so, what's the best approach (using Python 3.1)? If not, what should I do instead?
Thanks!
What
A:
If the classes are defined in computers.py, say, you can do
import computers
getattr( computers, "Laptop" )( <params> )
to instantiate a computers.Laptop. If they are defined in the same file that you are running the code in (so that they are global variables), you can do
globals()[ "Laptop" ]
but this is less elegant; it would be nicer to put them in a separate scope.
Alternatively, if you want a more powerful mapping (say you want "Nettop", "Lapbook", and "Laptop" all to instantiate Laptop), you could maintain a mapping of strings to their corresponding constructor and use that:
mapping = { "Laptop": Laptop, "Nettop": Laptop, ... }
mapping[ "Laptop" ]()
A:
you can create instances of a class by it's name using the following code
obj = globals()[classname]()
where classname is a string
A:
Technically, what you're asking for (or at least the way everyone is interpreting it) just isn't very good practice, especially if you might be taking input from an untrusted source (remember, any source other than yourself should generally be considered untrusted!). You should whitelist these things explicitly, because someone might trigger the execution of a function or creation of an object you didn't intend with properties you really don't want...
What you can do instead is something like this (this is of course wildly incomplete, but should give you the general idea):
class Laptop(object):
pass
class Desktop(object):
pass
possible_classes = {
"laptop": Laptop,
"desktop": Desktop,
}
new_object = possible_classes[identifier_string](propA, propB, propC, ...)
Then just add the mapping for each new kind of object to the possible_classes dict.
A:
I think a inspection-based method would potentially be quite fragile and resistant to change. What if you want to use classes from other modules?
Why not a object factory? It could be a simple function or a class.
Example:
class ComputerFactory:
def __init__(self):
self._classes = {}
def register(moniker, creator):
"""Moniker is a name for the class.
Creator is a callable that creates the object
for the moniker.
"""
self._classes[moniker] = creator
def create(moniker, *args, **kwargs):
return self._classes[moniker](*args, **kwargs)
# Example usage
fac = ComputerFactory()
# Register constructor
fac.register("laptop", Laptop) # Laptop class is also a callable (the constructor)
# Register construction proxy
def sony_laptop_builder(make):
return Laptop("Sony")
fac.register("laptop", sony_laptop_builder)
A:
Not sure about the syntax of python code but is this what you want?
for item in parsedString:
if item == "laptop":
laptops.add(laptop()) #laptops is a list of laptops you
#have encountered so far in your list
# add the next elements to your laptop instance
if item == "desktop":
# code for desktop...
| Referring to class names through strings? | I need to parse some text file, create objects for various entities encountered in the text, and put them in some data structure (e.g., a list) for further processing. Example of the text:
laptop
17" dell, weight: 12 lb
desktop
24" hp
I know in advance which entities may exist in the text, and what attributes they are supposed to have. In this example, I would already have classes laptop and desktop defined (probably subclasses of class computer). The parser would just need to create objects laptop('dell', 17, 12), and dekstop('hp', 24).
If I follow this route, I would need to retrieve class names from strings, and create objects of those classes. Is it the Pythonic way of doing things? If so, what's the best approach (using Python 3.1)? If not, what should I do instead?
Thanks!
What
| [
"If the classes are defined in computers.py, say, you can do\nimport computers\ngetattr( computers, \"Laptop\" )( <params> )\n\nto instantiate a computers.Laptop. If they are defined in the same file that you are running the code in (so that they are global variables), you can do\nglobals()[ \"Laptop\" ]\n\nbut thi... | [
11,
5,
4,
1,
0
] | [] | [] | [
"class",
"python",
"string"
] | stackoverflow_0003439082_class_python_string.txt |
Q:
incorporating a sys.argv into a mySQL query in python
I'm writing a program that first queries with mySQL and then sorts that data. I want to be able to have a user type "python program_name.py mySQL_query" and have the program insert "mySQL_query" into the query at the beginning of the program. The issue I'm running into is the sys.argv command converts the input into a string, which mySQL then rejects. I've tried a few things to convert the sys.argv into a name instead of a string but they haven't been successful. Any ideas?
A:
Your code needs to like something like this:
qb="SELECT DISTINCT q19_scan.array_orientation_equatorial, q19_scan.run_id, q19_scan.run_subid, q19_scan.patch_day_number, %s FROM q19_typeb NATURAL JOIN q19_scan NATURAL JOIN q19_timestream NATURAL JOIN q19_weather NATURAL JOIN q19_ces_usable WHERE " % sys.argv[2]
I have replaced sys.argv[2] in your query with %s, and then applied formatting operator on this string with second operand being sys.argv[2]. You can read more about python's formatting operator in documentation, or even use newer formatting functions:
| incorporating a sys.argv into a mySQL query in python | I'm writing a program that first queries with mySQL and then sorts that data. I want to be able to have a user type "python program_name.py mySQL_query" and have the program insert "mySQL_query" into the query at the beginning of the program. The issue I'm running into is the sys.argv command converts the input into a string, which mySQL then rejects. I've tried a few things to convert the sys.argv into a name instead of a string but they haven't been successful. Any ideas?
| [
"Your code needs to like something like this:\nqb=\"SELECT DISTINCT q19_scan.array_orientation_equatorial, q19_scan.run_id, q19_scan.run_subid, q19_scan.patch_day_number, %s FROM q19_typeb NATURAL JOIN q19_scan NATURAL JOIN q19_timestream NATURAL JOIN q19_weather NATURAL JOIN q19_ces_usable WHERE \" % sys.argv[2]\n... | [
1
] | [] | [] | [
"command_line_arguments",
"mysql",
"python",
"string"
] | stackoverflow_0003419485_command_line_arguments_mysql_python_string.txt |
Q:
Why type coercion works differently on scripts / interactive prompt?
I'm using Python 3.1.2 (Mac OS X 10.6) and found this weird behavior (I'm a newbie, btw):
On the interactive prompt:
>>> fraction = 4 / 3
>>> print(fraction)
1.33333333333
>>> print(type(fraction))
<class 'float'>
However, if I do the same thing in a script, results are different:
## fraction.py
fraction = 4 / 3
print(fraction)
print(type(fraction))
Output:
1
<class 'int'>
Is this normal?
A:
No it's not normal. Are you sure you are running Python 3 in that script? It's possible that Python 2.5 (the default install on Mac OS X) is chosen. Try to verify by
import sys
print (sys.version)
If you are running the script as ./fraction.py, you could force the shell to use Python 3.1 by putting
#!/usr/bin/env python3.1
in the first line.
A:
What KennyTM said. The reason is that in Python <3, / signifies integer division if both arguments are integers. This was silly, and was changed in Py3k so that / always returns a float, even if dividing ints.
| Why type coercion works differently on scripts / interactive prompt? | I'm using Python 3.1.2 (Mac OS X 10.6) and found this weird behavior (I'm a newbie, btw):
On the interactive prompt:
>>> fraction = 4 / 3
>>> print(fraction)
1.33333333333
>>> print(type(fraction))
<class 'float'>
However, if I do the same thing in a script, results are different:
## fraction.py
fraction = 4 / 3
print(fraction)
print(type(fraction))
Output:
1
<class 'int'>
Is this normal?
| [
"No it's not normal. Are you sure you are running Python 3 in that script? It's possible that Python 2.5 (the default install on Mac OS X) is chosen. Try to verify by\nimport sys\nprint (sys.version)\n\nIf you are running the script as ./fraction.py, you could force the shell to use Python 3.1 by putting\n#!/usr/bi... | [
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0003439442_python.txt |
Q:
matplotlib: add circle to plot
How do I add a small filled circle or point to a countour plot in matplotlib?
A:
Here is an example, using pylab.Circle:
import numpy as np
import matplotlib.pyplot as plt
e = np.e
X, Y = np.meshgrid(np.linspace(0, 5, 100), np.linspace(0, 5, 100))
F = X ** Y
G = Y ** X
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
circ = plt.Circle((e, e), radius=0.07, color='g')
plt.contour(X, Y, (F - G), [0])
ax.add_patch(circ)
plt.show()
And here is another example (though not a contour plot) from the docs.
Or, you could just use plot:
import numpy as np
import matplotlib.pyplot as plt
e = np.e
X, Y = np.meshgrid(np.linspace(0, 5, 100), np.linspace(0, 5, 100))
F = X ** Y
G = Y ** X
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
plt.contour(X, Y, (F - G), [0])
plt.plot([e], [e], 'g.', markersize=20.0)
plt.show()
| matplotlib: add circle to plot | How do I add a small filled circle or point to a countour plot in matplotlib?
| [
"Here is an example, using pylab.Circle:\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ne = np.e\nX, Y = np.meshgrid(np.linspace(0, 5, 100), np.linspace(0, 5, 100))\nF = X ** Y\nG = Y ** X\n\nfig = plt.figure()\nax = fig.add_subplot(1, 1, 1)\ncirc = plt.Circle((e, e), radius=0.07, color='g')\nplt.contour(X... | [
38
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0003439639_matplotlib_python.txt |
Q:
Modifying an open source python program
I have an open source project written in python , it has some Forms and I want to modify a few things in the code and in the forms but it is my first time with python and I don't know what IDE to use and how to start ..my basic question is can I deal with forms in python like c#, java ...etc ? and how should I start ?
A:
Because this project uses pyGTK, you can use glade which is a gtk forms designer, but it would probably add an extra layer of complexity that's really not necessary. Since you're already familiar with C#/Java, I'd recommend running through the official Python tutorial. Then I'd take a look at this excellent PyGTK tutorial. If you spend about a day really trying to understand the Python model and the "pythonic" way of doing things, you should then be able to easily modify that program.
While you probably don't need to use and IDE for a project this simple, if you want, you can use Eclipse (which you may be familiar with coming from Java) with PyDev. It allows you to write/debug Python programs inside the what may be the familiar Eclipse IDE.
| Modifying an open source python program | I have an open source project written in python , it has some Forms and I want to modify a few things in the code and in the forms but it is my first time with python and I don't know what IDE to use and how to start ..my basic question is can I deal with forms in python like c#, java ...etc ? and how should I start ?
| [
"Because this project uses pyGTK, you can use glade which is a gtk forms designer, but it would probably add an extra layer of complexity that's really not necessary. Since you're already familiar with C#/Java, I'd recommend running through the official Python tutorial. Then I'd take a look at this excellent PyGTK ... | [
4
] | [] | [] | [
"open_source",
"python"
] | stackoverflow_0003439895_open_source_python.txt |
Q:
Python Equivalent to phpinfo()
Quite simply, is there a python equivalent to php's phpinfo();? If so, what is it and how do I use it (a link to a reference page would work great).
A:
Check this one out!
pyinfo() A good looking phpinfo-like python script
A:
Did you try this out: http://www.webhostingtalk.com/showpost.php?s=f55e18d344e3783edd98aef5be809ac8&p=4632018&postcount=4
A:
There is nothing directly comparable to phpinfo(), but you can get some bits of information ...
>>> import sys
>>> sys.version
'2.6.4 (r264:75706, Feb 6 2010, 01:49:44) \n[GCC 4.2.1 (Apple Inc. build 5646)]'
>>> sys.platform
'darwin'
>>> sys.modules.keys()
['copy_reg', 'sre_compile', '_sre', 'encodings', 'site', ... ]
>>> import os
>>> os.name
'posix'
>>> import platform
>>> platform.architecture()
('32bit', '')
>>> platform.machine()
'i386'
...
A:
Afaik there is no similar function. However, the platform module allows you to access some basic information about the machine, OS and Python.
A:
phpinfo prints information about running PHP version, loaded modules and so on.
AFAIK Python does not such a conventient function that dumps the complete configuration.
But you should have a look at the sys package.
import sys
# print all imported modules since start
print sys.modules
# print load path
print sys.path
...
Check out Python's sys-library reference.
| Python Equivalent to phpinfo() | Quite simply, is there a python equivalent to php's phpinfo();? If so, what is it and how do I use it (a link to a reference page would work great).
| [
"Check this one out!\npyinfo() A good looking phpinfo-like python script\n",
"Did you try this out: http://www.webhostingtalk.com/showpost.php?s=f55e18d344e3783edd98aef5be809ac8&p=4632018&postcount=4\n",
"There is nothing directly comparable to phpinfo(), but you can get some bits of information ...\n>>> import... | [
4,
3,
2,
1,
0
] | [] | [] | [
"php",
"python"
] | stackoverflow_0002572371_php_python.txt |
Q:
antlr to generate python code is feasible?
the requirement is to generate several classes which inherits the base ORM class,
and this class may have several static properties like columns and other things,
and little bit python expressions that can be eval at run time for small business logic,
my question is, it is feasible to use antlr for such kind of things, as I'm not much familiar with antlr but google suggested me to use antlr for python code generator...
please advice......
A:
I think you have misunderstood the point of the ANTLR project. ANTLR is a parser generator, which means roughly:
You create a grammer for a language of your choosing. This could well be python, or a hybrid of it.
You run it through ANTLR which gives you code in a number of Languages capable of parsing your language.
This is useful in generating custom scripting languages and the natural language processing domain, both of which are (effectively) related.
Your problem sounds more like you are trying to generate some python code to model a business situation for an enterprise application (loathe as I am to use that term). Rather than reinvent the wheel I suggest you take a look at existing frameworks for achieving this such as SQLAlchemy and Django, both of which provide a base ORM implementation and allow you to derive subclasses which represent your data and include processing logic.
If you are looking for a solution to generate this for you from a description such as UML, I am sure someone is trying to do this too.
| antlr to generate python code is feasible? | the requirement is to generate several classes which inherits the base ORM class,
and this class may have several static properties like columns and other things,
and little bit python expressions that can be eval at run time for small business logic,
my question is, it is feasible to use antlr for such kind of things, as I'm not much familiar with antlr but google suggested me to use antlr for python code generator...
please advice......
| [
"I think you have misunderstood the point of the ANTLR project. ANTLR is a parser generator, which means roughly:\n\nYou create a grammer for a language of your choosing. This could well be python, or a hybrid of it.\nYou run it through ANTLR which gives you code in a number of Languages capable of parsing your lan... | [
5
] | [] | [] | [
"antlr",
"code_generation",
"python"
] | stackoverflow_0003440224_antlr_code_generation_python.txt |
Q:
is there need for a more declarative way of expressing regular expressions ? :)
I am trying to create a Python function that can take an plain English description of a regular expression and return the regular expression to the caller.
Currently I am thinking of the description in YAML format.
So, we can store the description as a raw string variable, which is passed on to this another function and output of that function is then passed to the 're' module. Following is a rather simplistic example:
# a(b|c)d+e*
re1 = """
- literal: 'a'
- one_of: 'b,c'
- one_or_more_of: 'd'
- zero_or_more_of: 'e'
"""
myre = re.compile(getRegex(re1))
myre.search(...)
etc.
Does anyone think something of this sort would be of wider use?
Do you know already existing packages that can do it?
What are the limitations that you see to this approach?
Does anyone think, having the declarative string in code, would make it more maintainable?
A:
This is actually pretty similar (identical?) to how a lexer/parser works. If you had a defined grammar then you could probably write a parser with not too much trouble. For instance, you could write something like this:
<expression> :: == <rule> | <rule> <expression> | <rule> " followed by " <expression>
<rule> :: == <val> | <qty> <val>
<qty> :: == "literal" | "one" | "one of" | "one or more of" | "zero or more of"
<val> :: == "a" | "b" | "c" | "d" | ... | "Z" |
That's nowhere near a perfect description. For more info, take a look at this BNF of the regex language. You could then look at lexing and parsing the expression.
If you did it this way you could probably get a little closer to Natural Language/English versions of regexes.
I can see a tool like this being useful, but as was previously said, mainly for beginners.
The main limitation to this approach would be in the amount of code you have to write to translate the language into regex (and/or vice versa). On the other hand, I think a two-way translation tool would actually be more ideal and see more use. Being able to take a regex and turn it into English might be a lot more helpful to spot errors.
Of course it doesn't take too long to pickup regex as the syntax is usually terse and most of the meanings are pretty self explanatory, at least if you use | or || as OR in your language, and you think of * as multiplying by 0-N, + as adding 0-N.
Though sometimes I wouldn't mind typing "find one or more 'a' followed by three digits or 'b' then 'c'"
A:
Please take a look at pyparsing. Many of the issues that you describe with RE's are the same ones that inspired me to write that package.
Here are some specific features of pyparsing from the O'Reilly e-book chapter "What's so special about pyparsing?".
A:
maybe not exactly what you are asking for, but there is a way how to write regexes more readable way (VERBOSE, shortly X flag):
rex_name = re.compile("""
[A-Za-z] # first letter
[a-z]+ # the rest
""", re.X)
rex_name.match('Joe')
A:
For developers trying to write regular expressions that are easy to grok and maintain, I wonder whether this sort of approach would offer anything that re.VERBOSE does not provide already.
For beginners, your idea might have some appeal. However, before you go down this path, you might try to mock up what your declarative syntax would look like for more complicated regular expressions using capturing groups, anchors, look-ahead assertions, and so forth. One challenge is that you might end up with a declarative syntax that is just as difficult to remember as the regex language itself.
You might also think about alternative ways to express things. For example, the first thought that occurred to me was to express a regex using functions with short, easy-to-remember names. For example:
from refunc import *
pattern = Compile(
'a',
Capture(
Choices('b', 'c'),
N_of( 'd', 1, Infin() ),
N_of( 'e', 0, Infin() ),
),
Look_ahead('foo'),
)
But when I see that in action, it looks like a pain to me. There are many aspects of regex that are quite intuitive -- for example, + to mean "one or more". One option would be a hybrid approach, allowing your user to mix those parts of regex that are already simple with functions for the more esoteric bits.
pattern = Compile(
'a',
Capture(
'[bc]',
'd+',
'e*',
),
Look_ahead('foo'),
)
I would add that in my experience, regular expressions are about learning a thought process. Getting comfortable with the syntax is the easy part.
| is there need for a more declarative way of expressing regular expressions ? :) | I am trying to create a Python function that can take an plain English description of a regular expression and return the regular expression to the caller.
Currently I am thinking of the description in YAML format.
So, we can store the description as a raw string variable, which is passed on to this another function and output of that function is then passed to the 're' module. Following is a rather simplistic example:
# a(b|c)d+e*
re1 = """
- literal: 'a'
- one_of: 'b,c'
- one_or_more_of: 'd'
- zero_or_more_of: 'e'
"""
myre = re.compile(getRegex(re1))
myre.search(...)
etc.
Does anyone think something of this sort would be of wider use?
Do you know already existing packages that can do it?
What are the limitations that you see to this approach?
Does anyone think, having the declarative string in code, would make it more maintainable?
| [
"This is actually pretty similar (identical?) to how a lexer/parser works. If you had a defined grammar then you could probably write a parser with not too much trouble. For instance, you could write something like this:\n<expression> :: == <rule> | <rule> <expression> | <rule> \" followed by \" <expression>\n<rule... | [
6,
6,
3,
3
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0003439471_python_regex.txt |
Q:
Find text then add line after in Python
I need to read a plist file and search for a string, then add a new line of text on the next line. I can't imagine it will take much to do this. However the plist is in binary format so not exactly sure how to deal with that.
Thanks in advance,
Aaron
#Convert plist to XML
os.system('plutil -convert xml1 com.apple.iChat.Jabber.plist')
AutoDiscovery = "<integer>0<integer>"
import fileinput
for line in fileinput.FileInput("com.apple.iChat.Jabber.plist",inplace=1):
line = line.replace("<key>AutoDiscoverHostAndPort</key>",AutoDiscovery)
print line,
#Concert plist to binary file
os.system('plutil -convert binary1 com.apple.iChat.Jabber.plist')
A:
You want to convert it into xml format first:
plutil -convert xml file.plist
Then the rest should be fairly easy.
EDIT:
newFile = open('file.copy', 'w+')
for line in open('file'):
if (line.find('string_to_find') >= 0):
# do something with "line"
newFile.write(line)
newFile.close()
EDIT2:
# convert plist from binary to xml
plist = plistlib.readPlist('your.plist')
plist['key'] = 0
plistlib.writePlist('your.plist')
# convert plist from xml to binary
A:
Use plistlib for all your plist file needs. No conversion needed.
| Find text then add line after in Python | I need to read a plist file and search for a string, then add a new line of text on the next line. I can't imagine it will take much to do this. However the plist is in binary format so not exactly sure how to deal with that.
Thanks in advance,
Aaron
#Convert plist to XML
os.system('plutil -convert xml1 com.apple.iChat.Jabber.plist')
AutoDiscovery = "<integer>0<integer>"
import fileinput
for line in fileinput.FileInput("com.apple.iChat.Jabber.plist",inplace=1):
line = line.replace("<key>AutoDiscoverHostAndPort</key>",AutoDiscovery)
print line,
#Concert plist to binary file
os.system('plutil -convert binary1 com.apple.iChat.Jabber.plist')
| [
"You want to convert it into xml format first:\nplutil -convert xml file.plist\n\nThen the rest should be fairly easy.\nEDIT:\nnewFile = open('file.copy', 'w+')\nfor line in open('file'):\n if (line.find('string_to_find') >= 0):\n # do something with \"line\"\n newFile.write(line)\nnewFile.close()\n\nE... | [
2,
0
] | [] | [] | [
"plist",
"python"
] | stackoverflow_0003440750_plist_python.txt |
Q:
How to check type of variable? Python
I need to do one thing if args is integer and ather thing if args is string.
How can i chack type? Example:
def handle(self, *args, **options):
if not args:
do_something()
elif args is integer:
do_some_ather_thing:
elif args is string:
do_totally_different_thing()
A:
First of, *args is always a list. You want to check if its content are strings?
import types
def handle(self, *args, **options):
if not args:
do_something()
# check if everything in args is a Int
elif all( isinstance(s, types.IntType) for s in args):
do_some_ather_thing()
# as before with strings
elif all( isinstance(s, types.StringTypes) for s in args):
do_totally_different_thing()
It uses types.StringTypes because Python actually has two kinds of strings: unicode and bytestrings - this way both work.
In Python3 the builtin types have been removed from the types lib and there is only one string type.
This means that the type checks look like isinstance(s, int) and isinstance(s, str).
A:
You could also try to do it in a more Pythonic way without using type or isinstance(preferred because it supports inheritance):
if not args:
do_something()
else:
try:
do_some_other_thing()
except TypeError:
do_totally_different_thing()
It obviously depends on what do_some_other_thing() does.
A:
type(variable_name)
Then you need to use:
if type(args) is type(0):
blabla
Above we are comparing if the type of the variable args is the same as the literal 0 which is an integer, if you wish to know if for instance the type is long, you compare with type(0l), etc.
A:
If you know that you are expecting an integer/string argument, you shouldn't swallow it into *args. Do
def handle( self, first_arg = None, *args, **kwargs ):
if isinstance( first_arg, int ):
thing_one()
elif isinstance( first_arg, str ):
thing_two()
A:
No one has mentioned it, but the Easier to Ask For Forgiveness principle probably applies since I presume you'll be doing something with that integer:
def handle(self, *args, **kwargs):
try:
#Do some integer thing
except TypeError:
#Do some string thing
Of course if that integer thing is modifying the values in your list, maybe you should check first. Of course if you want to loop through args and do something for integers and something else for strings:
def handle(self, *args, **kwargs):
for arg in args:
try:
#Do some integer thing
except TypeError:
#Do some string thing
Of course this is also assuming that no other operation in the try will throw a TypeError.
| How to check type of variable? Python | I need to do one thing if args is integer and ather thing if args is string.
How can i chack type? Example:
def handle(self, *args, **options):
if not args:
do_something()
elif args is integer:
do_some_ather_thing:
elif args is string:
do_totally_different_thing()
| [
"First of, *args is always a list. You want to check if its content are strings?\nimport types\ndef handle(self, *args, **options):\n if not args:\n do_something()\n # check if everything in args is a Int\n elif all( isinstance(s, types.IntType) for s in args):\n do_some_ather_thing()\n # as... | [
13,
1,
0,
0,
0
] | [] | [] | [
"python",
"variables"
] | stackoverflow_0003440969_python_variables.txt |
Q:
Sqlite. How to get value of Auto Increment Primary Key after Insert, other than last_insert_rowid()?
I am using Sqlite3 with Flask microframework, but this question concerns only the Sqlite side of things..
Here is a snippet of the code:
g.db.execute('INSERT INTO downloads (name, owner, mimetype) VALUES (?, ?, ?)', [name, owner, mimetype])
file_entry = query_db('SELECT last_insert_rowid()')
g.db.commit()
The downloads table has another column with the following attributes: id integer primary key autoincrement,
If two people write at the same time the code above could produce errors.
Transactions can be messy. In Sqlite is there a neat built in way of returning the primary key generated after doing an INSERT ?
A:
The way you're doing it is valid. There won't be a problem if the above snipped is executed concurrently by two scripts. last_insert_rowid() returns the rowid of the latest INSERT statement for the connection that calls it. You can also get the rowid by doing g.db.lastrowid.
| Sqlite. How to get value of Auto Increment Primary Key after Insert, other than last_insert_rowid()? | I am using Sqlite3 with Flask microframework, but this question concerns only the Sqlite side of things..
Here is a snippet of the code:
g.db.execute('INSERT INTO downloads (name, owner, mimetype) VALUES (?, ?, ?)', [name, owner, mimetype])
file_entry = query_db('SELECT last_insert_rowid()')
g.db.commit()
The downloads table has another column with the following attributes: id integer primary key autoincrement,
If two people write at the same time the code above could produce errors.
Transactions can be messy. In Sqlite is there a neat built in way of returning the primary key generated after doing an INSERT ?
| [
"The way you're doing it is valid. There won't be a problem if the above snipped is executed concurrently by two scripts. last_insert_rowid() returns the rowid of the latest INSERT statement for the connection that calls it. You can also get the rowid by doing g.db.lastrowid.\n"
] | [
39
] | [] | [] | [
"flask",
"python",
"sqlite"
] | stackoverflow_0003442033_flask_python_sqlite.txt |
Q:
What is the proper way to do an INSERT query in Python MySQL?
I have a python script that connects to a local MySQL db. I know it is connecting correctly because I can do this and get the proper results:
cursor.execute("SELECT * FROM reel")
But when I try to do any insert statements it just does nothing. No error messages, no exceptions. Nothing shows up in the database when I check it from sqlyog. This is what my code looks like:
self.cursor.executemany("INSERT INTO reel (etime,etext) VALUES (%s,%s)", tups)
where tups is a list of tuples looking like this ('0000-00-00 00:00:00','text'). No errors show up and if I copy paste the generated SQL query into sqlyog it works. I've tried generating the query and doing cursor.execute() on it and no errors and no result either. Anyone know what I'm doing wrong?
A:
You need to do a self.cursor.commit() after self.cursor.executemany("INSERT INTO reel (etime,etext) VALUES (%s,%s)", tups)
Starting with 1.2.0, MySQLdb disables autocommit by default, as required by the DB-API standard (PEP-249). If you are using InnoDB tables or some other type of transactional table type, you'll need to do connection.commit() before closing the connection, or else none of your changes will be written to the database.
Conversely, you can also use connection.rollback() to throw away any changes you've made since the last commit.
Important note: Some SQL statements -- specifically DDL statements like CREATE TABLE -- are non-transactional, so they can't be rolled back, and they cause pending transactions to commit.
Is a FAQ
| What is the proper way to do an INSERT query in Python MySQL? | I have a python script that connects to a local MySQL db. I know it is connecting correctly because I can do this and get the proper results:
cursor.execute("SELECT * FROM reel")
But when I try to do any insert statements it just does nothing. No error messages, no exceptions. Nothing shows up in the database when I check it from sqlyog. This is what my code looks like:
self.cursor.executemany("INSERT INTO reel (etime,etext) VALUES (%s,%s)", tups)
where tups is a list of tuples looking like this ('0000-00-00 00:00:00','text'). No errors show up and if I copy paste the generated SQL query into sqlyog it works. I've tried generating the query and doing cursor.execute() on it and no errors and no result either. Anyone know what I'm doing wrong?
| [
"You need to do a self.cursor.commit() after self.cursor.executemany(\"INSERT INTO reel (etime,etext) VALUES (%s,%s)\", tups)\nStarting with 1.2.0, MySQLdb disables autocommit by default, as required by the DB-API standard (PEP-249). If you are using InnoDB tables or some other type of transactional table type, you... | [
6
] | [] | [] | [
"mysql",
"python"
] | stackoverflow_0003442307_mysql_python.txt |
Q:
What characters in key_name?
I wonder what you can use as a key_name?
I do a lot of queries on non-ascii unicode characters, I wonder if I can use these as key names to speed up the queries.
Thanks!
A:
Per the documentation, key_name is a unicode string, though plain str values get converted as ASCII -- so you'll want to make sure you're actually providing a true unicode string (I strongly suggest reading the entire Python Unicode HOWTO).
| What characters in key_name? | I wonder what you can use as a key_name?
I do a lot of queries on non-ascii unicode characters, I wonder if I can use these as key names to speed up the queries.
Thanks!
| [
"Per the documentation, key_name is a unicode string, though plain str values get converted as ASCII -- so you'll want to make sure you're actually providing a true unicode string (I strongly suggest reading the entire Python Unicode HOWTO).\n"
] | [
5
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0003442312_google_app_engine_python.txt |
Q:
How do I make Tkinter support PNG transparency?
I put in a partially transparent PNG image in Tkinter and all I get is this
How do I make the dark triangle on the right clear? (like it's supposed to be)
This is python 2.6 on Windows 7, btw.
A:
Here's an example (the PNG file example.png has lots of transparency in different places):
from Tkinter import Tk, Frame, Canvas
import ImageTk
t = Tk()
t.title("Transparency")
frame = Frame(t)
frame.pack()
canvas = Canvas(frame, bg="black", width=500, height=500)
canvas.pack()
photoimage = ImageTk.PhotoImage(file="example.png")
canvas.create_image(150, 150, image=photoimage)
t.mainloop()
You need to make sure the image has been stored as "RGBA" which is RGB with an alpha channel. You can check for that using a graphics program of your choice, or using PIL (Python Imaging Library):
import Image
im = Image.open("button.png")
print im.mode
This should print "RGBA". If not, you'll have to make sure the alpha channel is saved with the image. You'll have to consult your graphics program manual for how to do that.
| How do I make Tkinter support PNG transparency? | I put in a partially transparent PNG image in Tkinter and all I get is this
How do I make the dark triangle on the right clear? (like it's supposed to be)
This is python 2.6 on Windows 7, btw.
| [
"Here's an example (the PNG file example.png has lots of transparency in different places):\nfrom Tkinter import Tk, Frame, Canvas\nimport ImageTk\n\nt = Tk()\nt.title(\"Transparency\")\n\nframe = Frame(t)\nframe.pack()\n\ncanvas = Canvas(frame, bg=\"black\", width=500, height=500)\ncanvas.pack()\n\nphotoimage = Im... | [
25
] | [] | [] | [
"png",
"python",
"tkinter",
"transparency"
] | stackoverflow_0003270209_png_python_tkinter_transparency.txt |
Q:
django cleaned_data [help]
ok so I have the following problem i`ve looked around but I cant find a solution ...
lets say I have the following forms.py
from django import forms
class LoginForm(forms.Form):
_username = forms.CharField()
_password = forms.CharField()
and in views.py I have
def index(request):
if request.method == 'POST':
form = LoginForm(request.POST)
else:
form = LoginForm()
if form.is_valid:
username = form.cleaned_data['_username']
password = form.cleaned_data['_password']
if check_credential(username, password):
request.session['_username'] = username
request.session['_password'] = password
I`m using
void@void:~$ django-admin --version
1.1.1
I`m using djangobook to learn django they used an old ver of django that had clean_data ...ive tryed using
from django import newforms as forms
but the result was the same ...
'LoginForm' object has no attribute 'cleaned_data'
A:
form.is_valid is a function. Use it as
if form.is_valid():
# actions
Only after is_valid() internally had called each field's own clean method, the form has dict named cleaned_data.
| django cleaned_data [help] | ok so I have the following problem i`ve looked around but I cant find a solution ...
lets say I have the following forms.py
from django import forms
class LoginForm(forms.Form):
_username = forms.CharField()
_password = forms.CharField()
and in views.py I have
def index(request):
if request.method == 'POST':
form = LoginForm(request.POST)
else:
form = LoginForm()
if form.is_valid:
username = form.cleaned_data['_username']
password = form.cleaned_data['_password']
if check_credential(username, password):
request.session['_username'] = username
request.session['_password'] = password
I`m using
void@void:~$ django-admin --version
1.1.1
I`m using djangobook to learn django they used an old ver of django that had clean_data ...ive tryed using
from django import newforms as forms
but the result was the same ...
'LoginForm' object has no attribute 'cleaned_data'
| [
"form.is_valid is a function. Use it as \nif form.is_valid():\n # actions\n\nOnly after is_valid() internally had called each field's own clean method, the form has dict named cleaned_data.\n"
] | [
7
] | [] | [] | [
"django",
"forms",
"python"
] | stackoverflow_0003442376_django_forms_python.txt |
Q:
Can 2 objects have the same key name?
I wonder if 2 objects can have the same key name?
They wouldn't be the same class.
Thanks!
A:
Yes.
An entity is uniquely identified by its path, which is the kind & name or ID of the entity and all of its ancestors. If two entities have the same name, but different kinds and/or ancestries, they will have distinct paths.
| Can 2 objects have the same key name? | I wonder if 2 objects can have the same key name?
They wouldn't be the same class.
Thanks!
| [
"Yes.\nAn entity is uniquely identified by its path, which is the kind & name or ID of the entity and all of its ancestors. If two entities have the same name, but different kinds and/or ancestries, they will have distinct paths.\n"
] | [
4
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0003442477_google_app_engine_python.txt |
Q:
Serving secure Django pages with HTTPS
What is the proper deployment configuration for a Django application that needs some pages served with HTTPS and others with HTTP?
I want to use HTTPS for the pages that involve registration and inputting passwords. I want to use HTTP for all other pages.
A:
There's no single approach as far as I know. You can use a decorator secure_required as developed in this post by Scott Barnham:
Securing Django with SSL
or use middleware:
SSLMidleware
If you're looking for deployment information with respect to Apache and mod_wsgi, then Graham Dumpleton provides a nice answer in this question:
How to force the use of SSL for some URL of my Django Application ?
| Serving secure Django pages with HTTPS | What is the proper deployment configuration for a Django application that needs some pages served with HTTPS and others with HTTP?
I want to use HTTPS for the pages that involve registration and inputting passwords. I want to use HTTP for all other pages.
| [
"There's no single approach as far as I know. You can use a decorator secure_required as developed in this post by Scott Barnham:\n\nSecuring Django with SSL\n\nor use middleware:\n\nSSLMidleware\n\nIf you're looking for deployment information with respect to Apache and mod_wsgi, then Graham Dumpleton provides a n... | [
6
] | [] | [] | [
"deployment",
"django",
"https",
"python"
] | stackoverflow_0003442448_deployment_django_https_python.txt |
Q:
WSGI content encoding
If I execute the following Python 3.1 program, I see only � instead of the correct characters in my browser. The file itself is UTF-8 encoded and the same encoding is sent with the response.
from wsgiref.simple_server import make_server
page = "<html><body>äöü€ßÄÖÜ</body></html>"
def application(environ, start_response):
start_response("200 Ok", [("Content-Type", "text/html; charset=UTF-8")])
return page
httpd = make_server('', 8000, application)
print("Serving on port 8000...")
httpd.serve_forever()
"UTF-8" is set correctly in the response:
HTTP/1.0 200 Ok
Date: Mon, 09 Aug 2010 16:35:02 GMT
Server: WSGIServer/0.1 Python/3.1.1+
Content-Type: text/html; charset=UTF-8
What is wrong here?
A:
WSGI on Python 3 doesn't exist yet. The Web-SIG have still not reached any conclusion about how strings (bytes/unicode) are to be handled in Python 3.x.
wsgiref is largely an automated 2to3 conversion; it still has problems even apart from the factor of what WSGI on 3.x will actually mean. Don't rely on it as a reference to how WSGI apps will work under Python 3.
That the situation is still like this coming into the 3.2 release cycle is embarrassing and depressing.
return page
Well, whilst WSGI for 3.x is still an unknown factor, one thing most agree on is that the response body of a WSGI app should generally be bytes and not unicode, since HTTP is a bytes-based protocol. Whether Unicode strings will be accepted—and if so what encoding they'll be converted with—remains to be seen, so avoid the issue and return bytes:
return [page.encode('utf-8')]
(The [] are needed because WSGI apps should return an iterable that's output and flushed an item at a time. If you pass a string on its own, that's used as an iterable and returned a character at a time, which is horrible for performance.)
A:
Those characters are not UTF-8; they are latin-1. If you put those literals into your Python source code (which you shouldn't do), you need to declare the encoding of the file, by placing the following line at the top:
#-*- coding: latin-1 -*-
and serving in latin-1:
start_response("200 Ok", [("Content-Type", "text/html; charset=latin-1")])
Assuming you meant to do everything in UTF-8, you need to look up the code points for those characters. You can then do
page = u"\x--\x--...\x--"
and serve that up as Unicode.
Note that you can verify this by changing the encoding of your browser; if you manually change it to latin-1 the characters will display fine.
| WSGI content encoding | If I execute the following Python 3.1 program, I see only � instead of the correct characters in my browser. The file itself is UTF-8 encoded and the same encoding is sent with the response.
from wsgiref.simple_server import make_server
page = "<html><body>äöü€ßÄÖÜ</body></html>"
def application(environ, start_response):
start_response("200 Ok", [("Content-Type", "text/html; charset=UTF-8")])
return page
httpd = make_server('', 8000, application)
print("Serving on port 8000...")
httpd.serve_forever()
"UTF-8" is set correctly in the response:
HTTP/1.0 200 Ok
Date: Mon, 09 Aug 2010 16:35:02 GMT
Server: WSGIServer/0.1 Python/3.1.1+
Content-Type: text/html; charset=UTF-8
What is wrong here?
| [
"WSGI on Python 3 doesn't exist yet. The Web-SIG have still not reached any conclusion about how strings (bytes/unicode) are to be handled in Python 3.x.\nwsgiref is largely an automated 2to3 conversion; it still has problems even apart from the factor of what WSGI on 3.x will actually mean. Don't rely on it as a r... | [
8,
0
] | [] | [] | [
"character_encoding",
"content_type",
"http",
"python",
"utf_8"
] | stackoverflow_0003442229_character_encoding_content_type_http_python_utf_8.txt |
Q:
wxPython: Highlight item in GidSizer upon mouse click
I have a Panel with a bunch of pictures placed on it in a GridSizer layout. How can I draw a highlighted color around the edge of an image or its border to show that it has been selected upon a mouse click event?
A:
Take a look at the Widget Inspection Tool's code. It can highlight any widget. On my machine, it's in the "_InspectionHighlighter" class in the inspection.py file, which is here: C:\Python25\Lib\site-packages\wx-2.8-msw-unicode\wx\lib
You can read about the tool here: http://wiki.wxpython.org/Widget%20Inspection%20Tool
A:
You could put each picture in a panel, and use SetBackgroundColour()to set the background color of the panel.
| wxPython: Highlight item in GidSizer upon mouse click | I have a Panel with a bunch of pictures placed on it in a GridSizer layout. How can I draw a highlighted color around the edge of an image or its border to show that it has been selected upon a mouse click event?
| [
"Take a look at the Widget Inspection Tool's code. It can highlight any widget. On my machine, it's in the \"_InspectionHighlighter\" class in the inspection.py file, which is here: C:\\Python25\\Lib\\site-packages\\wx-2.8-msw-unicode\\wx\\lib\nYou can read about the tool here: http://wiki.wxpython.org/Widget%20Ins... | [
1,
0
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0003431154_python_wxpython.txt |
Q:
How to catch an OperationFailure from MongoDB and PyMongo in Python
I have been having a problem where after my mongodb connection to mongohq via pymongo goes idle for awhile (no queries), it will timeout. This is fine, but the connection the database is only created when the Django app is started up. It seems like it is reconnecting fine, but it needs to reauthenticate then. When the connection has died and reconnected, and a query tries to run, it raises an OperationFailure and the following exception value database error: unauthorized for db [shanereustle] lock type: -1 which tells me it is reconnecting, but not authenticating. I have imported OperationFailure from pymongo.errors and have been trying to use the following try...except but I can't seem to catch the error, and authenticate.
try:
db.mongohq.shanereustle.blog.find()
except OperationFailure:
db.authenticate() #this function reauthenticates the existing connection
But for some reason this does not catch. If instead of this code, I simply run db.authenticate() before the query, it will reauthenticate just fine and go fine, but I don't want to reauthenticate on every query. Other suggestions on proper ways to do this are very welcome and I appreciate the help.
Thanks!
A:
Can you try a find_one() instead of find(). The latter doesn't iterate over the cursor automatically.
I just tried this with an --auth database, and it worked:
try:
connection.test.foo.find_one()
except pymongo.errors.OperationFailure:
print "caught"
| How to catch an OperationFailure from MongoDB and PyMongo in Python | I have been having a problem where after my mongodb connection to mongohq via pymongo goes idle for awhile (no queries), it will timeout. This is fine, but the connection the database is only created when the Django app is started up. It seems like it is reconnecting fine, but it needs to reauthenticate then. When the connection has died and reconnected, and a query tries to run, it raises an OperationFailure and the following exception value database error: unauthorized for db [shanereustle] lock type: -1 which tells me it is reconnecting, but not authenticating. I have imported OperationFailure from pymongo.errors and have been trying to use the following try...except but I can't seem to catch the error, and authenticate.
try:
db.mongohq.shanereustle.blog.find()
except OperationFailure:
db.authenticate() #this function reauthenticates the existing connection
But for some reason this does not catch. If instead of this code, I simply run db.authenticate() before the query, it will reauthenticate just fine and go fine, but I don't want to reauthenticate on every query. Other suggestions on proper ways to do this are very welcome and I appreciate the help.
Thanks!
| [
"Can you try a find_one() instead of find(). The latter doesn't iterate over the cursor automatically.\nI just tried this with an --auth database, and it worked:\ntry:\n connection.test.foo.find_one()\nexcept pymongo.errors.OperationFailure:\n print \"caught\"\n\n"
] | [
7
] | [] | [] | [
"django",
"mongodb",
"pymongo",
"python"
] | stackoverflow_0003442267_django_mongodb_pymongo_python.txt |
Q:
How to package a python program
Im new to python programming.Im writing a simple command line based twitter app,and i have to use external libraries like simplejson,tweepy etc.
Is there a way i can package my python program to include these libraries as well,so that when i distribute this program, the user doesnt have to install the required libraries first himself ?
Thank You
A:
Python will search for modules in the current directory, so you can just package the libraries along in a subdirectory. For example, if myprogram.py use the foo package:
import foo
this means that there's either
a foo.py on your Python path; put it into the same directory as myprogram.py, or
a directory foo on your Python path which contains a module __init__.py; put the entire directory (.py files only, no need for .pyc files) into the same directory as myprogram.py.
Of course, have a look at the licenses first to check whether they allow redistribution with your program in this manner.
| How to package a python program | Im new to python programming.Im writing a simple command line based twitter app,and i have to use external libraries like simplejson,tweepy etc.
Is there a way i can package my python program to include these libraries as well,so that when i distribute this program, the user doesnt have to install the required libraries first himself ?
Thank You
| [
"Python will search for modules in the current directory, so you can just package the libraries along in a subdirectory. For example, if myprogram.py use the foo package:\nimport foo\n\nthis means that there's either\n\na foo.py on your Python path; put it into the same directory as myprogram.py, or\na directory fo... | [
4
] | [] | [] | [
"python"
] | stackoverflow_0003442886_python.txt |
Q:
When using soappy SOAPServer, how do I read the request's headers?
I've got a Python webservice using SOAPpy. The webservice server is structured as shown below:
class myClass:
def hello():
return 'world'
if __name__ == "__main__":
server = SOAPServer( ( 'localhost', 8888 ) )
myObject = myClass()
namespace = 'whatever::namespace'
server.registerObject( myObject, namespace )
server.serve_forever()
If a client calls the hello() method from my webservice, how can I read the headers, so I can start logging some information (for example: ip address) for debugging?
A:
Do you want to do the logging in your hello method? Here's a minimal example that shows how to pass the SOAPContext information (which can give you some of this info) into the function/method call:
from SOAPpy import *
def hello(_SOAPContext = None):
return "Your IP address is %s" % _SOAPContext.connection.getpeername()[0]
if __name__ == "__main__":
server = SOAPServer( ( '10.3.40.104', 8080 ) )
server.registerFunction( MethodSig(hello, keywords=0, context=1) )
server.serve_forever()
A:
you can add a RequestHandler to the SoapServer object that extends the SOAPRequestHandler and replaces the HeaderHandler (have a look at the source of server.py for an example)
| When using soappy SOAPServer, how do I read the request's headers? | I've got a Python webservice using SOAPpy. The webservice server is structured as shown below:
class myClass:
def hello():
return 'world'
if __name__ == "__main__":
server = SOAPServer( ( 'localhost', 8888 ) )
myObject = myClass()
namespace = 'whatever::namespace'
server.registerObject( myObject, namespace )
server.serve_forever()
If a client calls the hello() method from my webservice, how can I read the headers, so I can start logging some information (for example: ip address) for debugging?
| [
"Do you want to do the logging in your hello method? Here's a minimal example that shows how to pass the SOAPContext information (which can give you some of this info) into the function/method call:\nfrom SOAPpy import *\n\ndef hello(_SOAPContext = None):\n return \"Your IP address is %s\" % _SOAPContext.connec... | [
2,
1
] | [] | [] | [
"python",
"soap",
"soappy",
"web_services"
] | stackoverflow_0003442276_python_soap_soappy_web_services.txt |
Q:
Python - Reportlab: Error using custom font
Im using the reportlab framework for creating pdf's. I'm also using a custom font in my pdf's called '3of9'. Now, sometimes I'm getting the following error:
IOError: Cannot open resource "/usr/lib/python2.6/site-packages/reportlab/fonts/LeERC___.AFM", while looking for faceName='3of9'
This doesn't happens everytime, but too often. And in most of the cases everything works well, so I have no idea why the error comes up.
Has anyone an idea how to solve this?
A:
either make sure you have LeERC___.AFM at the given path or try to upgrade to a more recent reportlab version.
LeERC___.AFM is part of the reportlab distribution to version 2.1 (which can be downloaded at
http://www.reportlab.com/ftp/ReportLab_2_1.zip)
| Python - Reportlab: Error using custom font | Im using the reportlab framework for creating pdf's. I'm also using a custom font in my pdf's called '3of9'. Now, sometimes I'm getting the following error:
IOError: Cannot open resource "/usr/lib/python2.6/site-packages/reportlab/fonts/LeERC___.AFM", while looking for faceName='3of9'
This doesn't happens everytime, but too often. And in most of the cases everything works well, so I have no idea why the error comes up.
Has anyone an idea how to solve this?
| [
"either make sure you have LeERC___.AFM at the given path or try to upgrade to a more recent reportlab version. \nLeERC___.AFM is part of the reportlab distribution to version 2.1 (which can be downloaded at \nhttp://www.reportlab.com/ftp/ReportLab_2_1.zip)\n"
] | [
1
] | [] | [] | [
"pdf",
"python",
"reportlab"
] | stackoverflow_0003139617_pdf_python_reportlab.txt |
Q:
How do I step through/debug a python web application?
I can't seem to find any information on debugging a python web application, specifically stepping through the execution of a web request.
is this just not possible? if no, why not?
A:
If you put
import pdb
pdb.set_trace()
in your code, the web app will drop to a pdb debugger session upon executing set_trace.
Also useful, is
import code
code.interact(local=locals())
which drops you to the python interpreter. Pressing Ctrl-d resumes execution.
Still more useful, is
import IPython.Shell
ipshell = IPython.Shell.IPShellEmbed()
ipshell(local_ns=locals())
which drops you into an IPython session (assuming you've installed IPython). Here too, pressing Ctrl-d resumes execution.
A:
If you are running your web application through apache and mod_wsgi or mod_python, both provide some support for step through debugging with pdb. The trick is you have to run apache in foreground mode with the -X flag.
On my Gentoo system I do this with (this is essentially the same command the apache init script uses replacing the -k start with the -X):
/usr/sbin/apache2 -D DEFAULT_VHOST -D INFO -D LANGUAGE -D SSL -D SSL_DEFAULT_VHOST -D PYTHON -d /usr/lib64/apache2 -f /etc/apache2/httpd.conf -X
A:
use Python Debbuger, import pdb; pdb.set_trace() exactly where you want to start debugging, and your terminal will pause in that line.
More info here:
http://plone.org/documentation/kb/using-pdb
| How do I step through/debug a python web application? | I can't seem to find any information on debugging a python web application, specifically stepping through the execution of a web request.
is this just not possible? if no, why not?
| [
"If you put\nimport pdb\npdb.set_trace()\n\nin your code, the web app will drop to a pdb debugger session upon executing set_trace. \nAlso useful, is \nimport code\ncode.interact(local=locals())\n\nwhich drops you to the python interpreter. Pressing Ctrl-d resumes execution.\nStill more useful, is \nimport IPython.... | [
11,
3,
0
] | [] | [] | [
"debugging",
"python",
"step_into"
] | stackoverflow_0003442920_debugging_python_step_into.txt |
Q:
Cross-platform subprocess with hidden window
I want to open a process in the background and interact with it, but this process should be invisible in both Linux and Windows. In Windows you have to do some stuff with STARTUPINFO, while this isn't valid in Linux:
ValueError: startupinfo is only supported on Windows platforms
Is there a simpler way than creating a separate Popen command for each OS?
if os.name == 'nt':
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
proc = subprocess.Popen(command, startupinfo=startupinfo)
if os.name == 'posix':
proc = subprocess.Popen(command)
A:
You can reduce one line :)
startupinfo = None
if os.name == 'nt':
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
proc = subprocess.Popen(command, startupinfo=startupinfo)
A:
Just a note: for Python 2.7 I have to use subprocess._subprocess.STARTF_USESHOWWINDOW instead of subprocess.STARTF_USESHOWWINDOW.
A:
I'm not sure you can get much simpler than what you've done. You're talking about optimising out maybe 5 lines of code. For the money I would just get on with my project and accept this as a consquence of cross-platform development. If you do it a lot then create a specialised class or function to encapsulate the logic and import it.
A:
You can turn your code into:
params = dict()
if os.name == 'nt':
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
params['startupinfo'] = startupinfo
proc = subprocess.Popen(command, **params)
but that's not much better.
| Cross-platform subprocess with hidden window | I want to open a process in the background and interact with it, but this process should be invisible in both Linux and Windows. In Windows you have to do some stuff with STARTUPINFO, while this isn't valid in Linux:
ValueError: startupinfo is only supported on Windows platforms
Is there a simpler way than creating a separate Popen command for each OS?
if os.name == 'nt':
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
proc = subprocess.Popen(command, startupinfo=startupinfo)
if os.name == 'posix':
proc = subprocess.Popen(command)
| [
"You can reduce one line :)\nstartupinfo = None\nif os.name == 'nt':\n startupinfo = subprocess.STARTUPINFO()\n startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW\nproc = subprocess.Popen(command, startupinfo=startupinfo)\n\n",
"Just a note: for Python 2.7 I have to use subprocess._subprocess.STARTF_US... | [
40,
12,
4,
1
] | [] | [] | [
"cross_platform",
"linux",
"python",
"subprocess",
"windows"
] | stackoverflow_0001016384_cross_platform_linux_python_subprocess_windows.txt |
Q:
Shifting thinking from CakePHP to Django - a monolithic views file?
I'm trying to get started with Django, and have previously worked with CakePHP, and so my MVC background comes out of that. I'm aware of Django's slightly different MTV architecture, and am fine with the monolithic model files - multiple classes in one file I can handle just fine.
But I'm confused about how to do the views (which are roughly analagous to controllers in MVC, correct?). The examples I've seen just have one views.py that has methods like index(), view(), etc. But if I have a bunch of users that create and own widgets that they can share, for example, I want to have /users/view that runs view() for the users model, and /widgets/view that runs view() for the widgets model.
I don't see any way to separate those out, and don't know what the correct/conventional/right way is to do so. I may just be having trouble wrapping my head around Django's way of doing things, too. Should I have methods in view.py that are user_view and widget_view? That seems very clunky.
Or should I have user_view.py or even user/view.py that contains index() and view()? Could I reference those from the URL routing? How are things generally done with Django and this kind of thing?
This may ultimately be related to (or even solved by) this answer, but I'm asking more as a question of what convention and the right way to think about such things is.
Additionally, shouldn't the docs/examples be clearer on this? I've been impressed by the docs thus far, but I'm pretty sure most web apps will deal with more than one "object," and it seems to me that this would come up pretty often.
A:
Python view files are just Python modules. The views themselves are just functions that can live anywhere you like - the module doesn't even have to be called views.py. The urlconf (in urls.py) can refer to views anywhere at all.
One obvious way of separating things out is into separate applications, which is covered well in the documentation - you can also have separate urls.py files for each app and use include in the main site-level urls.py to include all the sub-files.
But there's nothing to stop you sub-dividing the views in a single app into multiple files - eg by creating a views module, containing a (blank) __init__.py and as many other view files as you like.
Or, if you really do have views associated only with a particular model - and you'd be surprised how seldom that is the case - again, you could make your views classmethods on the model class itself. All a view has to do is to accept a request, and any other parameters, and return a response.
| Shifting thinking from CakePHP to Django - a monolithic views file? | I'm trying to get started with Django, and have previously worked with CakePHP, and so my MVC background comes out of that. I'm aware of Django's slightly different MTV architecture, and am fine with the monolithic model files - multiple classes in one file I can handle just fine.
But I'm confused about how to do the views (which are roughly analagous to controllers in MVC, correct?). The examples I've seen just have one views.py that has methods like index(), view(), etc. But if I have a bunch of users that create and own widgets that they can share, for example, I want to have /users/view that runs view() for the users model, and /widgets/view that runs view() for the widgets model.
I don't see any way to separate those out, and don't know what the correct/conventional/right way is to do so. I may just be having trouble wrapping my head around Django's way of doing things, too. Should I have methods in view.py that are user_view and widget_view? That seems very clunky.
Or should I have user_view.py or even user/view.py that contains index() and view()? Could I reference those from the URL routing? How are things generally done with Django and this kind of thing?
This may ultimately be related to (or even solved by) this answer, but I'm asking more as a question of what convention and the right way to think about such things is.
Additionally, shouldn't the docs/examples be clearer on this? I've been impressed by the docs thus far, but I'm pretty sure most web apps will deal with more than one "object," and it seems to me that this would come up pretty often.
| [
"Python view files are just Python modules. The views themselves are just functions that can live anywhere you like - the module doesn't even have to be called views.py. The urlconf (in urls.py) can refer to views anywhere at all.\nOne obvious way of separating things out is into separate applications, which is cov... | [
6
] | [] | [] | [
"django",
"django_views",
"model_view_controller",
"python"
] | stackoverflow_0003443157_django_django_views_model_view_controller_python.txt |
Q:
How can I do dynamic class generation in Python? (or would a series of if/elses be better)
So, I'm writing something and I've come into a roadblock on how to do it (and what is the proper way of doing things). SO, explaining the situation will help be better understand the problem, and hopefully someone will know the answer :) Here it goes:
Basically, I'm writing up some dynamic forms in Python (more specifically Django) - I am using a form factory to generate the form that I want to make. This is all fine and dandy, so far I have been defining the properties of the form in a hardcoded way, basically matching a property to a certain form (a ChoiceField, a Boolean, etc). BUT, what I would like instead of hardcoding these values is essentially create a properties dictionary dynamically, based on what information I pass it...
I basically have an array of "options", and so here are the two methods I am considering:
Have a function for my "options" model/object that will have a series of if/elses. Like:
def get_property():
if value = "artifact": #artifact being one option
return form.BooleanField(label="blah")
else if value = "environment": #environment being another type of option
return form.ChoicesField(label="blah")
etc...
Use a very polymorphic approach. In this way, I mean creating an object based on my "option" object, and will create a new object based on the option. Say maybe something like:
class Base_Property():
value = ""
def __init__(self, option):
value = form.BooleanField()
class Artifact_Property(Base_Property):
def __init__(self, option):
Base_Property.__init__(self, option)
value = form.ChoiceField(choices=some_choices_array())
If option two is the way to go, could someone explain how I can create an object dynamically based on a variable? Like, matching the name of the value (say, Artifact, to match Artifact_Property).
Thanks so much for the help! I am really interested to see what happens to be a proper way - maybe it will spark a debate :)
-Shawn
A:
Have you considered using a dictionary? They're excellent for this sort of conditional.
def get_option(field_type):
options = {
'artifact': forms.BooleanField,
'environment': forms.Choice Field,
}
return options[field_type](label='blah')
| How can I do dynamic class generation in Python? (or would a series of if/elses be better) | So, I'm writing something and I've come into a roadblock on how to do it (and what is the proper way of doing things). SO, explaining the situation will help be better understand the problem, and hopefully someone will know the answer :) Here it goes:
Basically, I'm writing up some dynamic forms in Python (more specifically Django) - I am using a form factory to generate the form that I want to make. This is all fine and dandy, so far I have been defining the properties of the form in a hardcoded way, basically matching a property to a certain form (a ChoiceField, a Boolean, etc). BUT, what I would like instead of hardcoding these values is essentially create a properties dictionary dynamically, based on what information I pass it...
I basically have an array of "options", and so here are the two methods I am considering:
Have a function for my "options" model/object that will have a series of if/elses. Like:
def get_property():
if value = "artifact": #artifact being one option
return form.BooleanField(label="blah")
else if value = "environment": #environment being another type of option
return form.ChoicesField(label="blah")
etc...
Use a very polymorphic approach. In this way, I mean creating an object based on my "option" object, and will create a new object based on the option. Say maybe something like:
class Base_Property():
value = ""
def __init__(self, option):
value = form.BooleanField()
class Artifact_Property(Base_Property):
def __init__(self, option):
Base_Property.__init__(self, option)
value = form.ChoiceField(choices=some_choices_array())
If option two is the way to go, could someone explain how I can create an object dynamically based on a variable? Like, matching the name of the value (say, Artifact, to match Artifact_Property).
Thanks so much for the help! I am really interested to see what happens to be a proper way - maybe it will spark a debate :)
-Shawn
| [
"Have you considered using a dictionary? They're excellent for this sort of conditional.\ndef get_option(field_type):\n options = {\n 'artifact': forms.BooleanField,\n 'environment': forms.Choice Field,\n }\n\nreturn options[field_type](label='blah')\n\n"
] | [
5
] | [] | [] | [
"django",
"forms",
"inheritance",
"oop",
"python"
] | stackoverflow_0003443078_django_forms_inheritance_oop_python.txt |
Q:
Django Piston Content Type Always Null
I had django-piston working a week ago but recently I'm unable to call any web services. Below is a simple example. I have a 'test' service that returns 'yes' if there is a content type and 'no' if content type is null. I've done this because I get HTTP 500 errors when I do a POST and try to parse my parameters via 'data = request.data'. I'm assuming I can't do request.data because the content type is null?
So, here is my simple web service:
class testHandler(BaseHandler):
def create(self, request):
if request.content_type:
return 'yes'
else:
data = request.data
return 'no'
And here is the urls.py file:
class CsrfExemptResource( Resource ):
def __init__( self, handler, authentication = None ):
super( CsrfExemptResource, self ).__init__( handler, authentication )
self.csrf_exempt = getattr( self.handler, 'csrf_exempt', True )
controller_handler = CsrfExemptResource(controllerHandler)
test_handler = CsrfExemptResource(testHandler)
urlpatterns = patterns('',
url(r'^controller/', controller_handler),
url(r'^test/', test_handler),
)
And finally the code I run from my python terminal to call the service:
params = urllib.urlencode({'value':'someValue'})
req = urllib2.Request("http://127.0.0.1/cindy/api/test/", params)
result = urllib2.urlopen(req).read()
So 'result' always return no, and if I put the line 'request.data' in the service I get a HTTP 500 error.
Thanks in advance.
A:
I don't think there is a data attribute in the HttpRequest object. You might be looking for raw_post_data.
| Django Piston Content Type Always Null | I had django-piston working a week ago but recently I'm unable to call any web services. Below is a simple example. I have a 'test' service that returns 'yes' if there is a content type and 'no' if content type is null. I've done this because I get HTTP 500 errors when I do a POST and try to parse my parameters via 'data = request.data'. I'm assuming I can't do request.data because the content type is null?
So, here is my simple web service:
class testHandler(BaseHandler):
def create(self, request):
if request.content_type:
return 'yes'
else:
data = request.data
return 'no'
And here is the urls.py file:
class CsrfExemptResource( Resource ):
def __init__( self, handler, authentication = None ):
super( CsrfExemptResource, self ).__init__( handler, authentication )
self.csrf_exempt = getattr( self.handler, 'csrf_exempt', True )
controller_handler = CsrfExemptResource(controllerHandler)
test_handler = CsrfExemptResource(testHandler)
urlpatterns = patterns('',
url(r'^controller/', controller_handler),
url(r'^test/', test_handler),
)
And finally the code I run from my python terminal to call the service:
params = urllib.urlencode({'value':'someValue'})
req = urllib2.Request("http://127.0.0.1/cindy/api/test/", params)
result = urllib2.urlopen(req).read()
So 'result' always return no, and if I put the line 'request.data' in the service I get a HTTP 500 error.
Thanks in advance.
| [
"I don't think there is a data attribute in the HttpRequest object. You might be looking for raw_post_data.\n"
] | [
0
] | [] | [] | [
"django",
"django_piston",
"python"
] | stackoverflow_0003443313_django_django_piston_python.txt |
Q:
Issue with passing paramters to a class method in Python
I have been playing with Python for the past week and I running into a problem with passing 4 parameters to a class method.
Here is the class method defined within it's class:
class Line:
locx0 = 0
locy0 = 0
locx1 = 0
locy1 = 0
def __init__(self):
print'<<Line __init__()>>'
def setLineCoordinates(locx0, locy0, locx1, locy1):
self.locx0 = locx0
self.locy0 = locy0
self.locx1 = locx1
self.locy1 = locy1
def getLineCoordinatesX0():
return self.x0
def getLineCoordinatesY0():
return self.y0
def getLineCoordinatesX1():
return self.x1
def getLineCoordinatesY0():
return self.y0
Here is where I call the class method:
def LineDepot():
x0 = None
x1 = None
y0 = None
y1 = None
line = Line()
print"Please enter starting and ending coordinates "
print"If no value is entered, then it will be assumed that the coordinate value is zero "
x0 = int(input('Enter value for initial x coordiante : '))
y0 = int(input('Enter value for initial y coordiante : '))
x1 = int(input('Enter value for end x coordiante :'))
y1 = int(input('Enter value for end y coordiante :'))
line.setLineCoordinates(x0, y0, x1, y1)
This is the error I have been getting in the output :
Please make a selection from the following menu...
1.Create a new Line
2.View current lines
3.View logs
4.Mail line info or logs
5.View summary of line stats
6.Exit this program
Menu Selection:1
<<Line __init__()>>
Please enter starting and ending coordinates
If no value is entered, then it will be assumed that the coordinate value is zero
Enter value for initial x coordiante : 1
Enter value for initial y coordiante : 2
Enter value for end x coordiante :3
Enter value for end y coordiante :4
Traceback (most recent call last):
File "./linear.line.py", line 107, in <module>
Main()
File "./linear.line.py", line 15, in Main
Menu()
File "./linear.line.py", line 52, in Menu
LineDepot()
File "./linear.line.py", line 32, in LineDepot
line.setLineCoordinates(x0, y0, x1, y1)
TypeError: setLineCoordinates() takes exactly 4 arguments (5 given)
I trying to figure out for the life of me why when I pass 4 arguments, the interpreter is
telling me that I am trying to pass 5.
I have and continue to be in the process of researching the problem.
Any help with this will be greatly appreciated.
Thanks!!!
A:
You are missing self in your definition
When a class method is called python includes the objects reference as the first function argument
def setLineCoordinates(self,x0,y0,x1,y1)
def getLineCoordinatesX0(self):
...
A:
You forgot to add self to the class methods' definitions. The first parameter (which by convention is called self) contains a reference to the object instance, and it needs to be explicitly written in the definition, whereas it will be implicitly added when the method is called.
def setLineCoordinates(self, locx0, locy0, locx1, locy1):
etc...
should work better.
A:
FYI - that is an instance method and not a class method. There are three method types in python.
A class method is a method that receives a class object as the first argument
A static method is a method with absolutely no context
An instance method is a method that receives a instance of a class as the first argument
Each of the method types has a different use and purpose. As others have stated, you are missing the self instance argument to your instance methods. Here's a little example of each of the method types and how they are called for comparison.
class C:
c_class_var = 1
def __init__(self):
self.instance_var = 2
def instance_method(self):
print
print 'instance_method called for object', self
print 'dir()', dir()
print 'dir(self)', dir(self)
@staticmethod
def static_method():
print
print 'static_method called, no context exists!'
print 'dir()', dir()
@classmethod
def class_method(cls):
print
print 'class_method called for class', cls
print 'dir()', dir()
print 'dir(cls)', dir(cls)
class D(C):
d_class_var = 3
c_obj = C()
c_obj.instance_method()
C.static_method()
C.class_method()
d_obj = D()
d_obj.instance_method()
D.static_method()
D.class_method()
and here is the output:
instance_method called for object <__main__.C instance at 0x00A706E8>
dir() ['self']
dir(self) ['__doc__', '__init__', '__module__', 'c_class_var', 'class_method', 'instance_method', 'instance_var', 'static_method']
static_method called, no context exists!
dir() []
class_method called for class __main__.C
dir() ['cls']
dir(cls) ['__doc__', '__init__', '__module__', 'c_class_var', 'class_method', 'instance_method', 'static_method']
instance_method called for object <__main__.D instance at 0x00A70710>
dir() ['self']
dir(self) ['__doc__', '__init__', '__module__', 'c_class_var', 'class_method', 'd_class_var', 'instance_method', 'instance_var', 'static_method']
static_method called, no context exists!
dir() []
class_method called for class __main__.D
dir() ['cls']
dir(cls) ['__doc__', '__init__', '__module__', 'c_class_var', 'class_method', 'd_class_var', 'instance_method', 'static_method']
A:
You forgot to put self in the method name.
class Line():
def setLineCoordinates(self,locx0, locy0, locx1, locy1):
self.locx0 = locx0
self.locy0 = locy0
self.locx1 = locx1
self.locy1 = locy1
def getLineCoordinatesX0(self):
return self.x0
In python the passing of the self variable has to be explicit (it is not implicit like C++).
A:
Your function definition is missing `self
def setLineCoordinates(self, locx0, locy0, locx1, locy1):
self.locx0 = locx0
....
| Issue with passing paramters to a class method in Python | I have been playing with Python for the past week and I running into a problem with passing 4 parameters to a class method.
Here is the class method defined within it's class:
class Line:
locx0 = 0
locy0 = 0
locx1 = 0
locy1 = 0
def __init__(self):
print'<<Line __init__()>>'
def setLineCoordinates(locx0, locy0, locx1, locy1):
self.locx0 = locx0
self.locy0 = locy0
self.locx1 = locx1
self.locy1 = locy1
def getLineCoordinatesX0():
return self.x0
def getLineCoordinatesY0():
return self.y0
def getLineCoordinatesX1():
return self.x1
def getLineCoordinatesY0():
return self.y0
Here is where I call the class method:
def LineDepot():
x0 = None
x1 = None
y0 = None
y1 = None
line = Line()
print"Please enter starting and ending coordinates "
print"If no value is entered, then it will be assumed that the coordinate value is zero "
x0 = int(input('Enter value for initial x coordiante : '))
y0 = int(input('Enter value for initial y coordiante : '))
x1 = int(input('Enter value for end x coordiante :'))
y1 = int(input('Enter value for end y coordiante :'))
line.setLineCoordinates(x0, y0, x1, y1)
This is the error I have been getting in the output :
Please make a selection from the following menu...
1.Create a new Line
2.View current lines
3.View logs
4.Mail line info or logs
5.View summary of line stats
6.Exit this program
Menu Selection:1
<<Line __init__()>>
Please enter starting and ending coordinates
If no value is entered, then it will be assumed that the coordinate value is zero
Enter value for initial x coordiante : 1
Enter value for initial y coordiante : 2
Enter value for end x coordiante :3
Enter value for end y coordiante :4
Traceback (most recent call last):
File "./linear.line.py", line 107, in <module>
Main()
File "./linear.line.py", line 15, in Main
Menu()
File "./linear.line.py", line 52, in Menu
LineDepot()
File "./linear.line.py", line 32, in LineDepot
line.setLineCoordinates(x0, y0, x1, y1)
TypeError: setLineCoordinates() takes exactly 4 arguments (5 given)
I trying to figure out for the life of me why when I pass 4 arguments, the interpreter is
telling me that I am trying to pass 5.
I have and continue to be in the process of researching the problem.
Any help with this will be greatly appreciated.
Thanks!!!
| [
"You are missing self in your definition\nWhen a class method is called python includes the objects reference as the first function argument\ndef setLineCoordinates(self,x0,y0,x1,y1)\ndef getLineCoordinatesX0(self):\n...\n\n",
"You forgot to add self to the class methods' definitions. The first parameter (which b... | [
5,
4,
3,
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0003443292_python.txt |
Q:
Finding the correlation matrix
I have a matrix which is fairly large (around 50K rows), and I want to print the correlation coefficient between each row in the matrix. I have written Python code like this:
for i in xrange(rows): # rows are the number of rows in the matrix.
for j in xrange(i, rows):
r = scipy.stats.pearsonr(data[i,:], data[j,:])
print r
Please note that I am making use of the pearsonr function available from the scipy module (http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.pearsonr.html).
My question is: Is there a quicker way of doing this? Is there some matrix partition technique that I can use?
Thanks!
A:
New Solution
After looking at Joe Kington's answer, I decided to look into the corrcoef() code and was inspired by it to do the following implementation.
ms = data.mean(axis=1)[(slice(None,None,None),None)]
datam = data - ms
datass = np.sqrt(scipy.stats.ss(datam,axis=1))
for i in xrange(rows):
temp = np.dot(datam[i:],datam[i].T)
rs = temp / (datass[i:]*datass[i])
Each loop through generates the Pearson coefficients between row i and rows i through to the last row. It is very fast. It is at least 1.5x as fast as using corrcoef() alone because it doesn't redundantly calculate the coefficients and a few other things. It will also be faster and won't give you the memory problems with a 50,000 row matrix because then you can choose to either store each set of r's or process them before generating another set. Without storing any of the r's long term, I was able to get the above code to run on 50,000 x 10 set of randomly generated data in under a minute on my fairly new laptop.
Old Solution
First, I wouldn't recommend printing out the r's to the screen. For 100 rows (10 columns), this is a difference of 19.79 seconds with printing vs. 0.301 seconds without using your code. Just store the r's and use them later if you would like, or do some processing on them as you go along like looking for some of the largest r's.
Second, you can get some savings by not redundantly calculating some quantities. The Pearson coefficient is calculated in scipy using some quantities that you can precalculate rather than calculating every time that a row is used. Also, you aren't using the p-value (which is also returned by pearsonr() so let's scratch that too. Using the below code:
r = np.zeros((rows,rows))
ms = data.mean(axis=1)
datam = np.zeros_like(data)
for i in xrange(rows):
datam[i] = data[i] - ms[i]
datass = scipy.stats.ss(datam,axis=1)
for i in xrange(rows):
for j in xrange(i,rows):
r_num = np.add.reduce(datam[i]*datam[j])
r_den = np.sqrt(datass[i]*datass[j])
r[i,j] = min((r_num / r_den), 1.0)
I get a speed-up of about 4.8x over the straight scipy code when I've removed the p-value stuff - 8.8x if I leave the p-value stuff in there (I used 10 columns with hundreds of rows). I also checked that it does give the same results. This isn't a really huge improvement, but it might help.
Ultimately, you are stuck with the problem that you are computing (50000)*(50001)/2 = 1,250,025,000 Pearson coefficients (if I'm counting correctly). That's a lot. By the way, there's really no need to compute each row's Pearson coefficient with itself (it will equal 1), but that only saves you from computing 50,000 Pearson coefficients. With the above code, I expect that it would take about 4 1/4 hours to do your computation if you have 10 columns to your data based on my results on smaller datasets.
You can get some improvement by taking the above code into Cython or something similar. I expect that you'll maybe get up to a 10x improvement over straight Scipy if you're lucky. Also, as suggested by pyInTheSky, you can do some multiprocessing.
A:
Have you tried just using numpy.corrcoef? Seeing as how you're not using the p-values, it should do exactly what you want, with as little fuss as possible. (Unless I'm mis-remembering exactly what pearson's R is, which is quite possible.)
Just quickly checking the results on random data, it returns exactly the same thing as @Justin Peel's code above and runs ~100x faster.
For example, testing things with 1000 rows and 10 columns of random data...:
import numpy as np
import scipy as sp
import scipy.stats
def main():
data = np.random.random((1000, 10))
x = corrcoef_test(data)
y = justin_peel_test(data)
print 'Maximum difference between the two results:', np.abs((x-y)).max()
return data
def corrcoef_test(data):
"""Just using numpy's built-in function"""
return np.corrcoef(data)
def justin_peel_test(data):
"""Justin Peel's suggestion above"""
rows = data.shape[0]
r = np.zeros((rows,rows))
ms = data.mean(axis=1)
datam = np.zeros_like(data)
for i in xrange(rows):
datam[i] = data[i] - ms[i]
datass = sp.stats.ss(datam,axis=1)
for i in xrange(rows):
for j in xrange(i,rows):
r_num = np.add.reduce(datam[i]*datam[j])
r_den = np.sqrt(datass[i]*datass[j])
r[i,j] = min((r_num / r_den), 1.0)
r[j,i] = r[i,j]
return r
data = main()
Yields a maximum absolute difference of ~3.3e-16 between the two results
And timings:
In [44]: %timeit corrcoef_test(data)
10 loops, best of 3: 71.7 ms per loop
In [45]: %timeit justin_peel_test(data)
1 loops, best of 3: 6.5 s per loop
numpy.corrcoef should do just what you want, and it's a lot faster.
A:
you can use the python multiprocess module, chunk up your rows into 10 sets, buffer your results and then print the stuff out (this would only speed it up on a multicore machine though)
http://docs.python.org/library/multiprocessing.html
btw: you'd also have to turn your snippet into a function and also consider how to do the data reassembly. having each subprocess have a list like this ...[startcord,stopcord,buff] .. might work nicely
def myfunc(thelist):
for i in xrange(thelist[0]:thelist[1]):
....
thelist[2] = result
| Finding the correlation matrix | I have a matrix which is fairly large (around 50K rows), and I want to print the correlation coefficient between each row in the matrix. I have written Python code like this:
for i in xrange(rows): # rows are the number of rows in the matrix.
for j in xrange(i, rows):
r = scipy.stats.pearsonr(data[i,:], data[j,:])
print r
Please note that I am making use of the pearsonr function available from the scipy module (http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.pearsonr.html).
My question is: Is there a quicker way of doing this? Is there some matrix partition technique that I can use?
Thanks!
| [
"New Solution\nAfter looking at Joe Kington's answer, I decided to look into the corrcoef() code and was inspired by it to do the following implementation.\nms = data.mean(axis=1)[(slice(None,None,None),None)]\ndatam = data - ms\ndatass = np.sqrt(scipy.stats.ss(datam,axis=1))\nfor i in xrange(rows):\n temp = np.... | [
10,
7,
0
] | [] | [] | [
"algorithm",
"python",
"scipy"
] | stackoverflow_0003437513_algorithm_python_scipy.txt |
Q:
Reading web pages with Python
I'm trying to read and handle a web-page in Python which has lines like the following in it:
<div class="or_q_tagcloud" id="tag1611"></div></td></tr><tr><td class="or_q_artist"><a title="[Artist916]" href="http://rateyourmusic.com/artist/ac_dc" class="artist">AC/DC</a></td><td class="or_q_album"><a title="[Album374717]" href="http://rateyourmusic.com/release/album/ac_dc/live_f5/" class="album">Live</a></td><td class="or_q_rating" id="rating374717">4.0</td><td class="or_q_ownership" id="ownership374717">CD</td><td class="or_q_tags_td">
I'm currently only interested in the artist name (AC/DC) and album name (Live). I can read and print them with libxml2dom but I can't figure out how I can distinguish between the links because the node value for every link is None.
One obvious way would be to read the input line at a time but is there a more clever way of handling this html file so that I can create either two separate lists where each index matches the other or a struct with this info?
import urllib
import sgmllib
import libxml2dom
def collect_text(node):
"A function which collects text inside 'node', returning that text."
s = ""
for child_node in node.childNodes:
if child_node.nodeType == child_node.TEXT_NODE:
s += child_node.nodeValue
else:
s += collect_text(child_node)
return s
f = urllib.urlopen("/home/x/Documents/rym_list.html")
s = f.read()
doc = libxml2dom.parseString(s, html=1)
links = doc.getElementsByTagName("a")
for link in links:
print "--\nNode " , artist.childNodes
if artist.localName == "artist":
print "artist"
print collect_text(artist).encode('utf-8')
f.close()
A:
Given the small snippit of HTML, I've no idea whether this would be effective on the full page, but here's how to extract 'AC/DC' and 'Live' using lxml.etree and xpath.
>>> from lxml import etree
>>> doc = etree.HTML("""<html>
... <head></head>
... <body>
... <tr>
... <td class="or_q_artist"><a title="[Artist916]" href="http://rateyourmusic.com/artist/ac_dc" class="artist">AC/DC</a></td>
... <td class="or_q_album"><a title="[Album374717]" href="http://rateyourmusic.com/release/album/ac_dc/live_f5/" class="album">Live</a></td>
... <td class="or_q_rating" id="rating374717">4.0</td><td class="or_q_ownership" id="ownership374717">CD</td>
... <td class="or_q_tags_td">
... </tr>
... </body>
... </html>
... """)
>>> doc.xpath('//td[@class="or_q_artist"]/a/text()|//td[@class="or_q_album"]/a/text()')
['AC/DC', 'Live']
A:
See if you can solve the problem in javascript using jQuery style DOM/CSS selectors to get at the elements/text that you want.
If you can then get a copy of BeautifulSoup for python and you should be good to go in a matter of minutes.
| Reading web pages with Python | I'm trying to read and handle a web-page in Python which has lines like the following in it:
<div class="or_q_tagcloud" id="tag1611"></div></td></tr><tr><td class="or_q_artist"><a title="[Artist916]" href="http://rateyourmusic.com/artist/ac_dc" class="artist">AC/DC</a></td><td class="or_q_album"><a title="[Album374717]" href="http://rateyourmusic.com/release/album/ac_dc/live_f5/" class="album">Live</a></td><td class="or_q_rating" id="rating374717">4.0</td><td class="or_q_ownership" id="ownership374717">CD</td><td class="or_q_tags_td">
I'm currently only interested in the artist name (AC/DC) and album name (Live). I can read and print them with libxml2dom but I can't figure out how I can distinguish between the links because the node value for every link is None.
One obvious way would be to read the input line at a time but is there a more clever way of handling this html file so that I can create either two separate lists where each index matches the other or a struct with this info?
import urllib
import sgmllib
import libxml2dom
def collect_text(node):
"A function which collects text inside 'node', returning that text."
s = ""
for child_node in node.childNodes:
if child_node.nodeType == child_node.TEXT_NODE:
s += child_node.nodeValue
else:
s += collect_text(child_node)
return s
f = urllib.urlopen("/home/x/Documents/rym_list.html")
s = f.read()
doc = libxml2dom.parseString(s, html=1)
links = doc.getElementsByTagName("a")
for link in links:
print "--\nNode " , artist.childNodes
if artist.localName == "artist":
print "artist"
print collect_text(artist).encode('utf-8')
f.close()
| [
"Given the small snippit of HTML, I've no idea whether this would be effective on the full page, but here's how to extract 'AC/DC' and 'Live' using lxml.etree and xpath.\n>>> from lxml import etree\n>>> doc = etree.HTML(\"\"\"<html>\n... <head></head>\n... <body>\n... <tr>\n... <td class=\"or_q_artist\"><a title=\"... | [
2,
0
] | [] | [] | [
"libxml2",
"python"
] | stackoverflow_0003441447_libxml2_python.txt |
Q:
R, python or octave: empirical quantile (inverse cdf) with confidence intervals?
I'm looking for a built-in function that returns the sample quantile and an estimated confidence interval in something other than MATLAB (MATLAB's ecdf does this).
I'm guessing R has this built-in and I just haven't found it yet.
If you have any standalone code to do this, you could also point to it here, though I hope to find something that is included as part of a larger open code base.
-Trying to get away from MATLAB.
A:
The survfit function can be used to get the survival function with confidence intervals. Since it is just 1-ecdf, there is a direct relationship between the quantiles. To use this you have to create a variable that says that each of your observations is complete (not censored):
library(survival)
x <- rexp(10)
ev <- rep(1, length(x))
sf <- survfit(Surv(x,ev)~1)
With output:
>summary(sf)
Call: survfit(formula = Surv(x, ev) ~ 1)
time n.risk n.event survival std.err lower 95% CI upper 95% CI
-1.4143 10 1 0.9 0.0949 0.7320 1.000
-1.1229 9 1 0.8 0.1265 0.5868 1.000
-0.9396 8 1 0.7 0.1449 0.4665 1.000
-0.4413 7 1 0.6 0.1549 0.3617 0.995
-0.2408 6 1 0.5 0.1581 0.2690 0.929
-0.1698 5 1 0.4 0.1549 0.1872 0.855
0.0613 4 1 0.3 0.1449 0.1164 0.773
0.1983 3 1 0.2 0.1265 0.0579 0.691
0.5199 2 1 0.1 0.0949 0.0156 0.642
0.8067 1 1 0.0 NaN NA NA
In fact, survfit does calculate the median and its confidence interval, but not the other quantiles:
>sf
Call: survfit(formula = Surv(x, ev) ~ 1)
records n.max n.start events median 0.95LCL 0.95UCL
10.000 10.000 10.000 10.000 -0.205 -0.940 NA
The actual work for of the calculation of the confidence interval of the median is well hidden in the survival:::survmean function, which you could probably use to generalize to other quantiles.
| R, python or octave: empirical quantile (inverse cdf) with confidence intervals? | I'm looking for a built-in function that returns the sample quantile and an estimated confidence interval in something other than MATLAB (MATLAB's ecdf does this).
I'm guessing R has this built-in and I just haven't found it yet.
If you have any standalone code to do this, you could also point to it here, though I hope to find something that is included as part of a larger open code base.
-Trying to get away from MATLAB.
| [
"The survfit function can be used to get the survival function with confidence intervals. Since it is just 1-ecdf, there is a direct relationship between the quantiles. To use this you have to create a variable that says that each of your observations is complete (not censored):\nlibrary(survival)\nx <- rexp(10)\ne... | [
4
] | [] | [] | [
"c#",
"octave",
"python",
"r",
"statistics"
] | stackoverflow_0003442810_c#_octave_python_r_statistics.txt |
Q:
Array broadcasting with numpy
How do I write the following loop using Python's implicit looping?
def kl(myA, myB, a, b):
lots of stuff that assumes all inputs are scalars
x, y = meshgrid(inclusive_arange(0.0, xsize, 0.10),\
inclusive_arange(0.0, ysize, 0.10))
for j in range(x.shape[0]):
for i in range(x.shape[1]):
z[j, i] = kl(x[j, i], y[j, i])
I want to do something like
z = kl(x, y)
but that gives:
TypeError: only length-1 arrays can be converted to Python scalars
A:
The capability you're asking about only exists in Numpy, and it's called array broadcasting, not implicit looping. A function that broadcasts a scalar operation over an array is called a universal function, or ufunc. Many basic Numpy functions are of this type.
You can use numpy.frompyfunc to convert your existing function kl into a ufunc.
kl_ufunc = numpy.frompyfunc(kl, 4, 1)
...
z = kl_ufunc(x + 1.0, y + 1.0, myA, myB)
Of course, if you want, you could call the ufunc kl instead of kl_ufunc, but then the original definition of kl would be lost. That might be fine for your purposes.
A:
There is a video series here which you might find useful:
http://showmedo.com/videotutorials/video?name=10370070&fromSeriesID=1037
Note that it is part of a tutorial series that discusses a broad range of numpy topics.
Just FYI.
| Array broadcasting with numpy | How do I write the following loop using Python's implicit looping?
def kl(myA, myB, a, b):
lots of stuff that assumes all inputs are scalars
x, y = meshgrid(inclusive_arange(0.0, xsize, 0.10),\
inclusive_arange(0.0, ysize, 0.10))
for j in range(x.shape[0]):
for i in range(x.shape[1]):
z[j, i] = kl(x[j, i], y[j, i])
I want to do something like
z = kl(x, y)
but that gives:
TypeError: only length-1 arrays can be converted to Python scalars
| [
"The capability you're asking about only exists in Numpy, and it's called array broadcasting, not implicit looping. A function that broadcasts a scalar operation over an array is called a universal function, or ufunc. Many basic Numpy functions are of this type.\nYou can use numpy.frompyfunc to convert your existin... | [
5,
1
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0003443234_numpy_python.txt |
Q:
fullscreen matplotlib figures
I am visualising numpy arrays with imshow from pyplot, and would like to see just the array data in a fullscreen display with no toolbars or window borders.
Running with "ipython -pylab" and then calling imshow() and show() gives me a window but pressing "f" does not toggle fullscreen mode. Is there a function call to toggle fullscreen mode? (that would also be preferable to manually pressing a key)
A:
I think fullscreen is only implemented for the gtk matplotlib backend (I could be very wrong there...). At any rate, it's definitely not implemented for all platforms and backends that matplotlib supports.
However, from the sounds of what you're doing (simple fullscreen display of a 2D numpy array), you might find pygarrayimage useful.
| fullscreen matplotlib figures | I am visualising numpy arrays with imshow from pyplot, and would like to see just the array data in a fullscreen display with no toolbars or window borders.
Running with "ipython -pylab" and then calling imshow() and show() gives me a window but pressing "f" does not toggle fullscreen mode. Is there a function call to toggle fullscreen mode? (that would also be preferable to manually pressing a key)
| [
"I think fullscreen is only implemented for the gtk matplotlib backend (I could be very wrong there...). At any rate, it's definitely not implemented for all platforms and backends that matplotlib supports.\nHowever, from the sounds of what you're doing (simple fullscreen display of a 2D numpy array), you might fi... | [
2
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0003443891_matplotlib_python.txt |
Q:
Function for class exemplar
I have something like that in my python code
class A:
__mess = "Yeap!"
def doSome(self):
self.FN()
def FN(self):
pass
def myFN(self):
print self.__mess
b = A()
b.FN = myFN
b.doSome()
But this doesn't work. Where am I wrong?
python 2.6.5
upd: I want to redefine method (FN) only for one exemplar (b).
upd2:
import new
class A:
__mess = "Yeap!"
def doSome(self):
self.FN()
def FN(self):
pass
def myFN(self):
print self.__mess
b = A()
b.FN = new.instancemethod(myFN, b, A)
b.doSome()
Doesn't work too.
Traceback (most recent call last):
File "", line 1, in
File "", line 4, in doSome
File "", line 2, in myFN
AttributeError: A instance has no
attribute '__mess'
A:
myLoopFN is a function, not an instance method. Do
import new
b.loopFN = new.instancemethod( myLoopFN, b, A )
The problem is that Python treats instance methods very slightly differently to regular functions: they get the instance upon which they are run as the default first argument. If you define a method inside a class definition it automagically becomes an instance method, so that when you instantiate the class it gets passed the instance. However, when you define myLoopFN you do it outside the class definition, so that it is an ordinary function instead of an instance method. You fix this by explicitly declaring it as an instance method.
...
BUT
This is icky because it's not something you should do; changing instance methods at runtime will lead to problems. You'll never be sure whether your A is an original A or a modified one, and you won't be able to debug it because you can't tell whether you've changed loopFN or not. This will give you the kind of bugs that Nyarlathotep himself would be proud of.
The right way to do this is to subclass A and override the method, so that you can distinguish between the different classes.
class myA( A ):
def loopFN(self):
#put modified function here
This way, you can instantiate the modified class and be certain of its methods.
Edit
You are using a double-underscore variable name, __mess. You (almost certainly) don't want to do this. For some reason known only to our Benevolent Dictator for Life and a select few others, Python automatically mangles these __ names to _<class-name>__, to serve as a sort-of faux private variable. This is horrible, and besides there's no reason to call it __mess instead of (the much nicer) mess.
If you absolutely must call it __mess, you can refer to it as follows:
def myFN(self):
print( self._A__mess )
(mutatis mutandis when you change the name of A). This is nasty and unPythonic.
A:
Regarding the second error (with __mess):
Change
print self.__mess
to
print self._mess
And change
class A:
__mess = "Yeap!"
to
class A:
_mess = "Yeap!"
Double underscores tell Python to use name-mangling.
An alternative is to change
def myFN(self):
print self.__mess
to
def myFN(self):
print self._A__mess
| Function for class exemplar | I have something like that in my python code
class A:
__mess = "Yeap!"
def doSome(self):
self.FN()
def FN(self):
pass
def myFN(self):
print self.__mess
b = A()
b.FN = myFN
b.doSome()
But this doesn't work. Where am I wrong?
python 2.6.5
upd: I want to redefine method (FN) only for one exemplar (b).
upd2:
import new
class A:
__mess = "Yeap!"
def doSome(self):
self.FN()
def FN(self):
pass
def myFN(self):
print self.__mess
b = A()
b.FN = new.instancemethod(myFN, b, A)
b.doSome()
Doesn't work too.
Traceback (most recent call last):
File "", line 1, in
File "", line 4, in doSome
File "", line 2, in myFN
AttributeError: A instance has no
attribute '__mess'
| [
"myLoopFN is a function, not an instance method. Do\nimport new\nb.loopFN = new.instancemethod( myLoopFN, b, A )\n\nThe problem is that Python treats instance methods very slightly differently to regular functions: they get the instance upon which they are run as the default first argument. If you define a method i... | [
4,
1
] | [] | [] | [
"python"
] | stackoverflow_0003444075_python.txt |
Q:
What is twisted's equivalent of tornado's IOLoop.add_callback?
I'm trying to adapt some tornado code to work with twisted.
Tornado's IOLoop has a function (add_callback) that will essentially call the function back in the next iteration of the loop. As far as I can tell, twisted doesn't have a direct translation of this. Is there any way to simulate this in twisted?
A:
reactor.callLater(0, x) or reactor.callFromThread(x)
| What is twisted's equivalent of tornado's IOLoop.add_callback? | I'm trying to adapt some tornado code to work with twisted.
Tornado's IOLoop has a function (add_callback) that will essentially call the function back in the next iteration of the loop. As far as I can tell, twisted doesn't have a direct translation of this. Is there any way to simulate this in twisted?
| [
"reactor.callLater(0, x) or reactor.callFromThread(x)\n"
] | [
6
] | [] | [] | [
"python",
"tornado",
"twisted"
] | stackoverflow_0003444391_python_tornado_twisted.txt |
Q:
Can subprocess.Popen be used when called from py code running under mod_wsgi in Apache2
I'm using subprocess.Popen and getting IOErrors when running under mod_wsgi. The following code will work in a python term, or a django runserver, and under mod_python. If you put it under mod_wsgi (v2), it fails: (2, 'No such file or directory') I have tried many variations involving using subprocess.PIPE. I have tried to redefine stdout, and to use the httpd directives to turn off mod_wsgi's complains of stdout usage. I recently tried upgrading to version 3.
import subprocess
input_file = 'test.html'
p = subprocess.Popen(['htmldoc','-f', 'output.pdf', '--book', input_file])
p.communicate()
len(open('output.pdf').read())
My test effort is going to be to move back to mod_python, and see if the problem goes away. I'd like to know if anyone else has done this and can shed some light on this problem.
A:
That error message means that Popen can't find htmldoc. Check your $PATH environment variable through os.environ['PATH'] and make sure that htmldoc is installed in one of the paths there.
Alternatively, you can call Popen using an absolute path. For example,
subprocess.Popen(['/usr/bin/htmldoc', ...
| Can subprocess.Popen be used when called from py code running under mod_wsgi in Apache2 | I'm using subprocess.Popen and getting IOErrors when running under mod_wsgi. The following code will work in a python term, or a django runserver, and under mod_python. If you put it under mod_wsgi (v2), it fails: (2, 'No such file or directory') I have tried many variations involving using subprocess.PIPE. I have tried to redefine stdout, and to use the httpd directives to turn off mod_wsgi's complains of stdout usage. I recently tried upgrading to version 3.
import subprocess
input_file = 'test.html'
p = subprocess.Popen(['htmldoc','-f', 'output.pdf', '--book', input_file])
p.communicate()
len(open('output.pdf').read())
My test effort is going to be to move back to mod_python, and see if the problem goes away. I'd like to know if anyone else has done this and can shed some light on this problem.
| [
"That error message means that Popen can't find htmldoc. Check your $PATH environment variable through os.environ['PATH'] and make sure that htmldoc is installed in one of the paths there.\nAlternatively, you can call Popen using an absolute path. For example,\nsubprocess.Popen(['/usr/bin/htmldoc', ...\n\n"
] | [
0
] | [] | [] | [
"apache2",
"mod_wsgi",
"python",
"subprocess"
] | stackoverflow_0003444536_apache2_mod_wsgi_python_subprocess.txt |
Q:
How to use itertools.groupby when the key value is in the elements of the iterable?
To illustrate, I start with a list of 2-tuples:
import itertools
import operator
raw = [(1, "one"),
(2, "two"),
(1, "one"),
(3, "three"),
(2, "two")]
for key, grp in itertools.groupby(raw, key=lambda item: item[0]):
print key, list(grp).pop()[1]
yields:
1 one
2 two
1 one
3 three
2 two
In an attempt to investigate why:
for key, grp in itertools.groupby(raw, key=lambda item: item[0]):
print key, list(grp)
# ---- OUTPUT ----
1 [(1, 'one')]
2 [(2, 'two')]
1 [(1, 'one')]
3 [(3, 'three')]
2 [(2, 'two')]
Even this will give me the same output:
for key, grp in itertools.groupby(raw, key=operator.itemgetter(0)):
print key, list(grp)
I want to get something like:
1 one, one
2 two, two
3 three
I am thinking this is because the key is within the tuple inside the list, when in fact the tuple gets moved around as one. Is there a way to get to my desired output? Maybe groupby() isn't suited for this task?
A:
groupby clusters consecutive elements of the iterable which have the same key.
To produce the output you desire, you must first sort raw.
for key, grp in itertools.groupby(sorted(raw), key=operator.itemgetter(0)):
print key, map(operator.itemgetter(1), grp)
# 1 ['one', 'one']
# 2 ['two', 'two']
# 3 ['three']
A:
I think a cleaner way to get your desired result is this.
>>> from collections import defaultdict
>>> d=defaultdict(list)
>>> for k,v in raw:
... d[k].append(v)
...
>>> for k,v in sorted(d.items()):
... print k, v
...
1 ['one', 'one']
2 ['two', 'two']
3 ['three']
building d is O(n), and now sorted() is just over the unique keys instead of the entire dataset
A:
From the docs:
The operation of groupby() is similar
to the uniq filter in Unix. It
generates a break or new group every
time the value of the key function
changes (which is why it is usually
necessary to have sorted the data
using the same key function). That
behavior differs from SQL’s GROUP BY
which aggregates common elements
regardless of their input order.
Since you are sorting the tuples lexicographically anyway, you can just call sorted:
for key, grp in itertools.groupby( sorted( raw ), key = operator.itemgetter( 0 ) ):
print( key, list( map( operator.itemgetter( 1 ), list( grp ) ) ) )
| How to use itertools.groupby when the key value is in the elements of the iterable? | To illustrate, I start with a list of 2-tuples:
import itertools
import operator
raw = [(1, "one"),
(2, "two"),
(1, "one"),
(3, "three"),
(2, "two")]
for key, grp in itertools.groupby(raw, key=lambda item: item[0]):
print key, list(grp).pop()[1]
yields:
1 one
2 two
1 one
3 three
2 two
In an attempt to investigate why:
for key, grp in itertools.groupby(raw, key=lambda item: item[0]):
print key, list(grp)
# ---- OUTPUT ----
1 [(1, 'one')]
2 [(2, 'two')]
1 [(1, 'one')]
3 [(3, 'three')]
2 [(2, 'two')]
Even this will give me the same output:
for key, grp in itertools.groupby(raw, key=operator.itemgetter(0)):
print key, list(grp)
I want to get something like:
1 one, one
2 two, two
3 three
I am thinking this is because the key is within the tuple inside the list, when in fact the tuple gets moved around as one. Is there a way to get to my desired output? Maybe groupby() isn't suited for this task?
| [
"groupby clusters consecutive elements of the iterable which have the same key.\nTo produce the output you desire, you must first sort raw.\nfor key, grp in itertools.groupby(sorted(raw), key=operator.itemgetter(0)):\n print key, map(operator.itemgetter(1), grp)\n\n# 1 ['one', 'one']\n# 2 ['two', 'two']\n# 3 ['t... | [
13,
7,
3
] | [] | [] | [
"group_by",
"python",
"python_itertools"
] | stackoverflow_0003440549_group_by_python_python_itertools.txt |
Q:
Printing a particular subset of keys in a dictionary
I have a dictionary in Python where the keys are pathnames. For example:
dict["/A"] = 0
dict["/A/B"] = 1
dict["/A/C"] = 1
dict["/X"] = 10
dict["/X/Y"] = 11
I was wondering, what's a good way to print all "subpaths" given any key.
For example, given a function called "print_dict_path" that does this, something like
print_dict_path("/A")
or
print_dict_path("/A/B")
would print out something like:
"B" = 1
"C" = 1
The only method I can think of is something like using regex and going through the entire dictionary, but I'm not sure if that's the best method (nor am I that well versed in regex).
Thanks for any help.
A:
One possibility without using regex is to just use startswith
top_path = '/A/B'
for p in d.iterkeys():
if p.startswith(top_path):
print d[p]
A:
You can use str.find:
def print_dict_path(prefix, d):
for k in d:
if k.find(prefix) == 0:
print "\"{0}\" = {1}".format(k,d[k])
A:
Well, you'll definitely have to loop through the entire dict.
def filter_dict_path( d, sub ):
for key, val in d.iteritems():
if key.startswith(sub): ## or do you want `sub in key` ?
yield key, val
print dict(filter_dict_path( old_dict, sub ))
You could speed this up by using the appropriate data structure: a Tree.
A:
Is your dictionary structure fixed? It would be nicer to do this using nested dictionaries:
{
"A": {
"value": 0
"dirs": {
"B": {
"value": 1
}
"C": {
"value": 1
}
}
"X": {
"value": 10
"dirs": {
"Y": {
"value": 11
}
}
The underlying data structure here is a tree, but Python doesn't have that built in.
A:
This removes one level of indenting, which may make the code in the body of the for loop more readable in some cases
top_path = '/A/B'
for p in (p for p in d.iterkeys() if p.startswith(top_path)):
print d[p]
If you find performance to be a problem, consider using a trie instead of the dictionary
| Printing a particular subset of keys in a dictionary | I have a dictionary in Python where the keys are pathnames. For example:
dict["/A"] = 0
dict["/A/B"] = 1
dict["/A/C"] = 1
dict["/X"] = 10
dict["/X/Y"] = 11
I was wondering, what's a good way to print all "subpaths" given any key.
For example, given a function called "print_dict_path" that does this, something like
print_dict_path("/A")
or
print_dict_path("/A/B")
would print out something like:
"B" = 1
"C" = 1
The only method I can think of is something like using regex and going through the entire dictionary, but I'm not sure if that's the best method (nor am I that well versed in regex).
Thanks for any help.
| [
"One possibility without using regex is to just use startswith\ntop_path = '/A/B'\nfor p in d.iterkeys():\n if p.startswith(top_path):\n print d[p]\n\n",
"You can use str.find:\ndef print_dict_path(prefix, d):\n for k in d:\n if k.find(prefix) == 0:\n print \"\\\"{0}\\\" = {1}\".for... | [
5,
1,
1,
1,
1
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0003441255_dictionary_python.txt |
Q:
Making a key-command for a python program with no GUI
I want to make a key command so that the program will stop running when the Ctrl key then the 'e' key then the 'x' key then the 'i' and 't' keys are hit. So basically when the program is running if you type Ctrl + exit, the program will stop running. There is no GUI and I don't want to do this via a python interpreter.
The end goal is a program that will close if the Ctrl + exit command is typed, regardless of what other programs are in focus. This program is going to be a light weight key-logger, so having a GUI would be pointless.
A:
Use a simple FSM for the "exiting logic" while you're logging the received keys, e.g.:
FINAL_STATE = 9999
transitions = {(None, 'e'): 1, (1, 'x'): 2, (2, 'i'): 3, (3, 't'): FINAL_STATE}
def keylogger_logic(filename, get_next_keystroke, fsm_state=None):
with open(filename, 'w') as f:
k = get_next_keystroke()
f.write(k)
f.flush()
fsm_state = transitions.get((fsm_state, k))
if fsm_state == FINAL_STATE: break
This assume you have or write a function that returns "the next keystroke" as a string, and pass it to keylogger_logic as the second argument (I'd do it this way, not by hardcoding the key-getter functionality together with this logic, as an application of the Dependency Injection pattern to make things very easy to unit-test; similarly for having fsm_state as an argument, i.e., making it settable by the caller -- eases testing). Easy to adjust if you'd rather have your "get next keystroke" function return things other than a string (you'll just have to fix the f.write and the transitions table).
| Making a key-command for a python program with no GUI | I want to make a key command so that the program will stop running when the Ctrl key then the 'e' key then the 'x' key then the 'i' and 't' keys are hit. So basically when the program is running if you type Ctrl + exit, the program will stop running. There is no GUI and I don't want to do this via a python interpreter.
The end goal is a program that will close if the Ctrl + exit command is typed, regardless of what other programs are in focus. This program is going to be a light weight key-logger, so having a GUI would be pointless.
| [
"Use a simple FSM for the \"exiting logic\" while you're logging the received keys, e.g.:\nFINAL_STATE = 9999\ntransitions = {(None, 'e'): 1, (1, 'x'): 2, (2, 'i'): 3, (3, 't'): FINAL_STATE}\n\ndef keylogger_logic(filename, get_next_keystroke, fsm_state=None):\n with open(filename, 'w') as f:\n k = get_ne... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0003444558_python.txt |
Q:
How to build a computationally intensive webservice?
I need to build a webservice that is very computationally intensive, and I'm trying to get my bearings on how best to proceed.
I expect users to connect to my service, at which point some computation is done for some amount of time, typically less than 60s. The user knows that they need to wait, so this is not really a problem. My question is, what's the best way to structure a service like this and leave me with the least amount of headache? Can I use Node.js, web.py, CherryPy, etc.? Do I need a load balancer sitting in front of these pieces if used? I don't expect huge numbers of users, perhaps hundreds or into the thousands. I'll need a number of machines to host this number of users, of course, but this is uncharted territory for me, and if someone can give me a few pointers or things to read, that would be great.
Thanks.
A:
Can I use Node.js, web.py, CherryPy, etc.?
Yes. Pick one. Django is nice, also.
Do I need a load balancer sitting in front of these pieces if used?
Almost never.
I'll need a number of machines to host this number of users,
Doubtful.
Remember that each web transaction has several distinct (and almost unrelated) parts.
A front-end (Apache HTTPD or NGINX or similar) accepts the initial web request. It can handle serving static files (.CSS, .JS, Images, etc.) so your main web application is uncluttered by this.
A reasonably efficient middleware like mod_wsgi can manage dozens (or hundreds) of backend processes.
If you choose a clever backend processing component like celery, you should be able to distribute the "real work" to the minimal number of processors to get the job done.
The results are fed back into Apache HTTPD (or NGINX) via mod_wsgi to the user's browser.
Now the backend processes (managed by celery) are divorced from the essential web server. You achieve a great deal of parallelism with Apache HTTPD and mod_wsgi and celery allowing you to use every scrap of processor resource.
Further, you may be able to decompose your "computationally intensive" process into parallel processes -- a Unix Pipeline is remarkably efficient and makes use of all available resources. You have to decompose your problem into step1 | step2 | step3 and make celery manage those pipelines.
You may find that this kind of decomposition leads to serving a far larger workload than you might have originally imagined.
Many Python web frameworks will keep the user's session information in a single common database. This means that all of your backends can -- without any real work -- move the user's session from web server to web server, making "load balancing" seamless and automatic. Just have lots of HTTPD/NGINX front-ends that spawn Django (or web.py or whatever) which all share a common database. It works remarkably well.
A:
I think you can build it however you like, as long as you can make it an asynchronous service so that the users don't have to wait.
Unless, of course, the users don't mind waiting in this context.
A:
I'd recommend using nginx as it can handle rewrite/balancing/ssl etc with a minimum of fuss
A:
If you want to make your web sevices asynchronous you can try Twisted. It is a framework oriented to asynchronous tasks and implements so many network protocols. It is so easy to offer this services via xml-rpc (just put xmlrpc_ as the prefix of your method). On the other hand it scales very well with hundreds and thousands of users.
Celery is also a good option to make the most computionally intensive tasks asynchronous. It integrates very well with Django.
| How to build a computationally intensive webservice? | I need to build a webservice that is very computationally intensive, and I'm trying to get my bearings on how best to proceed.
I expect users to connect to my service, at which point some computation is done for some amount of time, typically less than 60s. The user knows that they need to wait, so this is not really a problem. My question is, what's the best way to structure a service like this and leave me with the least amount of headache? Can I use Node.js, web.py, CherryPy, etc.? Do I need a load balancer sitting in front of these pieces if used? I don't expect huge numbers of users, perhaps hundreds or into the thousands. I'll need a number of machines to host this number of users, of course, but this is uncharted territory for me, and if someone can give me a few pointers or things to read, that would be great.
Thanks.
| [
"\nCan I use Node.js, web.py, CherryPy, etc.? \n\nYes. Pick one. Django is nice, also.\n\nDo I need a load balancer sitting in front of these pieces if used? \n\nAlmost never.\n\nI'll need a number of machines to host this number of users, \n\nDoubtful.\nRemember that each web transaction has several distinct (an... | [
6,
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0003444804_python.txt |
Q:
python unittest methods
Can I call a test method from within the test class in python? For example:
class Test(unittest.TestCase):
def setUp(self):
#do stuff
def test1(self):
self.test2()
def test2(self):
#do stuff
update: I forgot the other half of my question. Will setup or teardown be called only after the method that the tester calls? Or will it get called between test1 entering and after calling test2 from test1?
A:
This is pretty much a Do Not Do That. If you want tests run in a specific order define a runTest method and do not name your methods test....
class Test_Some_Condition( unittest.TestCase ):
def setUp( self ):
...
def runTest( self ):
step1()
step2()
step3()
def tearDown( self ):
...
This will run the steps in order with one (1) setUp and one (1) tearDown. No mystery.
A:
Try running the following code:
import unittest
class Test(unittest.TestCase):
def setUp(self):
print 'Setting Up'
def test1(self):
print 'In test1'
self.test2()
def test2(self):
print 'In test2'
def tearDown(self):
print 'Tearing Down'
if __name__ == '__main__':
unittest.main()
And the results is:
Setting Up
In test1
In test2
Tearing Down
.Setting Up
In test2
Tearing Down
.
----------------------------------------------------------------------
Ran 2 tests in 0.000s
OK
Now you see, setUp get called before a test method get called by unittest, and tearDown is called after the call.
A:
All methods whose name begins with the string 'test' are considered unit tests (i.e. they get run when you call unittest.main()). So you can call methods from within the Test class, but you should name it something that does not start with the string 'test' unless you want it to be also run as a unit test.
A:
sure, why not -- however that means test2 will be called twice -- once by test1 and then again as its own test, since all functions named test will be called.
A:
Yes to both:
setUp will be called between each test
test2 will be called twice.
If you would like to call a function inside a test, then omit the test prefix.
| python unittest methods | Can I call a test method from within the test class in python? For example:
class Test(unittest.TestCase):
def setUp(self):
#do stuff
def test1(self):
self.test2()
def test2(self):
#do stuff
update: I forgot the other half of my question. Will setup or teardown be called only after the method that the tester calls? Or will it get called between test1 entering and after calling test2 from test1?
| [
"This is pretty much a Do Not Do That. If you want tests run in a specific order define a runTest method and do not name your methods test....\nclass Test_Some_Condition( unittest.TestCase ):\ndef setUp( self ):\n ...\ndef runTest( self ):\n step1()\n step2()\n step3()\ndef tearDown( self ):\n ...\n... | [
8,
6,
1,
0,
0
] | [] | [] | [
"python",
"unit_testing"
] | stackoverflow_0003444827_python_unit_testing.txt |
Q:
Twisted: degrade gracefully performance in case reactor is overloaded?
Is it somehow possible to "detect" that the reactor is overloaded and start dropping connections, or refuse new connections? How can we avoid the reactor being completely overloaded and not being able to catch up?
A:
If I understand Twisted Reactors correctly, they don't parallelize everything. Whatever operations have been queued is scheduled and is done one by one.
One way out for you is to have a custom addCallback which checks for how many callbacks have been registered already and drop if necessary.
A:
No easy way, but here's some suggestions: http://www.mail-archive.com/twisted-python@twistedmatrix.com/msg00389.html
A:
I would approach this per protocol. Throttle when the actual service requires it, not when you think it will. Rather than worrying about how many callbacks are waiting for a reactor tick, I'd worry about how long the HTTP requests (for example) are taking to complete. The number of operations waiting for the reactor could be an implementation detail - for example, if one access pattern ended up with callbacks on long DeferredLists, and another had a more linear chain of callbacks, the time to respond might not be different even though the number of callbacks would be.
This could be done by keeping metrics of the time to complete a logical operation (such as servicing a HTTP request). An advantage of this is that it gives you important information before a problem happens.
| Twisted: degrade gracefully performance in case reactor is overloaded? | Is it somehow possible to "detect" that the reactor is overloaded and start dropping connections, or refuse new connections? How can we avoid the reactor being completely overloaded and not being able to catch up?
| [
"If I understand Twisted Reactors correctly, they don't parallelize everything. Whatever operations have been queued is scheduled and is done one by one.\nOne way out for you is to have a custom addCallback which checks for how many callbacks have been registered already and drop if necessary.\n",
"No easy way, b... | [
1,
1,
1
] | [] | [] | [
"performance",
"python",
"twisted"
] | stackoverflow_0003423845_performance_python_twisted.txt |
Q:
Distributing minimal python installation with application
My company is working on an application that is half Qt/C++ for the editor interface and half Django (via QtWebKit browser control) for the runtime. What we want to do is distribute a minimal python installation with our application.
For instance, our Mac app bundle would ideally be structured something like this:
TheApp.app/
Contents/
MacOS/
TheApp
Resources/
MinimalPythonInstallation/
On Windows:
C:\Program Files\TheApp\
TheApp.exe
MinimalPythonInstallation\
I've seen plenty of projects out there for distributing full Python applications such as py2app, py2exe, and PyInstaller. Those seem to have some of the features I'm looking for, but without the ability to just make a minimal python distribution. i.e. the python executable, Django, and the bare minimum of the python standard library needed by Django, our python code, etc.
Is there anything out there that can do what I'm looking for?
A:
You can find the set of modules you need with modulefinder -- indeed, I believe that's a key part of what the systems you mention, like py2exe and PyInstaller, do for you, so I'm not clear why you want to "reinvent the wheel" -- care to clarify? Have you looked at exactly what e.g. PyInstaller puts in the executables it generates, and, if so, why isn't that good enough for you? If you explain this in detail, maybe there's some extra way we can help.
(PyInstaller is cross-platform, so, if you want to support Mac as well as Windows, it's probably the one you'll want, since py2exe is Windows-only).
| Distributing minimal python installation with application | My company is working on an application that is half Qt/C++ for the editor interface and half Django (via QtWebKit browser control) for the runtime. What we want to do is distribute a minimal python installation with our application.
For instance, our Mac app bundle would ideally be structured something like this:
TheApp.app/
Contents/
MacOS/
TheApp
Resources/
MinimalPythonInstallation/
On Windows:
C:\Program Files\TheApp\
TheApp.exe
MinimalPythonInstallation\
I've seen plenty of projects out there for distributing full Python applications such as py2app, py2exe, and PyInstaller. Those seem to have some of the features I'm looking for, but without the ability to just make a minimal python distribution. i.e. the python executable, Django, and the bare minimum of the python standard library needed by Django, our python code, etc.
Is there anything out there that can do what I'm looking for?
| [
"You can find the set of modules you need with modulefinder -- indeed, I believe that's a key part of what the systems you mention, like py2exe and PyInstaller, do for you, so I'm not clear why you want to \"reinvent the wheel\" -- care to clarify? Have you looked at exactly what e.g. PyInstaller puts in the execu... | [
3
] | [] | [] | [
"distribution",
"django",
"macos",
"python",
"windows"
] | stackoverflow_0003444630_distribution_django_macos_python_windows.txt |
Q:
Designing a interface to a websites api
Ok I am programing a way to interface with Grooveshark (http://grooveshark.com). Right now I have a class Grooveshark and several methods, one gets a session with the server, another gets a token that is based on the session and another is used to construct api calls to the server (and other methods use that). Right now I use it like so.... Note uses twisted and t.i.defer in twisted
g = Grooveshark()
d = g.get_session()
d.addCallback(lambda x: g.get_token())
## and then something like.... ##
g.search("Song")
I find this unpythonic and ugly sense even after initializing the class you have to call two methods first or else the other methods won't work. To solve this I am trying to get it so that the method that creates api calls takes care of the session and token. Currently those two methods (the session and token methods) set class variables and don't return anything (well None). So my question is, is there a common design used when interfacing with sites that require tokens and sessions? Also the token and session are retrieved from a server so I can't have them run in the init method (as it would either block or may not be done before a api call is made)
A:
I find this unpythonic and ugly sense
even after initializing the class you
have to call two methods first or else
the other methods won't work.
If so, then why not put the get_session part in your class's __init__? If it always must be performed before anything else, that would seem to make sense. Of course, this means that calling the class will still return a yet-unusable instance -- that's kind of inevitable with asynchronous, event-drive programming... you don't "block until the instance is ready for use".
One possibility would be to pass the callback to perform as an argument to the class when you call it; a more Twisted-normal one would be to have Grooveshark be a function which returns a deferred (you'll add to the deferred the callback to perform, and call it with the instance as the argument when that instance is finally ready to be used).
A:
I would highly recommend looking at the Facebook graph API. Just because you need sessions and some authentication doesn't mean you can build a clean REST API. Facebook uses OAuth to handle the authentication but there are other possibilities.
| Designing a interface to a websites api | Ok I am programing a way to interface with Grooveshark (http://grooveshark.com). Right now I have a class Grooveshark and several methods, one gets a session with the server, another gets a token that is based on the session and another is used to construct api calls to the server (and other methods use that). Right now I use it like so.... Note uses twisted and t.i.defer in twisted
g = Grooveshark()
d = g.get_session()
d.addCallback(lambda x: g.get_token())
## and then something like.... ##
g.search("Song")
I find this unpythonic and ugly sense even after initializing the class you have to call two methods first or else the other methods won't work. To solve this I am trying to get it so that the method that creates api calls takes care of the session and token. Currently those two methods (the session and token methods) set class variables and don't return anything (well None). So my question is, is there a common design used when interfacing with sites that require tokens and sessions? Also the token and session are retrieved from a server so I can't have them run in the init method (as it would either block or may not be done before a api call is made)
| [
"\nI find this unpythonic and ugly sense\n even after initializing the class you\n have to call two methods first or else\n the other methods won't work.\n\nIf so, then why not put the get_session part in your class's __init__? If it always must be performed before anything else, that would seem to make sense. ... | [
3,
0
] | [] | [] | [
"python",
"twisted",
"twisted.web"
] | stackoverflow_0003445006_python_twisted_twisted.web.txt |
Q:
issue with Python Gtk+
I can't nail exactly when/what update I did on my Lucid box but now I get:
Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import gtk
/usr/lib/pymodules/python2.6/gtk-2.0/gtk/__init__.py:57: GtkWarning: could not open display
warnings.warn(str(e), _gtk.Warning)
>>>
Any hints?
UPDATED:
jldupont@server:~$ phidgets-manager
/usr/lib/pymodules/python2.6/gtk-2.0/gtk/__init__.py:57: GtkWarning: could not open display
warnings.warn(str(e), _gtk.Warning)
/usr/lib/phidgets-dbus/phidgetsdbus/apps/app_manager.py:15: GtkWarning: gtk_settings_get_for_screen: assertion `GDK_IS_SCREEN (screen)' failed
self.item_exit = gtk.MenuItem( "exit", True)
/usr/lib/phidgets-dbus/phidgetsdbus/apps/app_manager.py:15: Warning: g_object_get: assertion `G_IS_OBJECT (object)' failed
self.item_exit = gtk.MenuItem( "exit", True)
/usr/lib/phidgets-dbus/phidgetsdbus/apps/app_manager.py:18: Warning: invalid (NULL) pointer instance
self.menu = gtk.Menu()
/usr/lib/phidgets-dbus/phidgetsdbus/apps/app_manager.py:18: Warning: g_signal_connect_data: assertion `G_TYPE_CHECK_INSTANCE (instance)' failed
self.menu = gtk.Menu()
/usr/lib/phidgets-dbus/phidgetsdbus/apps/app_manager.py:50: Warning: invalid (NULL) pointer instance
self.tray=gtk.StatusIcon()
/usr/lib/phidgets-dbus/phidgetsdbus/apps/app_manager.py:50: Warning: g_signal_connect_data: assertion `G_TYPE_CHECK_INSTANCE (instance)' failed
self.tray=gtk.StatusIcon()
/usr/lib/phidgets-dbus/phidgetsdbus/apps/app_manager.py:50: GtkWarning: gdk_screen_get_root_window: assertion `GDK_IS_SCREEN (screen)' failed
self.tray=gtk.StatusIcon()
/usr/lib/phidgets-dbus/phidgetsdbus/apps/app_manager.py:50: GtkWarning: gdk_screen_get_display: assertion `GDK_IS_SCREEN (screen)' failed
self.tray=gtk.StatusIcon()
/usr/lib/phidgets-dbus/phidgetsdbus/apps/app_manager.py:50: GtkWarning: gdk_x11_display_get_xdisplay: assertion `GDK_IS_DISPLAY (display)' failed
self.tray=gtk.StatusIcon()
/usr/lib/phidgets-dbus/phidgetsdbus/apps/app_manager.py:50: GtkWarning: gdk_screen_get_number: assertion `GDK_IS_SCREEN (screen)' failed
self.tray=gtk.StatusIcon()
/usr/bin/phidgets-manager: line 10: 3899 Segmentation fault python phidgets-manager.py
A:
I manage to get rid of the problem by completely reinstalling X:
sudo apt-get remove --purge xserver-xorg
sudo apt-get install xserver-xorg
sudo dpkg-reconfigure xserver-xorg
Hope this helps someone!
| issue with Python Gtk+ | I can't nail exactly when/what update I did on my Lucid box but now I get:
Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import gtk
/usr/lib/pymodules/python2.6/gtk-2.0/gtk/__init__.py:57: GtkWarning: could not open display
warnings.warn(str(e), _gtk.Warning)
>>>
Any hints?
UPDATED:
jldupont@server:~$ phidgets-manager
/usr/lib/pymodules/python2.6/gtk-2.0/gtk/__init__.py:57: GtkWarning: could not open display
warnings.warn(str(e), _gtk.Warning)
/usr/lib/phidgets-dbus/phidgetsdbus/apps/app_manager.py:15: GtkWarning: gtk_settings_get_for_screen: assertion `GDK_IS_SCREEN (screen)' failed
self.item_exit = gtk.MenuItem( "exit", True)
/usr/lib/phidgets-dbus/phidgetsdbus/apps/app_manager.py:15: Warning: g_object_get: assertion `G_IS_OBJECT (object)' failed
self.item_exit = gtk.MenuItem( "exit", True)
/usr/lib/phidgets-dbus/phidgetsdbus/apps/app_manager.py:18: Warning: invalid (NULL) pointer instance
self.menu = gtk.Menu()
/usr/lib/phidgets-dbus/phidgetsdbus/apps/app_manager.py:18: Warning: g_signal_connect_data: assertion `G_TYPE_CHECK_INSTANCE (instance)' failed
self.menu = gtk.Menu()
/usr/lib/phidgets-dbus/phidgetsdbus/apps/app_manager.py:50: Warning: invalid (NULL) pointer instance
self.tray=gtk.StatusIcon()
/usr/lib/phidgets-dbus/phidgetsdbus/apps/app_manager.py:50: Warning: g_signal_connect_data: assertion `G_TYPE_CHECK_INSTANCE (instance)' failed
self.tray=gtk.StatusIcon()
/usr/lib/phidgets-dbus/phidgetsdbus/apps/app_manager.py:50: GtkWarning: gdk_screen_get_root_window: assertion `GDK_IS_SCREEN (screen)' failed
self.tray=gtk.StatusIcon()
/usr/lib/phidgets-dbus/phidgetsdbus/apps/app_manager.py:50: GtkWarning: gdk_screen_get_display: assertion `GDK_IS_SCREEN (screen)' failed
self.tray=gtk.StatusIcon()
/usr/lib/phidgets-dbus/phidgetsdbus/apps/app_manager.py:50: GtkWarning: gdk_x11_display_get_xdisplay: assertion `GDK_IS_DISPLAY (display)' failed
self.tray=gtk.StatusIcon()
/usr/lib/phidgets-dbus/phidgetsdbus/apps/app_manager.py:50: GtkWarning: gdk_screen_get_number: assertion `GDK_IS_SCREEN (screen)' failed
self.tray=gtk.StatusIcon()
/usr/bin/phidgets-manager: line 10: 3899 Segmentation fault python phidgets-manager.py
| [
"I manage to get rid of the problem by completely reinstalling X:\nsudo apt-get remove --purge xserver-xorg\nsudo apt-get install xserver-xorg\nsudo dpkg-reconfigure xserver-xorg\nHope this helps someone!\n"
] | [
2
] | [] | [] | [
"gtk",
"linux",
"python"
] | stackoverflow_0003436781_gtk_linux_python.txt |
Q:
mod_wsgi and pylons: setting the working environment
I'm trying to setup Pylons (1.0) with Apache mod_wsgi. Everything works fine with mod_wsgi and I can run a simple python wsgi app just fine.
I've got the quickwiki example from the Pylons site working when running it with paster, but obviously I would never deploy in such a manner - so I'm trying to get the Quickwiki example working with mod_wsgi. When I use paster to run the site, I have to source ./pylons/bin/activate and I feel like this is the "step" that is missing when trying to get it working with mod_wsgi. The ./pylons/bin/activate script is the one that was in the source when downloading pylons.
When using it with mod_wsgi, I get:
ImportError: No module named
paste.deploy
I've looked at this site but just appending the path of the pylons app doesn't do it.
I've also looked at this site, but it didn't seem to do anything significant (and
didn't solve the issue) when issuing:
import activate_workingenv
activate_workingenv.activate_workingenv(WORKING_ENV)
Looking at the sys.path after issuing source ./pylons/bin/activate shows like a dozen things added to the path, including the paster stuff and all my requirements. I'd rather not hardcode all those in the script - what am I missing here?
I'm new to Pylons and my Python skills aren't super strong, so I may be missing something really simple.
A:
Read:
http://code.google.com/p/modwsgi/wiki/VirtualEnvironments
| mod_wsgi and pylons: setting the working environment | I'm trying to setup Pylons (1.0) with Apache mod_wsgi. Everything works fine with mod_wsgi and I can run a simple python wsgi app just fine.
I've got the quickwiki example from the Pylons site working when running it with paster, but obviously I would never deploy in such a manner - so I'm trying to get the Quickwiki example working with mod_wsgi. When I use paster to run the site, I have to source ./pylons/bin/activate and I feel like this is the "step" that is missing when trying to get it working with mod_wsgi. The ./pylons/bin/activate script is the one that was in the source when downloading pylons.
When using it with mod_wsgi, I get:
ImportError: No module named
paste.deploy
I've looked at this site but just appending the path of the pylons app doesn't do it.
I've also looked at this site, but it didn't seem to do anything significant (and
didn't solve the issue) when issuing:
import activate_workingenv
activate_workingenv.activate_workingenv(WORKING_ENV)
Looking at the sys.path after issuing source ./pylons/bin/activate shows like a dozen things added to the path, including the paster stuff and all my requirements. I'd rather not hardcode all those in the script - what am I missing here?
I'm new to Pylons and my Python skills aren't super strong, so I may be missing something really simple.
| [
"Read:\nhttp://code.google.com/p/modwsgi/wiki/VirtualEnvironments\n"
] | [
3
] | [] | [] | [
"mod_wsgi",
"pylons",
"python"
] | stackoverflow_0003445174_mod_wsgi_pylons_python.txt |
Q:
Is Python good for big software projects (not web based)?
Right now I'm developing mostly in C/C++, but I wrote some small utilities in Python to automatize some tasks and I really love it as language (especially the productivity).
Except for the performances (a problem that could be sometimes solved thanks to the ease of interfacing Python with C modules), do you think it is proper for production use in the development of stand-alone complex applications (think for example to a word processor or a graphic tool)?
What IDE would you suggest? The IDLE provided with Python is not enough even for small projects in my opinion.
A:
We've used IronPython to build our flagship spreadsheet application (40kloc production code - and it's Python, which IMO means loc per feature is low) at Resolver Systems, so I'd definitely say it's ready for production use of complex apps.
There are two ways in which this might not be a useful answer to you :-)
We're using IronPython, not the more usual CPython. This gives us the huge advantage of being able to use .NET class libraries. I may be setting myself up for flaming here, but I would say that I've never really seen a CPython application that looked "professional" - so having access to the WinForms widget set was a huge win for us. IronPython also gives us the advantage of being able to easily drop into C# if we need a performance boost. (Though to be honest we have never needed to do that. All of our performance problems to date have been because we chose dumb algorithms rather than because the language was slow.) Using C# from IP is much easier than writing a C Extension for CPython.
We're an Extreme Programming shop, so we write tests before we write code. I would not write production code in a dynamic language without writing the tests first; the lack of a compile step needs to be covered by something, and as other people have pointed out, refactoring without it can be tough. (Greg Hewgill's answer suggests he's had the same problem. On the other hand, I don't think I would write - or especially refactor - production code in any language these days without writing the tests first - but YMMV.)
Re: the IDE - we've been pretty much fine with each person using their favourite text editor; if you prefer something a bit more heavyweight then WingIDE is pretty well-regarded.
A:
You'll find mostly two answers to that – the religous one (Yes! Of course! It's the best language ever!) and the other religious one (you gotta be kidding me! Python? No... it's not mature enough). I will maybe skip the last religion (Python?! Use Ruby!). The truth, as always, is far from obvious.
Pros: it's easy, readable, batteries included, has lots of good libraries for pretty much everything. It's expressive and dynamic typing makes it more concise in many cases.
Cons: as a dynamic language, has way worse IDE support (proper syntax completion requires static typing, whether explicit in Java or inferred in SML), its object system is far from perfect (interfaces, anyone?) and it is easy to end up with messy code that has methods returning either int or boolean or object or some sort under unknown circumstances.
My take – I love Python for scripting, automation, tiny webapps and other simple well defined tasks. In my opinion it is by far the best dynamic language on the planet. That said, I would never use it any dynamically typed language to develop an application of substantial size.
Say – it would be fine to use it for Stack Overflow, which has three developers and I guess no more than 30k lines of code. For bigger things – first your development would be super fast, and then once team and codebase grow things are slowing down more than they would with Java or C#. You need to offset lack of compilation time checks by writing more unittests, refactorings get harder cause you never know what your refacoring broke until you run all tests or even the whole big app, etc.
Now – decide on how big your team is going to be and how big the app is supposed to be once it is done. If you have 5 or less people and the target size is roughly Stack Overflow, go ahead, write in Python. You will finish in no time and be happy with good codebase. But if you want to write second Google or Yahoo, you will be much better with C# or Java.
Side-note on C/C++ you have mentioned: if you are not writing performance critical software (say massive parallel raytracer that will run for three months rendering a film) or a very mission critical system (say Mars lander that will fly three years straight and has only one chance to land right or you lose $400mln) do not use it. For web apps, most desktop apps, most apps in general it is not a good choice. You will die debugging pointers and memory allocation in complex business logic.
A:
In my opinion python is more than ready for developing complex applications. I see pythons strength more on the server side than writing graphical clients. But have a look at http://www.resolversystems.com/. They develop a whole spreadsheet in python using the .net ironpython port.
If you are familiar with eclipse have a look at pydev which provides auto-completion and debugging support for python with all the other eclipse goodies like svn support. The guy developing it has just been bought by aptana, so this will be solid choice for the future.
@Marcin
Cons: as a dynamic language, has way
worse IDE support (proper syntax
completion requires static typing,
whether explicit in Java or inferred
in SML),
You are right, that static analysis may not provide full syntax completion for dynamic languages, but I thing pydev gets the job done very well. Further more I have a different development style when programming python. I have always an ipython session open and with one F5 I do not only get the perfect completion from ipython, but object introspection and manipulation as well.
But if you want to write second Google
or Yahoo, you will be much better with
C# or Java.
Google just rewrote jaiku to work on top of App Engine, all in python. And as far as I know they use a lot of python inside google too.
A:
I really like python, it's usually my language of choice these days for small (non-gui) stuff that I do on my own.
However, for some larger Python projects I've tackled, I'm finding that it's not quite the same as programming in say, C++. I was working on a language parser, and needed to represent an AST in Python. This is certainly within the scope of what Python can do, but I had a bit of trouble with some refactoring. I was changing the representation of my AST and changing methods and classes around a lot, and I found I missed the strong typing that would be available to me in a C++ solution. Python's duck typing was almost too flexible and I found myself adding a lot of assert code to try to check my types as the program ran. And then I couldn't really be sure that everything was properly typed unless I had 100% code coverage testing (which I didn't at the time).
Actually, that's another thing that I miss sometimes. It's possible to write syntactically correct code in Python that simply won't run. The compiler is incapable of telling you about it until it actually executes the code, so in infrequently-used code paths such as error handlers you can easily have unseen bugs lurking around. Even code that's as simple as printing an error message with a % format string can fail at runtime because of mismatched types.
I haven't used Python for any GUI stuff so I can't comment on that aspect.
A:
Python is considered (among Python programmers :) to be a great language for rapid prototyping. There's not a lot of extraneous syntax getting in the way of your thought processes, so most of the work you do tends to go into the code. (There's far less idioms required to be involved in writing good Python code than in writing good C++.)
Given this, most Python (CPython) programmers ascribe to the "premature optimization is the root of all evil" philosophy. By writing high-level (and significantly slower) Python code, one can optimize the bottlenecks out using C/C++ bindings when your application is nearing completion. At this point it becomes more clear what your processor-intensive algorithms are through proper profiling. This way, you write most of the code in a very readable and maintainable manner while allowing for speedups down the road. You'll see several Python library modules written in C for this very reason.
Most graphics libraries in Python (i.e. wxPython) are just Python wrappers around C++ libraries anyway, so you're pretty much writing to a C++ backend.
To address your IDE question, SPE (Stani's Python Editor) is a good IDE that I've used and Eclipse with PyDev gets the job done as well. Both are OSS, so they're free to try!
[Edit] @Marcin: Have you had experience writing > 30k LOC in Python? It's also funny that you should mention Google's scalability concerns, since they're Python's biggest supporters! Also a small organization called NASA also uses Python frequently ;) see "One coder and 17,000 Lines of Code Later".
A:
Nothing to add to the other answers, besides that if you choose python you must use something like pylint which nobody mentioned so far.
A:
One way to judge what python is used for is to look at what products use python at the moment. This wikipedia page has a long list including various web frameworks, content management systems, version control systems, desktop apps and IDEs.
As it says here - "Some of the largest projects that use Python are the Zope application server, YouTube, and the original BitTorrent client. Large organizations that make use of Python include Google, Yahoo!, CERN and NASA. ITA uses Python for some of its components."
So in short, yes, it is "proper for production use in the development of stand-alone complex applications". So are many other languages, with various pros and cons. Which is the best language for your particular use case is too subjective to answer, so I won't try, but often the answer will be "the one your developers know best".
A:
Refactoring is inevitable on larger codebases and the lack of static typing makes this much harder in python than in statically typed languages.
A:
And as far as I know they use a lot of python inside google too.
Well i'd hope so, the maker of python still works at google if i'm not mistaken?
As for the use of Python, i think it's a great language for stand-alone apps. It's heavily used in a lot of Linux programs, and there are a few nice widget sets out there to aid in the development of GUI's.
A:
Python is a delight to use. I use it routinely and also write a lot of code for work in C#. There are two drawbacks to writing UI code in Python. one is that there is not a single ui framework that is accepted by the majority of the community. when you write in c# the .NET runtime and class libraries are all meant to work together. With Python every UI library has at's own semantics which are often at odds with the pythonic mindset in which you are trying to write your program. I am not blaming the library writers. I've tried several libraries (wxwidgets, PythonWin[Wrapper around MFC], Tkinter), When doing so I often felt that I was writing code in a language other than Python (despite the fact that it was python) because the libraries aren't exactly pythonic they are a port from another language be it c, c++, tk.
So for me I will write UI code in .NET (for me C#) because of the IDE & the consistency of the libraries. But when I can I will write business logic in python because it is more clear and more fun.
A:
I know I'm probably stating the obvious, but don't forget that the quality of the development team and their familiarity with the technology will have a major impact on your ability to deliver.
If you have a strong team, then it's probably not an issue if they're familiar. But if you have people who are more 9 to 5'rs who aren't familiar with the technology, they will need more support and you'd need to make a call if the productivity gains are worth whatever the cost of that support is.
A:
I had only one python experience, my trash-cli project.
I know that probably some or all problems depends of my inexperience with python.
I found frustrating these things:
the difficult of finding a good IDE for free
the limited support to automatic refactoring
Moreover:
the need of introduce two level of grouping packages and modules confuses me.
it seems to me that there is not a widely adopted code naming convention
it seems to me that there are some standard library APIs docs that are incomplete
the fact that some standard libraries are not fully object oriented annoys me
Although some python coders tell me that they does not have these problems, or they say these are not problems.
A:
Try Django or Pylons, write a simple app with both of them and then decide which one suits you best. There are others (like Turbogears or Werkzeug) but those are the most used.
| Is Python good for big software projects (not web based)? | Right now I'm developing mostly in C/C++, but I wrote some small utilities in Python to automatize some tasks and I really love it as language (especially the productivity).
Except for the performances (a problem that could be sometimes solved thanks to the ease of interfacing Python with C modules), do you think it is proper for production use in the development of stand-alone complex applications (think for example to a word processor or a graphic tool)?
What IDE would you suggest? The IDLE provided with Python is not enough even for small projects in my opinion.
| [
"We've used IronPython to build our flagship spreadsheet application (40kloc production code - and it's Python, which IMO means loc per feature is low) at Resolver Systems, so I'd definitely say it's ready for production use of complex apps.\nThere are two ways in which this might not be a useful answer to you :-)\... | [
34,
23,
18,
13,
8,
5,
4,
3,
1,
1,
0,
0,
0
] | [] | [] | [
"ide",
"python"
] | stackoverflow_0000035753_ide_python.txt |
Q:
How do I get this page programatically?
Here is the page THE LINK TO LYRICS SITE
If I use normal method, all I get is the "http://lyricsvip.com" and not the lyrics.
A:
it's because the lyrics are loaded by Javascript and the 'normal' method doesn't execute Javascript when you try to scrape the page.
Seems like you're out of luck unfortunately, unless you manage to execute the Javascript-method found in the source:
<body onload="javascript:getContent('aerosmith', 'crazy', '1281384888', '0475352e376cf1c3906afd8ec1b8ac70')">
Which I'm pretty sure you wont be able to, since it's probably put there to prevent just that.. :)
A:
If you really want to do this, it is possible. You will need to control something like Gecko (using e.g. pywebkigtk) to open the web page up in a full browser that can execute JS, and then get the source code from that once it's finished rendering.
However, you won't be able to do it with any less than that. If you look at the Javascript source, you'll see that it just makes an AJAX POST request to content.php:
var url = "content.php?artist=" + artist + "&title=" + title + "&time=" + time + "&check=" + check;
with check, probably a hashed session ID. This is undoubtedly there to stop people doing exactly what you are doing.
A:
if you're on Windows, you could use PAMIE to drive a browser....
| How do I get this page programatically? | Here is the page THE LINK TO LYRICS SITE
If I use normal method, all I get is the "http://lyricsvip.com" and not the lyrics.
| [
"it's because the lyrics are loaded by Javascript and the 'normal' method doesn't execute Javascript when you try to scrape the page.\nSeems like you're out of luck unfortunately, unless you manage to execute the Javascript-method found in the source:\n<body onload=\"javascript:getContent('aerosmith', 'crazy', '128... | [
4,
1,
0
] | [] | [] | [
"ajax",
"fetch",
"html",
"python",
"webpage"
] | stackoverflow_0003443769_ajax_fetch_html_python_webpage.txt |
Q:
Intentionally Buggy Code (Python)
This is a strange request but I'm looking for buggy Python code. I want to learn more about bugs and debuggers and I need some buggy code to work with. Unfortunately, all the code I've written is short and bug-free (so far).
Preferably it's not GUI stuff (b/c I'm just starting to learn it) but anything's good.
Thanks in advance
A:
Not sure how to scout "intentionally" for source code with bugs but you can look into the bug trackers of the main Python projects (and the less widespread ones, too), look for the bugs the reports refer to and debug them. It's a win-win situation. You win the skill to debug and they (hopefully) win a patch for the bug :-)
A:
Debugging is 70% about finding and figuring out the bug from reports of anomalies before you can do anything about it, and 30% about figuring out how not to take the castle of cards down when fixing it.
If you have it pointed out in the code for you, or are just given code and you're told it's buggy, you're in a worse place than where you started.
Lawrence's comment is spot on IMO, go hunt down something that's been tracked and logged and you have rero steps for in a project where you have realistic constraints and enough codebase to work with if you want this exercise to have any meaning.
Will double as good exercise in learning to read too when you have to puzzle out an alien code base too.
A:
Here's a nice example, spot the bug ;)
Just a bit of code that bit me a couple of years ago.
methods = []
for i in range(10):
methods.append(lambda x: x + i)
print methods[0](10)
| Intentionally Buggy Code (Python) | This is a strange request but I'm looking for buggy Python code. I want to learn more about bugs and debuggers and I need some buggy code to work with. Unfortunately, all the code I've written is short and bug-free (so far).
Preferably it's not GUI stuff (b/c I'm just starting to learn it) but anything's good.
Thanks in advance
| [
"Not sure how to scout \"intentionally\" for source code with bugs but you can look into the bug trackers of the main Python projects (and the less widespread ones, too), look for the bugs the reports refer to and debug them. It's a win-win situation. You win the skill to debug and they (hopefully) win a patch for ... | [
6,
0,
0
] | [] | [] | [
"code_snippets",
"debugging",
"python"
] | stackoverflow_0003445429_code_snippets_debugging_python.txt |
Q:
Python/Django download Image from URL, modify, and save to ImageField
I've been looking for a way to download an image from a URL, preform some image manipulations (resize) actions on it, and then save it to a django ImageField. Using the two great posts (linked below), I have been able to download and save an image to an ImageField. However, I've been having some trouble manipulating the file once I have it.
Specifically, the model field save() method requires a File() object as the second parameter. So my data has to eventually be a File() object. The blog posts linked below show how to use urllib2 to save your an image URL into a File() object. This is great, however, I also want to manipulate the image using PIL as an Image() object. (or ImageFile object).
My preferred approach would be then to load the image URL directly into an Image() object, preform the resize, and convert it to a File() object and then save it in the model. However, my attempts to convert an Image() to a File() have failed. If at all possible, I want to limit the number of times I write to the disk, so I'd like to do this object transformation in Memory or using a NamedTemporaryFile(delete=True) object so I don't have to worry about extra files laying around. (Of course, I want the file to be written to disk once it is saved via the model).
import urllib2
from PIL import Image, ImageFile
from django.core.files import File
from django.core.files.temp import NamedTemporaryFile
inStream = urllib2.urlopen('http://www.google.com/intl/en_ALL/images/srpr/logo1w.png')
parser = ImageFile.Parser()
while True:
s = inStream.read(1024)
if not s:
break
parser.feed(s)
inImage = parser.close()
# convert to RGB to avoid error with png and tiffs
if inImage.mode != "RGB":
inImage = inImage.convert("RGB")
# resize could occur here
# START OF CODE THAT DOES NOT SEEM TO WORK
# I need to somehow convert an image .....
img_temp = NamedTemporaryFile(delete=True)
img_temp.write(inImage.tostring())
img_temp.flush()
file_object = File(img_temp)
# .... into a file that the Django object will accept.
# END OF CODE THAT DOES NOT SEEM TO WORK
my_model_instance.image.save(
'some_filename',
file_object, # this must be a File() object
save=True,
)
With this approach, the file appears corrupt whenever I view it as an image. Does anyone have any approach that takes a file file from a URL, allows one to manipulate it as an Image and then save it to a Django ImageField?
Any help is much appreciated.
Programmatically saving image to Django ImageField
Django: add image in an ImageField from image url
Update 08/11/2010: I did end up going with StringIO, however, I was stringIO was throwing an unusual Exception when I tried to save it in a Django ImageField. Specifically, the stack trace showed a name error:
"AttribueError exception "StringIO instance has no attribute 'name'"
After digging through the Django source, it looks like this error was caused when the model save tries to access the size attribute of the StringIO "File". (Though the error above indicates a problem with the name, the root cause of this error appears to be the lack of a size property on the StringIO image). As soon as I assigned a value to the size attribute of the image file, it worked fine.
A:
In an attempt to kill 2 birds with 1 stone. Why not use a (c)StringIO object instead of a NamedTemporaryFile? You won't have to store it on disk anymore and I know for a fact that something like this works (I use similar code myself).
from cStringIO import StringIO
img_temp = StringIO()
inImage.save(img_temp, 'PNG')
img_temp.seek(0)
file_object = File(img_temp, filename)
| Python/Django download Image from URL, modify, and save to ImageField | I've been looking for a way to download an image from a URL, preform some image manipulations (resize) actions on it, and then save it to a django ImageField. Using the two great posts (linked below), I have been able to download and save an image to an ImageField. However, I've been having some trouble manipulating the file once I have it.
Specifically, the model field save() method requires a File() object as the second parameter. So my data has to eventually be a File() object. The blog posts linked below show how to use urllib2 to save your an image URL into a File() object. This is great, however, I also want to manipulate the image using PIL as an Image() object. (or ImageFile object).
My preferred approach would be then to load the image URL directly into an Image() object, preform the resize, and convert it to a File() object and then save it in the model. However, my attempts to convert an Image() to a File() have failed. If at all possible, I want to limit the number of times I write to the disk, so I'd like to do this object transformation in Memory or using a NamedTemporaryFile(delete=True) object so I don't have to worry about extra files laying around. (Of course, I want the file to be written to disk once it is saved via the model).
import urllib2
from PIL import Image, ImageFile
from django.core.files import File
from django.core.files.temp import NamedTemporaryFile
inStream = urllib2.urlopen('http://www.google.com/intl/en_ALL/images/srpr/logo1w.png')
parser = ImageFile.Parser()
while True:
s = inStream.read(1024)
if not s:
break
parser.feed(s)
inImage = parser.close()
# convert to RGB to avoid error with png and tiffs
if inImage.mode != "RGB":
inImage = inImage.convert("RGB")
# resize could occur here
# START OF CODE THAT DOES NOT SEEM TO WORK
# I need to somehow convert an image .....
img_temp = NamedTemporaryFile(delete=True)
img_temp.write(inImage.tostring())
img_temp.flush()
file_object = File(img_temp)
# .... into a file that the Django object will accept.
# END OF CODE THAT DOES NOT SEEM TO WORK
my_model_instance.image.save(
'some_filename',
file_object, # this must be a File() object
save=True,
)
With this approach, the file appears corrupt whenever I view it as an image. Does anyone have any approach that takes a file file from a URL, allows one to manipulate it as an Image and then save it to a Django ImageField?
Any help is much appreciated.
Programmatically saving image to Django ImageField
Django: add image in an ImageField from image url
Update 08/11/2010: I did end up going with StringIO, however, I was stringIO was throwing an unusual Exception when I tried to save it in a Django ImageField. Specifically, the stack trace showed a name error:
"AttribueError exception "StringIO instance has no attribute 'name'"
After digging through the Django source, it looks like this error was caused when the model save tries to access the size attribute of the StringIO "File". (Though the error above indicates a problem with the name, the root cause of this error appears to be the lack of a size property on the StringIO image). As soon as I assigned a value to the size attribute of the image file, it worked fine.
| [
"In an attempt to kill 2 birds with 1 stone. Why not use a (c)StringIO object instead of a NamedTemporaryFile? You won't have to store it on disk anymore and I know for a fact that something like this works (I use similar code myself).\nfrom cStringIO import StringIO\nimg_temp = StringIO()\ninImage.save(img_temp, '... | [
5
] | [] | [] | [
"django",
"file",
"python",
"python_imaging_library",
"urllib2"
] | stackoverflow_0003445568_django_file_python_python_imaging_library_urllib2.txt |
Q:
Are there Python statical analysis/validation tools?
I've never been a huge Python fan. I learned it for a course where the teacher was really into it, but his enthusiasm never quite made it to the rest of our class it seems: as soon as we had the chance, we all jumped off to C#/Java.
Anyways. This wasn't a concluding experience, and what annoyed me the most in the language was that to find out if Python code would work, you actually have to execute it, and risk dying halfway through because of something stupid like a typo in a variable name (throwing up a NameError). Stuff that compilers for compiled languages catch at the very first glance, but that Python won't bother to complain about until it's too late. (I know you can always die half through a test with compiled programs too, but at least it won't be from a typo.)
I'm not really giving it a second chance yet, but for the sake of the next students, are there Python statical analysis or validation tools out there that would catch most errors (I understand you can't catch them all) compilers would catch at compile-time?
A:
"but that Python won't bother to complain about until it's too late"
It's not that the message comes too late. It's that you're waiting too long to use Python. Don't type a mountain of code and then complain that one small piece is bad.
Use Unit Testing. Write less code before running a test.
Use python Interactively to experiment. You can do most statistical processing from the >>> prompt.
Don't write long, main-program-like scripts. Write short scripts -- in small pieces -- and test the small pieces.
A:
Take a look at the following programs:
pylint
pyflakes
pychecker
A:
In addition to the ones mentioned by ars.
Try Pydev, it has static code analysis build-in. Or Pida which has a couple of different static analysis tools available.
Or if you are looking for a standalone library, try Rope
| Are there Python statical analysis/validation tools? | I've never been a huge Python fan. I learned it for a course where the teacher was really into it, but his enthusiasm never quite made it to the rest of our class it seems: as soon as we had the chance, we all jumped off to C#/Java.
Anyways. This wasn't a concluding experience, and what annoyed me the most in the language was that to find out if Python code would work, you actually have to execute it, and risk dying halfway through because of something stupid like a typo in a variable name (throwing up a NameError). Stuff that compilers for compiled languages catch at the very first glance, but that Python won't bother to complain about until it's too late. (I know you can always die half through a test with compiled programs too, but at least it won't be from a typo.)
I'm not really giving it a second chance yet, but for the sake of the next students, are there Python statical analysis or validation tools out there that would catch most errors (I understand you can't catch them all) compilers would catch at compile-time?
| [
"\n\"but that Python won't bother to complain about until it's too late\"\n\nIt's not that the message comes too late. It's that you're waiting too long to use Python. Don't type a mountain of code and then complain that one small piece is bad.\n\nUse Unit Testing. Write less code before running a test.\nUse pyt... | [
7,
6,
1
] | [] | [] | [
"python",
"validation"
] | stackoverflow_0003445726_python_validation.txt |
Q:
Key commands in Tkinter
I made a GUI with Tkinter, now how do I make it so when a key command will execute a command even if the Tkinter window is not in focus? Basically I want it so everything is bound to that key command.
Example:
Say I was browsing the internet and the focus was on my browser, I then type Ctrl + U. An event would then run on my program.
A:
Tkinter, on its own, cannot grab keystrokes that (from the OS's/WM's viewpoint) were directed to other, unrelated windows -- you'll need to instruct your window manager, desktop manager, or "operating system", to direct certain keystrokes differently than it usually does. So, what platform do you need to support for this functionality? Each platform has different ways to perform this kind of functionality, of course.
| Key commands in Tkinter | I made a GUI with Tkinter, now how do I make it so when a key command will execute a command even if the Tkinter window is not in focus? Basically I want it so everything is bound to that key command.
Example:
Say I was browsing the internet and the focus was on my browser, I then type Ctrl + U. An event would then run on my program.
| [
"Tkinter, on its own, cannot grab keystrokes that (from the OS's/WM's viewpoint) were directed to other, unrelated windows -- you'll need to instruct your window manager, desktop manager, or \"operating system\", to direct certain keystrokes differently than it usually does. So, what platform do you need to suppor... | [
2
] | [] | [] | [
"binding",
"python",
"tkinter"
] | stackoverflow_0003445867_binding_python_tkinter.txt |
Q:
Calling a Python module from Perl
I created a module in Python which provides about a dozen functionalities. While it will be mostly used from within Python, there is a good fraction of legacy users which will be calling it from Perl.
What is the best way to make a plug in to this module? My thoughts are:
Provide the functionalities as command line utilities and make system calls
Create some sort of server and handle RPC calls (say, via JSON RPC)
Any advise?
A:
One other choice is to inline Python directly in your Perl script, using Inline::Python.
This may be simpler than other solutions, and only requires one additional module.
A:
In the short run the easiest solution is to use Inline::Python. Closely followed by calling a command-line script.
In the long run, using a server to provide RPC functionality or simply calling a command-line script will give you the most future proof solution.
Why?
Becuase that way you aren't tied to Perl or Python as the language used to build the systems that consume the services provided by your library. Either method creates a clear, language independent interface that you can use with whatever development environment you adopt.
Depending on your needs any of the presented options may be the "best choice". Depending on how your needs evolve over time, a different choice may be revealed as "best".
My approach to this would be to ask a couple of questions:
How often do you change development tools. You've switched to Python from Perl. Did you start with Tcl and go to Perl? Are you going to switch to the exciting new language X in 1, 5 or 10 years? If you change tools 'often' (whatever that means) emphasize cross tool compatibility.
How fast is fast enough? Is the start up time for command line solutions ok? Does Inline::Python slow things down too much (you are still initializing a Python interpreter, it's just embedded in your Perl interpreter)?
Based on the answers to these questions, I would do the simplest thing that is likely to work.
My guess is that means in order:
Inline::Python
Command line scripts
Build an RPC server
A:
Provide the functionalities as command line utilities and make system calls
Works really nicely. This is the way programs like Python (and Perl) are meant to use used.
| Calling a Python module from Perl | I created a module in Python which provides about a dozen functionalities. While it will be mostly used from within Python, there is a good fraction of legacy users which will be calling it from Perl.
What is the best way to make a plug in to this module? My thoughts are:
Provide the functionalities as command line utilities and make system calls
Create some sort of server and handle RPC calls (say, via JSON RPC)
Any advise?
| [
"One other choice is to inline Python directly in your Perl script, using Inline::Python.\nThis may be simpler than other solutions, and only requires one additional module.\n",
"In the short run the easiest solution is to use Inline::Python. Closely followed by calling a command-line script.\nIn the long run, u... | [
19,
9,
3
] | [] | [] | [
"interop",
"perl",
"python"
] | stackoverflow_0003441766_interop_perl_python.txt |
Q:
Edit ini file option values with ConfigParser (Python)
Anyone know how'd I'd go about editing ini file values preferably using ConfigParser? (Or even a place to start from would be great!) I've got lots of comments throughout my config file so I'd like to keep them by just editing the values, not taking the values and playing around with multiple files.
Structure of my config file:
[name1]
URL = http://example.com
username = dog
password = password
[name2]
URL = http://catlover.com
username = cat
password = adffa
As you can see, I've got the same options for different section names, so editing just the values for one section is a bit trickier if ConfigParser can't do it.
Thanks in advance.
A:
Here is an example
import sys
import os.path
from ConfigParser import RawConfigParser as ConfParser
from ConfigParser import Error
p = ConfParser()
# this happend to me save as ASCII
o = open("config.ini")
if o.read().startswith("\xef\xbb\xbf"):
print "Fatal Error; Please save the file as ASCII not unicode."
sys.exit()
try:
results = p.read("config.ini")
except Error, msg:
print "Error Parsing File"
print msg
else:
if results == []:
print "Could not load config.ini."
if not os.path.exists("config.ini"):
print "config.ini does not exist."
else:
print "An uknown error occurred."
else:
print "Config Details"
sections = p.sections()
sections.sort()
for s in sections:
print "------------------------"
print s
if p.has_option(s, "URL"):
print "URL: ",
print p.get(s, "URL")
else:
print "URL: No Entry"
if p.has_option(s, "username"):
print "User: ",
print p.get(s, "username")
else:
print "User: N/A"
if p.has_option(s, "password"):
print "Password: ",
print p.get(s, "password")
else:
print "Password: N/A"
Also I created this class to store my apps variables etc and also make config writing easier it was originally used with twisted but I created a simple replacement logger
import os.path
import sys
#from twisted.python import log
import ConfigParser
from traceback import print_last
class Log(object):
def msg(t):
print "Logger: %s " % t
def err(t = None):
print "-------------Error-----------"
print "\n\n"
if t is None:
print_last()
# sloppy replacement for twisted's logging functions
log = Log()
class Settings(object):
'''Stores settings'''
config_variables = ['variables_that_should_be_stored_in_config']
def __init__(self, main_folder = None, log_file = None, music_folder = None ):
# load the defaults then see if there are updates ones in the config
self.load_defaults()
self.config = ConfigParser.RawConfigParser()
if len(self.config.read(self.settings_file)) == 1:
if 'Settings' in self.config.sections():
try:
self.music_folder = self.config.get('Settings', 'music_folder')
except ConfigParser.NoOptionError:
pass
log.msg('Music Folder: %s' % self.music_folder)
try:
self.mplayer = self.config.get('Settings', 'mplayer')
except ConfigParser.NoOptionError:
pass
try:
self.eula = self.config.getboolean('Settings', 'eula')
except ConfigParser.NoOptionError:
pass
else:
log.msg('No Settings Section; Defaults Loaded')
else:
log.msg('Settings at default')
def load_defaults(self):
log.msg('Loading Defaults')
self.main_folder = os.path.dirname(os.path.abspath(sys.argv[0]))
self.settings_file = os.path.join(self.main_folder, 'settings.cfg')
self.log_file = os.path.join(self.main_folder, 'grooveshark.log')
self.music_folder = os.path.join(self.main_folder, 'Music')
self.grooveshark_started = False
self.eula = False
self.download_percent = 0.5# default buffer percent is 50 %
if sys.platform == 'win32' or sys.platform == 'cygwin':# Windows
if os.path.exists( os.path.join(self.main_folder, 'mplayer', 'mplayer.exe') ):
self.mplayer = os.path.join(self.main_folder, 'mplayer', 'mplayer.exe')
elif os.path.exists( os.path.join(self.main_folder, '/mplayer.exe') ):
self.mplayer = os.path.join(self.main_folder, '/mplayer.exe')
else:
self.mplayer = 'download'
elif sys.platform == 'darwin':# Mac
if os.path.exists( os.path.join(self.main_folder, 'mplayer/mplayer.app') ):
self.mplayer = os.path.join(self.main_folder, 'mplayer/mplayer.app')
elif os.path.exists( os.path.join(self.main_folder, '/mplayer.app') ):
self.mplayer = os.path.join(self.main_folder, '/mplayer.app')
else:
self.mplayer = 'download'
else:# linux
# download or navigate to it
self.mplayer = 'download'
# Create Music Folder if it does not exist
if not os.path.exists(self.music_folder):
os.makedirs(self.music_folder)
# Create log file if it does not exist
if not os.path.exists(self.log_file):
l = open(self.log_file, 'wb')
l.close()
log.msg('Application Folder: %s' % self.main_folder)
log.msg('Log File: %s' % self.log_file)
log.msg('Music Folder: %s' % self.music_folder)
def __setattr__(self, variable, value):
log.msg('Setting %s to %s' % (variable, value))
object.__setattr__(self, variable, value)
if variable in self.config_variables:
try:
self.config.set('Settings', variable, value)
except:
# Means config wasn't created then, could be we were trying to set self.config (in which case self.config wasn't set yet because we were trying to set it)
log.err()
else:
# UPDATE settings file
log.msg('Saving Settings to %s' % (self.settings_file))
try:
self.config.write( open(self.settings_file, 'wb') )
except:
log.err()
| Edit ini file option values with ConfigParser (Python) | Anyone know how'd I'd go about editing ini file values preferably using ConfigParser? (Or even a place to start from would be great!) I've got lots of comments throughout my config file so I'd like to keep them by just editing the values, not taking the values and playing around with multiple files.
Structure of my config file:
[name1]
URL = http://example.com
username = dog
password = password
[name2]
URL = http://catlover.com
username = cat
password = adffa
As you can see, I've got the same options for different section names, so editing just the values for one section is a bit trickier if ConfigParser can't do it.
Thanks in advance.
| [
"Here is an example\nimport sys\nimport os.path\nfrom ConfigParser import RawConfigParser as ConfParser\nfrom ConfigParser import Error\n\np = ConfParser()\n# this happend to me save as ASCII\no = open(\"config.ini\")\nif o.read().startswith(\"\\xef\\xbb\\xbf\"):\n print \"Fatal Error; Please save the file as AS... | [
2
] | [] | [] | [
"configparser",
"ini",
"python"
] | stackoverflow_0003446034_configparser_ini_python.txt |
Q:
Is it possible to write an IM server in python? (be able to handle the heavy connections)
i wanna write an IM server in python, but i'm not sure if python can handle the heavy connections?
Thanks in advance.
A:
Omegle is written in Python and as of writing is sustaining 7,057 concurrent online users.
It's not so much about the choice of language, but the efficiency of your code and how well it is optimized.
while true:
# nothing
isn't going to be any slower than
while (1) ;
A:
Yes, you could :)
For example: SecondLife has written a library to support non-blocking IO, you can find it at: http://eventlet.net/
The beauty of Python is, you can optimize the code when it's needed. If some part of your code is executed a lot you can simply replace it with a C function to speed up your entire program without much effort.
A:
gevent is a Python network library based on libevent that is capable of handling thousands of connections. Read the introduction here.
| Is it possible to write an IM server in python? (be able to handle the heavy connections) | i wanna write an IM server in python, but i'm not sure if python can handle the heavy connections?
Thanks in advance.
| [
"Omegle is written in Python and as of writing is sustaining 7,057 concurrent online users.\nIt's not so much about the choice of language, but the efficiency of your code and how well it is optimized.\nwhile true:\n # nothing\n\nisn't going to be any slower than\nwhile (1) ;\n\n",
"Yes, you could :)\nFor exam... | [
2,
2,
1
] | [] | [] | [
"instant_messaging",
"python"
] | stackoverflow_0002542718_instant_messaging_python.txt |
Q:
Python: Is it possible to have multiple exceptions statments for a try block?
try:
case_no = re.search("Case Number:</span></td><td><span class=\"Value\">([^<]*?)<",br.response().read()).group(1)
except:
try:
try:
case_no = re.search("Citation Number:</span></td><td><span class=\"Value\">([^<]*?)<",br.response().read()).group(1)
except:
case_no = re.search("Citation Number:</span></td><td><span class=\"Value\">([^<]*?)<",br.response().read()).group(1)
except:
case_no = "N/A"
As you can see the above code is quite clumsy. I want to know if there is any way I can do like this.
try:
XYZ
except:
DOXYZ
except:
DOXYZ
Basically I want to be able to use - "try X if exception then try Y if exception then try Z" without nesting too much statemtns.
A:
Probably you shouldn't be checking exception at all?
patterns = [
"Case Number:</span></td><td><span class=\"Value\">([^<]*?)<",
"Citation Number:</span></td><td><span class=\"Value\">([^<]*?)<",
"Citation Number:</span></td><td><span class=\"Value\">([^<]*?)<" # same as #2?
]
text = br.response().read()
case_no = "N/A"
for pattern in patterns:
res = re.search(pattern, text)
if res:
case_no = res.group(1)
break
A:
Yes, it is posible, as long as you define exception condition...
Like:
try:
f = open('myfile.txt')
s = f.readline()
i = int(s.strip())
except IOError as (errno, strerror):
print "I/O error({0}): {1}".format(errno, strerror)
except ValueError:
print "Could not convert data to an integer."
except:
print "Unexpected error:", sys.exc_info()[0]
raise
But, you must define the exception type.
A:
A common idiom for the behavior you're looking for is something like:
try: foo()
except: pass
try: bar()
except: pass
But you should always catch a specific exception and make sure it makes sense. In your case it simply doesn't make sense - to see if the regular expression matched, test the result for None:
r = br.response().read()
PATTERN1="..."
PATTERN2="..."
PATTERN3="..."
mo = re.search(PATTERN1, r) or re.search(PATTERN2, r) or re.search(PATTERN3, r)
case_no = mo.group(1) if mo else "N/A"
For performance reasons you can precompile your regexes:
RE1 = re.compile("...")
RE2 = re.compile("...")
RE3 = re.compile("...")
mo = RE1.search(r) or RE2.search(r) or RE3.search(r)
Also, for your specific regex patterns you can easily combine them into one, and using a named group can help readability:
pat = r"""(Case|Citation) Number:</span></td><td><span class="Value">(?P<case_no>[^<]*?)<"""
mo = re.search(pat, r)
case_no = mo.group("case_no") if mo else "N/A"
And finally, using regular expressions to parse HTML is the road to disaster, consider using HTMLParser from the standard lib or Beautiful Soup.
A:
No, it is not possible to do what you want. the semantics of multiple except clauses covers catching different types of exceptions that may be thrown from the same block of code. You must nest the statements or rethink your code to get the desired results.
This might be a case where it would be better to test for the preconditions that you expect to cause an exception.
if test1():
#dox
elif test2():
#doy
elif test3():
#doz
etc.
I would also recommend against using catchall except: phrases except in very specialized circumstances where you know you need them.
A:
If you're doing the same or a similar thing in every try/except block, you might use a loop
case_no = "N/A"
for _ in range(3):
try:
case_no = re.search("Case Number:</span></td><td><span class=\"Value\">([^<]*?)<",br.response().read()).group(1)
break
except SomeExplicitlyCaughtExceptions:
pass
Of course it makes no sense in this form, because trying the same thing three times will yield the same result.
A:
You'd be better off restructuring your code:
success = False
for _ in xrange(MAX_ATTEMPTS):
try:
XYZ
success = True
break
except:
pass
if not success:
DOXYZ
It's better to explicitly specify the exception, though. Do you really want to catch KeyboardInterrupts?
A:
I'd avoid the exceptions if I were doing this:
count = 3
caseRe = re.compile("Case Number:</span></td><td><span class=\"Value\">([^<]*?)<")
while count > 0:
text = br.response().read()
mo = caseRe.search(text)
if mo is None:
count -= 1
continue
case_no = mo.group(1)
break
if count == 0:
case_no = "N/A"
| Python: Is it possible to have multiple exceptions statments for a try block? | try:
case_no = re.search("Case Number:</span></td><td><span class=\"Value\">([^<]*?)<",br.response().read()).group(1)
except:
try:
try:
case_no = re.search("Citation Number:</span></td><td><span class=\"Value\">([^<]*?)<",br.response().read()).group(1)
except:
case_no = re.search("Citation Number:</span></td><td><span class=\"Value\">([^<]*?)<",br.response().read()).group(1)
except:
case_no = "N/A"
As you can see the above code is quite clumsy. I want to know if there is any way I can do like this.
try:
XYZ
except:
DOXYZ
except:
DOXYZ
Basically I want to be able to use - "try X if exception then try Y if exception then try Z" without nesting too much statemtns.
| [
"Probably you shouldn't be checking exception at all? \npatterns = [\n \"Case Number:</span></td><td><span class=\\\"Value\\\">([^<]*?)<\",\n \"Citation Number:</span></td><td><span class=\\\"Value\\\">([^<]*?)<\",\n \"Citation Number:</span></td><td><span class=\\\"Value\\\">([^<]*?)<\" # same as #2?\n]\ntext... | [
5,
3,
3,
2,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0003446878_python.txt |
Q:
GUI for the Linux and Windows platforms - Python CRUD app
i'm looking for a basic CRUD (create-read-update-delete) app
in Python, with some line-by-line display grid to browse through a file's
records and select individual records from there. It probably already
exists but i couldn't find anything yet.
Thanks
A:
Isn't Django all about web-based CRUD applications for Python?
A:
Maybe Camelot is what you need. It is a RAD framework for creating desktop database apps using Python, SQLAlchemy and Qt.
A:
hmm, probably more than what you need.
http://dabodev.com/
If you are more interested in lower level stuff, wxPython wiki has a lot of info, a google reveals
http://wiki.wxpython.org/DataAwareControlsMixin
but this might not be enough for you :)
| GUI for the Linux and Windows platforms - Python CRUD app | i'm looking for a basic CRUD (create-read-update-delete) app
in Python, with some line-by-line display grid to browse through a file's
records and select individual records from there. It probably already
exists but i couldn't find anything yet.
Thanks
| [
"Isn't Django all about web-based CRUD applications for Python?\n",
"Maybe Camelot is what you need. It is a RAD framework for creating desktop database apps using Python, SQLAlchemy and Qt.\n",
"hmm, probably more than what you need.\nhttp://dabodev.com/\nIf you are more interested in lower level stuff, wxPyt... | [
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0003443547_python.txt |
Q:
python: what is this funny notation? [0,1,3].__len__()
why would anyone use double underscores
why not just do len([1,2,3])?
my question is specifically What do the underscores mean?
A:
__len__() is the special Python method that is called when you use len().
It's pretty much like str() uses __str__(), repr uses __repr__(), etc. You can overload it in your classes to give len() a custom behaviour when used on an instance of your class.
See here: http://docs.python.org/release/2.5.2/ref/sequence-types.html:
__len__(self)
Called to implement the built-in function len(). Should return
the length of the object, an integer >= 0.
Also, an object that doesn't define a __nonzero__() method and
whose __len__() method returns zero is
considered to be false in a Boolean
context.
A:
If you "absolutely must" call it as a method (rather than a function) then the double underscores are needed. But the only motivation I can think for the code you show of is that somebody's gone so OO-happy that they don't understand the key Python principle that you don't directly call special methods (except you may need to call your superclass's version if you're overriding it, of course) -- you use the appropriate builtin or operator, and it calls (internally) whatever special methods are needed.
Actually, in the code you show the only sensible thing is to just use the constant 3, so maybe you've oversimplified your example a little...?-)
A:
You should read the docs on special method names.
A:
The one reason I've had to use x.__len__() rather than len(x) is due to the limitation that len can only return an int, whereas __len__ can return anything.
You might quite reasonably argue that only an integer should be returned, but if the length of your object is greater than sys.maxsize then you have no choice except to return a long instead:
>>> class A(object):
... def __len__(self):
... return 2**80
...
>>> a = A()
>>> len(a)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
OverflowError: long int too large to convert to int
>>> a.__len__()
1208925819614629174706176L
This isn't just a theoretical limitation, I've done a fair bit of work with bit containers where (with 32-bit Python) the len function stops working when the object reaches just 256MB.
| python: what is this funny notation? [0,1,3].__len__() |
why would anyone use double underscores
why not just do len([1,2,3])?
my question is specifically What do the underscores mean?
| [
"__len__() is the special Python method that is called when you use len().\nIt's pretty much like str() uses __str__(), repr uses __repr__(), etc. You can overload it in your classes to give len() a custom behaviour when used on an instance of your class.\nSee here: http://docs.python.org/release/2.5.2/ref/sequence... | [
4,
2,
2,
2
] | [] | [] | [
"python"
] | stackoverflow_0003444611_python.txt |
Q:
Having several file pointers open simultaneaously alright?
I'm reading from certain offsets in several hundred and possibly thousands files. Because I need only certain data from certain offsets at that particular time, I must either keep the file handle open for later use OR I can write the parts I need into seperate files.
I figured keeping all these file handles open rather than doing a significant amount of writing to the disk of new temporary files is the lesser of two evils. I was just worried about the efficiency of having so many file handles open.
Typically, I'll open a file, seek to an offset, read some data, then 5 seconds later do the same thing but at another offset, and do all this on thousand of files within a 2 minute timeframe.
Is that going to be a problem?
A followup: Really, I"m asking which is better to leave these thousands file handles open, or to constantly close them and re-open them just when I instantaneously need them.
A:
Some systems may limit the number of file descriptors that a single process can have open simultaneously. 1024 is a common default, so if you need "thousands" open at once, you might want to err on the side of portability and design your application to use a smaller
pool of open file descriptors.
A:
I recommend that you take a look at Storage.py in BitTorrent. It includes an implementation of a pool of file handles.
| Having several file pointers open simultaneaously alright? | I'm reading from certain offsets in several hundred and possibly thousands files. Because I need only certain data from certain offsets at that particular time, I must either keep the file handle open for later use OR I can write the parts I need into seperate files.
I figured keeping all these file handles open rather than doing a significant amount of writing to the disk of new temporary files is the lesser of two evils. I was just worried about the efficiency of having so many file handles open.
Typically, I'll open a file, seek to an offset, read some data, then 5 seconds later do the same thing but at another offset, and do all this on thousand of files within a 2 minute timeframe.
Is that going to be a problem?
A followup: Really, I"m asking which is better to leave these thousands file handles open, or to constantly close them and re-open them just when I instantaneously need them.
| [
"Some systems may limit the number of file descriptors that a single process can have open simultaneously. 1024 is a common default, so if you need \"thousands\" open at once, you might want to err on the side of portability and design your application to use a smaller\npool of open file descriptors.\n",
"I recom... | [
4,
3
] | [] | [] | [
"file",
"handles",
"python"
] | stackoverflow_0003446457_file_handles_python.txt |
Q:
Which files are taking most of my process's I/O time?
I have a fairly large python program that is causing a lot of disk I/O (on top, %wa can get as high as 80, and iotop says that my process is the culprit).
There are several things that may cause this - I'm writing to more than one log file, and I'm saving cached results to disk in several places, so it's not immediately obvious where I should focus my attention.
Is there a linux tool or a python trick that will allow me to see which subsystem is causing the most I/O operations?
A:
You should have a look at SystemTap. It's very powerful tracing and profiling mechanism for Linux system calls:
http://sourceware.org/systemtap/wiki
I'm sure it is possible to trace exactly which file descriptor is responsible for IO load - but it will get complicated to start with systemtap.
| Which files are taking most of my process's I/O time? | I have a fairly large python program that is causing a lot of disk I/O (on top, %wa can get as high as 80, and iotop says that my process is the culprit).
There are several things that may cause this - I'm writing to more than one log file, and I'm saving cached results to disk in several places, so it's not immediately obvious where I should focus my attention.
Is there a linux tool or a python trick that will allow me to see which subsystem is causing the most I/O operations?
| [
"You should have a look at SystemTap. It's very powerful tracing and profiling mechanism for Linux system calls:\nhttp://sourceware.org/systemtap/wiki\nI'm sure it is possible to trace exactly which file descriptor is responsible for IO load - but it will get complicated to start with systemtap.\n"
] | [
1
] | [] | [] | [
"linux",
"profiling",
"python"
] | stackoverflow_0003446396_linux_profiling_python.txt |
Q:
Sharing data between processes in Python
I have a complex data structure (user-defined type) on which a large number of independent calculations are performed. The data structure is basically immutable. I say basically, because though the interface looks immutable, internally some lazy-evaluation is going on. Some of the lazily calculated attributes are stored in dictionaries (return values of costly functions by input parameter).
I would like to use Pythons multiprocessing module to parallelize these calculations. There are two questions on my mind.
How do I best share the data-structure between processes?
Is there a way to handle the lazy-evaluation problem without using locks (multiple processes write the same value)?
Thanks in advance for any answers, comments or enlightening questions!
A:
How do I best share the data-structure between processes?
Pipelines.
origin.py | process1.py | process2.py | process3.py
Break your program up so that each calculation is a separate process of the following form.
def transform1( piece ):
Some transformation or calculation.
For testing, you can use it like this.
def t1( iterable ):
for piece in iterable:
more_data = transform1( piece )
yield NewNamedTuple( piece, more_data )
For reproducing the whole calculation in a single process, you can do this.
for x in t1( t2( t3( the_whole_structure ) ) ):
print( x )
You can wrap each transformation with a little bit of file I/O. Pickle works well for this, but other representations (like JSON or YAML) work well, too.
while True:
a_piece = pickle.load(sys.stdin)
more_data = transform1( a_piece )
pickle.dump( NewNamedTuple( piece, more_data ) )
Each processing step becomes an independent OS-level process. They will run concurrently and will -- immediately -- consume all OS-level resources.
Is there a way to handle the lazy-evaluation problem without using locks (multiple processes write the same value)?
Pipelines.
| Sharing data between processes in Python | I have a complex data structure (user-defined type) on which a large number of independent calculations are performed. The data structure is basically immutable. I say basically, because though the interface looks immutable, internally some lazy-evaluation is going on. Some of the lazily calculated attributes are stored in dictionaries (return values of costly functions by input parameter).
I would like to use Pythons multiprocessing module to parallelize these calculations. There are two questions on my mind.
How do I best share the data-structure between processes?
Is there a way to handle the lazy-evaluation problem without using locks (multiple processes write the same value)?
Thanks in advance for any answers, comments or enlightening questions!
| [
"\nHow do I best share the data-structure between processes?\n\nPipelines.\norigin.py | process1.py | process2.py | process3.py\n\nBreak your program up so that each calculation is a separate process of the following form.\ndef transform1( piece ):\n Some transformation or calculation.\n\nFor testing, you can us... | [
8
] | [] | [] | [
"lazy_evaluation",
"multiprocessing",
"python",
"sharing"
] | stackoverflow_0003447846_lazy_evaluation_multiprocessing_python_sharing.txt |
Q:
CMYK overprinting (colour-separated PDF output) with Reportlab
is it possible to use CMYK overprinting without using the CMYKColorSep class, which always generates a new seperate color in the printer settings, i just want to use overprinting with the standard 4 CMYK inks (colour-separated PDF output, as stated in the 2.4 changelog)
here my example code (reportlab 2.4 needed):
from reportlab.graphics.shapes import Rect
from reportlab.lib.colors import PCMYKColor, PCMYKColorSep
from reportlab.pdfgen.canvas import Canvas
black = PCMYKColor(0, 0, 0, 100)
blue = PCMYKColor(91.0, 43.0, 0.0, 0.0)
red = PCMYKColorSep( 0.0, 100.0, 91.0, 0.0, spotName='PANTONE 485 CV',density=100)
red2 = PCMYKColor( 0.0, 100.0, 91.0, 0.0, knockout=0) #knockout does nothing?
c = Canvas('test.pdf', (420,200))
c.setFillColor(black)
c.setFont('Helvetica', 10)
c.drawString(25,180, 'overprint w. CMYKColorSep')
c.setFillOverprint(True)
c.setFillColor(blue)
c.rect(25,25,100,100, fill=True, stroke=False)
c.setFillColor(red)
c.rect(100,75,100,100, fill=True, stroke=False)
c.setFillColor(black)
c.drawString(225,180, 'overprint w. plain CMYKColor (does not work)')
c.setFillColor(blue)
c.rect(225,25,100,100, fill=True, stroke=False)
c.setFillColor(red2)
c.rect(300,75,100,100, fill=True, stroke=False)
c.save()
note: you need to enable the overprinting preview in acrobat reader pro to correctly view this.
if this does not work with reportlab, do you know any other server-side alternative to generate pdf, where overprinting does work?
thank you very much
A:
You can only use overprint with CMYKColorSep. Its currently available in 2.4 but not stable (Robin is still messing with the code :) ).
There is a non public snippet on the reportlab website http://www.reportlab.com/snippets/10/ that demos it but hence the feature is still in development the snippet is not listed.
Meitham
A:
this feature is not implemented in Reportlab 2.4. But they will do it with their next major release.
| CMYK overprinting (colour-separated PDF output) with Reportlab | is it possible to use CMYK overprinting without using the CMYKColorSep class, which always generates a new seperate color in the printer settings, i just want to use overprinting with the standard 4 CMYK inks (colour-separated PDF output, as stated in the 2.4 changelog)
here my example code (reportlab 2.4 needed):
from reportlab.graphics.shapes import Rect
from reportlab.lib.colors import PCMYKColor, PCMYKColorSep
from reportlab.pdfgen.canvas import Canvas
black = PCMYKColor(0, 0, 0, 100)
blue = PCMYKColor(91.0, 43.0, 0.0, 0.0)
red = PCMYKColorSep( 0.0, 100.0, 91.0, 0.0, spotName='PANTONE 485 CV',density=100)
red2 = PCMYKColor( 0.0, 100.0, 91.0, 0.0, knockout=0) #knockout does nothing?
c = Canvas('test.pdf', (420,200))
c.setFillColor(black)
c.setFont('Helvetica', 10)
c.drawString(25,180, 'overprint w. CMYKColorSep')
c.setFillOverprint(True)
c.setFillColor(blue)
c.rect(25,25,100,100, fill=True, stroke=False)
c.setFillColor(red)
c.rect(100,75,100,100, fill=True, stroke=False)
c.setFillColor(black)
c.drawString(225,180, 'overprint w. plain CMYKColor (does not work)')
c.setFillColor(blue)
c.rect(225,25,100,100, fill=True, stroke=False)
c.setFillColor(red2)
c.rect(300,75,100,100, fill=True, stroke=False)
c.save()
note: you need to enable the overprinting preview in acrobat reader pro to correctly view this.
if this does not work with reportlab, do you know any other server-side alternative to generate pdf, where overprinting does work?
thank you very much
| [
"You can only use overprint with CMYKColorSep. Its currently available in 2.4 but not stable (Robin is still messing with the code :) ). \nThere is a non public snippet on the reportlab website http://www.reportlab.com/snippets/10/ that demos it but hence the feature is still in development the snippet is not liste... | [
3,
0
] | [] | [] | [
"cmyk",
"pdf",
"pdf_generation",
"python",
"reportlab"
] | stackoverflow_0003140231_cmyk_pdf_pdf_generation_python_reportlab.txt |
Q:
Processing data by reference or by value in python
Consider the following session. How are the differences explained? I thought that a += b is a syntactical sugar of (and thus equivalent to) a = a + b. Obviously I'm wrong.
>>> import numpy as np
>>> a = np.arange(24.).reshape(4,6)
>>> print a
[[ 0. 1. 2. 3. 4. 5.]
[ 6. 7. 8. 9. 10. 11.]
[ 12. 13. 14. 15. 16. 17.]
[ 18. 19. 20. 21. 22. 23.]]
>>> for line in a:
... line += 100
...
>>> print a #a has been changed
[[ 100. 101. 102. 103. 104. 105.]
[ 106. 107. 108. 109. 110. 111.]
[ 112. 113. 114. 115. 116. 117.]
[ 118. 119. 120. 121. 122. 123.]]
>>>
>>> for line in a:
... line = line + 999
...
>>> print a #a hasn't been changed
[[ 100. 101. 102. 103. 104. 105.]
[ 106. 107. 108. 109. 110. 111.]
[ 112. 113. 114. 115. 116. 117.]
[ 118. 119. 120. 121. 122. 123.]]
Thank you
A:
Using the + operator results in a call to the special method __add__ which should create a new object and should not modify the original.
On the other hand, using the += operator results in a call to __iadd__ which should modify the object if possible rather than creating a new object.
__add__
These methods are called to implement the binary arithmetic operations (+, -, *, //, %, divmod(), pow(), **, <<, >>, &, ^, |). For instance, to evaluate the expression x + y, where x is an instance of a class that has an __add__() method, x.__add__(y) is called.
__iadd__
These methods are called to implement the augmented arithmetic assignments (+=, -=, *=, /=, //=, %=, **=, <<=, >>=, &=, ^=, |=). These methods should attempt to do the operation in-place (modifying self) and return the result (which could be, but does not have to be, self).
Of course it is possible to implement __add__ and __iadd__ to have some other behaviour if you wanted to, but what you observe is the standard and recommended way. And, yes, it is a little surprising the first time you see it.
A:
You're not wrong, sometimes a += b really is syntactic sugar for a = a + b, but then sometimes it's not, which is one of the more confusing features of Python - see this similar question for more discussion.
The + operator calls the special method __add__, and the += operator tries to call the in-place __iadd__ special method, but I think it's worth expanding on the case where __iadd__ isn't defined.
If the in-place operator isn't defined, for example for immutable types such as strings and integers, then __add__ is called instead. So for these types a += b really is syntactic sugar for a = a + b. This toy class illustrates the point:
>>> class A(object):
... def __add__(self, other):
... print "In __add__ (not __iadd__)"
... return A()
...
>>> a = A()
>>> a = a + 1
In __add__ (not __iadd__)
>>> a += 1
In __add__ (not __iadd__)
This is the behaviour you should expect from any type that is immutable. While this can be confusing, the alternative would be to disallow += on immutable types which would be unfortunate as that would mean you couldn't use it on strings or integers!
For another example, this leads to a difference between lists and tuples, both of which support +=, but only lists can be modified:
>>> a = (1, 2)
>>> b = a
>>> b += (3, 4) # b = b + (3, 4) (creates new tuple, doesn't modify)
>>> a
(1, 2)
>>> a = [1, 2]
>>> b = a
>>> b += [3, 4] # calls __iadd___ so modifies b (and so a also)
>>> a
[1, 2, 3, 4]
Of course the same goes for all the other in-place operators, -=, *=, //=, %=, etc.
| Processing data by reference or by value in python | Consider the following session. How are the differences explained? I thought that a += b is a syntactical sugar of (and thus equivalent to) a = a + b. Obviously I'm wrong.
>>> import numpy as np
>>> a = np.arange(24.).reshape(4,6)
>>> print a
[[ 0. 1. 2. 3. 4. 5.]
[ 6. 7. 8. 9. 10. 11.]
[ 12. 13. 14. 15. 16. 17.]
[ 18. 19. 20. 21. 22. 23.]]
>>> for line in a:
... line += 100
...
>>> print a #a has been changed
[[ 100. 101. 102. 103. 104. 105.]
[ 106. 107. 108. 109. 110. 111.]
[ 112. 113. 114. 115. 116. 117.]
[ 118. 119. 120. 121. 122. 123.]]
>>>
>>> for line in a:
... line = line + 999
...
>>> print a #a hasn't been changed
[[ 100. 101. 102. 103. 104. 105.]
[ 106. 107. 108. 109. 110. 111.]
[ 112. 113. 114. 115. 116. 117.]
[ 118. 119. 120. 121. 122. 123.]]
Thank you
| [
"Using the + operator results in a call to the special method __add__ which should create a new object and should not modify the original.\nOn the other hand, using the += operator results in a call to __iadd__ which should modify the object if possible rather than creating a new object.\n\n__add__\nThese methods a... | [
15,
7
] | [] | [] | [
"numpy",
"python",
"syntactic_sugar",
"syntax"
] | stackoverflow_0003447435_numpy_python_syntactic_sugar_syntax.txt |
Q:
Stopping a recursive generator & permutations
As an exercise, I've been trying out various ways of generating all permutations of a list in Python -- recursive, non-recursive... -- and comparing the performance with itertools.permutations(). But I'm having trouble with the generator version of the recursive method, which doesn't finish cleanly with a StopIteration exception, but instead throws an IndexError:
def spawnperms(alist):
"""same algorithm as recursive option, but a generator"""
if (alist == []):
yield []
for perm in spawnperms(alist[:-1]):
for i in range(len(perm)+1):
yield perm[:i] + [alist[-1]] + perm[i:]
Calling this from the Python interpreter:
>>> for i in spawnperms(range(3)):
... print i
...
[2, 1, 0]
[1, 2, 0]
[1, 0, 2]
[2, 0, 1]
[0, 2, 1]
[0, 1, 2]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 5, in spawnperms
File "<stdin>", line 5, in spawnperms
File "<stdin>", line 5, in spawnperms
File "<stdin>", line 7, in spawnperms
IndexError: list index out of range
Ouch. I tried stepping through it with pdb, which nearly created a stack overflow in my brain, but what I understood is that the recursion "reaches down" to the empty list, and then the outer (I think) for loop runs out of indices.
How can I correct my code?
EDIT: One learning from Mark Byers' deceptively simple correct answer is that clean coding practices can prevent mistakes. Had I used an else systematically after if, regardless of whether I thought the condition could ever be revisited, this wouldn't have happened. And it still feels very stupid!
A:
You are missing an else:
if (alist == []):
yield []
else:
for ...
This is because yield does not behave in the same way as return. Execution continues after the yield statement when you request the next value.
| Stopping a recursive generator & permutations | As an exercise, I've been trying out various ways of generating all permutations of a list in Python -- recursive, non-recursive... -- and comparing the performance with itertools.permutations(). But I'm having trouble with the generator version of the recursive method, which doesn't finish cleanly with a StopIteration exception, but instead throws an IndexError:
def spawnperms(alist):
"""same algorithm as recursive option, but a generator"""
if (alist == []):
yield []
for perm in spawnperms(alist[:-1]):
for i in range(len(perm)+1):
yield perm[:i] + [alist[-1]] + perm[i:]
Calling this from the Python interpreter:
>>> for i in spawnperms(range(3)):
... print i
...
[2, 1, 0]
[1, 2, 0]
[1, 0, 2]
[2, 0, 1]
[0, 2, 1]
[0, 1, 2]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 5, in spawnperms
File "<stdin>", line 5, in spawnperms
File "<stdin>", line 5, in spawnperms
File "<stdin>", line 7, in spawnperms
IndexError: list index out of range
Ouch. I tried stepping through it with pdb, which nearly created a stack overflow in my brain, but what I understood is that the recursion "reaches down" to the empty list, and then the outer (I think) for loop runs out of indices.
How can I correct my code?
EDIT: One learning from Mark Byers' deceptively simple correct answer is that clean coding practices can prevent mistakes. Had I used an else systematically after if, regardless of whether I thought the condition could ever be revisited, this wouldn't have happened. And it still feels very stupid!
| [
"You are missing an else:\nif (alist == []):\n yield []\nelse:\n for ...\n\nThis is because yield does not behave in the same way as return. Execution continues after the yield statement when you request the next value. \n"
] | [
6
] | [] | [] | [
"exception",
"generator",
"permutation",
"python",
"recursion"
] | stackoverflow_0003448231_exception_generator_permutation_python_recursion.txt |
Q:
How to change the boolean value of C to the boolean value of python on mac
I would like to code in c ,but use the value in python by compile the c source file to .so file.
A:
The ctypes library is probably the easiest way to do this.
| How to change the boolean value of C to the boolean value of python on mac | I would like to code in c ,but use the value in python by compile the c source file to .so file.
| [
"The ctypes library is probably the easiest way to do this.\n"
] | [
1
] | [] | [] | [
"c",
"python"
] | stackoverflow_0003447769_c_python.txt |
Q:
How should I embed Python in a C++ Builder / Delphi 2010 application?
I'm interested in experimenting with embedding Python in my application, to let the user run Python scripts within the application environment, accessing internal (C++-implemented) objects, etc. I'm quite new to this so don't know exactly what I'm doing.
I have read Embedding Python in Another Application, though this seems to talk only about a C API and flat C functions, not classes or objects (unless I've missed something) and its "Embedding Python in C++" section is only two sentences long. However, I also came across how to use boost::python and this looks excellent.
There's one problem: boost::python is not supported by C++ Builder 2010.
So, given this, what is the best approach for embedding Python in a C++ application compiled with C++ Builder 2010, and, using whichever technique is best, how do you expose / integrate classes and objects to give the Python coder access to the object-oriented internals of a program? Have I missed a standard approach? Is exposing internal classes or instantiated objects to Python as objects easy, or is the API truly C-style or flat / non-OO, and if so what's the best approach to mimic an underlying OO layer through such an API?
Note: I actually use RAD Studio, which includes both C++ Builder and Delphi. It may be possible to make use of some sort of Delphi-specific binding, but the ones I've encountered are six or seven years old, or are new-ish (Python 2.6) but don't seem to have any documentation and have comments in the issue list like "Anyone reads thiese [sic] comments anyway? Anyone working on this project?" which is not encouraging. But please feel free to include Delphi-specific answers especially if you think it's likely they'll work in a combined D+CB app. I appreciate all answers even if they aren't quite perfect - I can research, I just need pointers on where to go. A native C++ solution would probably be ideal, though, since using VCL-derived objects has its own limitations.
Thanks for your input!
A:
You should not be afraid of the P4D project at google groups. It seems inactive because, in part, it is very stable and full-featured already. Those components are used in the much more active PyScripter application which is one of the best python development editors currently available. PyScripter is written in Delphi and uses the P4D components. As such, it also presents a very comprehensive example of how to use the P4D components, although the examples provided with the P4D source checkout are already good enough to get started.
A:
Is exposing internal classes or
instantiated objects to Python as
objects easy, or is the API truly
C-style or flat / non-OO, and if so
what's the best approach to mimic an
underlying OO layer through such an
API?
You have already answered yourself. The latter part of the sentence is correct.
Objects and classes do not exist in C++ as soon as you compile, only a few structures (vtables), and also another ones explaining some OO data, provided that RTTI is activated. That's why it is not possible to bridge the gap between Python and C++ using classes and objects.
You can build that surely by yourself, creating a set of C functions along with some data structures, and then an OO-layer. But you cannot do that out of the box.
For instance, class Car:
class Car {
public:
int getDoors()
{ return this->doors; }
protected:
int doors;
};
Is translated to:
struct Car {
int doors;
};
int Car_getDoors(Car * this)
{
return this->doors;
}
And a call to getDoors:
c->getDoors()
Is translated as:
Car_getDoors( c )
A:
You can generate C++ to $SCRIPTLANG wrappers with swig.
| How should I embed Python in a C++ Builder / Delphi 2010 application? | I'm interested in experimenting with embedding Python in my application, to let the user run Python scripts within the application environment, accessing internal (C++-implemented) objects, etc. I'm quite new to this so don't know exactly what I'm doing.
I have read Embedding Python in Another Application, though this seems to talk only about a C API and flat C functions, not classes or objects (unless I've missed something) and its "Embedding Python in C++" section is only two sentences long. However, I also came across how to use boost::python and this looks excellent.
There's one problem: boost::python is not supported by C++ Builder 2010.
So, given this, what is the best approach for embedding Python in a C++ application compiled with C++ Builder 2010, and, using whichever technique is best, how do you expose / integrate classes and objects to give the Python coder access to the object-oriented internals of a program? Have I missed a standard approach? Is exposing internal classes or instantiated objects to Python as objects easy, or is the API truly C-style or flat / non-OO, and if so what's the best approach to mimic an underlying OO layer through such an API?
Note: I actually use RAD Studio, which includes both C++ Builder and Delphi. It may be possible to make use of some sort of Delphi-specific binding, but the ones I've encountered are six or seven years old, or are new-ish (Python 2.6) but don't seem to have any documentation and have comments in the issue list like "Anyone reads thiese [sic] comments anyway? Anyone working on this project?" which is not encouraging. But please feel free to include Delphi-specific answers especially if you think it's likely they'll work in a combined D+CB app. I appreciate all answers even if they aren't quite perfect - I can research, I just need pointers on where to go. A native C++ solution would probably be ideal, though, since using VCL-derived objects has its own limitations.
Thanks for your input!
| [
"You should not be afraid of the P4D project at google groups. It seems inactive because, in part, it is very stable and full-featured already. Those components are used in the much more active PyScripter application which is one of the best python development editors currently available. PyScripter is writte... | [
8,
1,
0
] | [] | [] | [
"c++builder",
"c++builder_2010",
"delphi",
"embed",
"python"
] | stackoverflow_0003446799_c++builder_c++builder_2010_delphi_embed_python.txt |
Q:
How to keep the width of the bars the same no matter the number of bars we compare in the figure?
I want to keep the width of the bars the same no matter the number of bars compared is high or low.
I am using Matplotlib stacked bar chart.
the width of the bars is relative to the number of the bars.
Here is my sample code.
How can I make the width the same no matter the number of bars I compare from 1 to 10
import numpy as np
import matplotlib.pyplot as plt
N =1
ind = np.arange(N) # the x locations for the groups
width = 0.35 # the width of the bars: can also be len(x) sequence
design = []
arch = []
code = []
fig = plt.figure()
b = [70]
a= np.array([73])
c = [66]
p1 = plt.bar(ind, a,width, color='#263F6A')
p2 = plt.bar(ind, b, width, color='#3F9AC9', bottom=a)
p3 = plt.bar(ind, c, width, color='#76787A', bottom=a+b)
plt.ylabel('Scores')
plt.title('CQI Index')
plt.xticks(ind+width/2., ('P1'))#dynamic - fed
plt.yticks(np.arange(0,300,15))
plt.legend( (p1[0], p2[0], p3[0]), ('A','B','C') )
plt.grid(True)
plt.show()
Thank you
A:
The width of the bars doesn't change, the scale of your image changes. If you want the scale to stay the same you have to manually specify what range you want to show, whether your plot is 10x10, 100x100, or 1,000,000,000 x 10
Edit:
If I understand correctly, what you want is something like this:
Graph 1 - 2 bars:
10
+---------------------------+
| |
| |
| |
| |
| |
| 4_ |
| | | |
| 2_ | | |
| | | | | |
| | | | | |
+---------------------------+ 10
Graph 2 - add 2 more bars
10
+---------------------------+
| |
| |
| 7_ |
| | | |
| | | |
| 4_ | | |
| | | 3_ | | |
| 2_ | | | | | | |
| | | | | | | | | |
| | | | | | | | | |
+---------------------------+ 10
Where the apparent width of the bars hasn't changed from Graph 1 to Graph 2. If this is what you want to do then you'll need to set the scale of your plot
You can do that with
import matplotlib
matplotlib.use('GTKAgg')
import matplotlib.pyplot as plt
import gobject
fig = plt.figure()
ax = fig.add_subplot(111)
def draw1():
plt.bar(0,2)
plt.bar(2,4)
ax.set_xlim((0,10))
ax.set_ylim((0,10))
fig.canvas.draw()
return False
def draw2():
plt.bar(4,3)
plt.bar(6,7)
ax.set_xlim((0,10))
ax.set_ylim((0,10))
fig.canvas.draw()
return False
draw1()
gobject.timeout_add(1000, draw2)
plt.show()
| How to keep the width of the bars the same no matter the number of bars we compare in the figure? | I want to keep the width of the bars the same no matter the number of bars compared is high or low.
I am using Matplotlib stacked bar chart.
the width of the bars is relative to the number of the bars.
Here is my sample code.
How can I make the width the same no matter the number of bars I compare from 1 to 10
import numpy as np
import matplotlib.pyplot as plt
N =1
ind = np.arange(N) # the x locations for the groups
width = 0.35 # the width of the bars: can also be len(x) sequence
design = []
arch = []
code = []
fig = plt.figure()
b = [70]
a= np.array([73])
c = [66]
p1 = plt.bar(ind, a,width, color='#263F6A')
p2 = plt.bar(ind, b, width, color='#3F9AC9', bottom=a)
p3 = plt.bar(ind, c, width, color='#76787A', bottom=a+b)
plt.ylabel('Scores')
plt.title('CQI Index')
plt.xticks(ind+width/2., ('P1'))#dynamic - fed
plt.yticks(np.arange(0,300,15))
plt.legend( (p1[0], p2[0], p3[0]), ('A','B','C') )
plt.grid(True)
plt.show()
Thank you
| [
"The width of the bars doesn't change, the scale of your image changes. If you want the scale to stay the same you have to manually specify what range you want to show, whether your plot is 10x10, 100x100, or 1,000,000,000 x 10\nEdit:\nIf I understand correctly, what you want is something like this:\nGraph 1 - 2 ba... | [
2
] | [] | [] | [
"bar_chart",
"fixed_width",
"matplotlib",
"python"
] | stackoverflow_0003448350_bar_chart_fixed_width_matplotlib_python.txt |
Q:
Using datetime and manipulating date strings using python
I have a file of the following format
Summary:meeting Description:None DateStart:20100629T110000 DateEnd:20100629T120000 Time:20100805T084547Z
Summary:meeting Description:None DateStart:20100630T090000 DateEnd:20100630T100000 Time:20100805T084547Z
I need to create a function that would retrieve "Summary" at a given "date" and "time".
For example the function would have two arguments, the date and time, which wont be in date time formats. It needs to check if the date and time specified in the function argument is between the date and times in the DateStart and DateEnd in the file.
I am not sure how to retrieve time and date from the format specified above [i.e., 20100629T110000]. I was trying to use the following
line_time = datetime.strptime(time, "%Y%D%MT%H%M%S"), where time is "20100629T110000", but i am getting a lot of errors, like " datetime.datetime has not attribute strptime".
Whats the right way to do this function, thanks in advance.
....................EDIT................
Here is my error
Python 2.4.1 (#65, Mar 30 2005, 09:13:57) [MSC v.1310 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
****************************************************************
Personal firewall software may warn about the connection IDLE
makes to its subprocess using this computer's internal loopback
interface. This connection is not visible on any external
interface and no data is sent to or received from the Internet.
****************************************************************
>>>
Traceback (most recent call last):
File "C:\Python24\returnCalendarstatus", line 24, in -toplevel-
status = calendarstatus()
File "C:\Python24\returnCalendarstatus", line 16, in calendarstatus
line_time = datetime.strptime(time, "%Y%m%dT%H%M%S")
AttributeError: type object 'datetime.datetime' has no attribute 'strptime'
>>>
And here is my code
import os
import datetime
import time
from datetime import datetime
def calendarstatus():
g = open('calendaroutput.txt','r')
lines = g.readlines()
for line in lines:
line=line.strip()
info=line.split(";")
summary=info[1]
description=info[2]
time=info[5];
line_time = datetime.strptime(time, "%Y%m%dT%H%M%S")
return line_time.year
status = calendarstatus()
A:
Don't confuse the datetime module with the datetime Objects in the module.
The module has no strptime function, but the Object does have a strptime class method:
>>> time = "20100629T110000"
>>> import datetime
>>> line_time = datetime.strptime(time, "%Y%m%dT%H%M%S")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'strptime'
>>> line_time = datetime.datetime.strptime(time, "%Y%m%dT%H%M%S")
>>> line_time
datetime.datetime(2010, 6, 29, 11, 0)
Note the second time we have to reference the class as datetime.datetime.
Alternatively you can import just the class:
>>> from datetime import datetime
>>> line_time = datetime.strptime(time, "%Y%m%dT%H%M%S")
>>> line_time
datetime.datetime(2010, 6, 29, 11, 0)
Also, I changed your format string from %Y%D%MT%H%M%S to %Y%m%dT%H%M%S which I think is what you want.
A:
You need to actually read the documentation appropriate for your version of Python. See the note on strptime in the docs for datetime:
New in version 2.5.
and you are using version 2.4. You will need to use the workaround mentioned in that documentation:
import time
import datetime
[...]
time_string = info[5]
line_time = datetime(*(time.strptime(time_string, "%Y%m%dT%H%M%S")[0:6]))
| Using datetime and manipulating date strings using python | I have a file of the following format
Summary:meeting Description:None DateStart:20100629T110000 DateEnd:20100629T120000 Time:20100805T084547Z
Summary:meeting Description:None DateStart:20100630T090000 DateEnd:20100630T100000 Time:20100805T084547Z
I need to create a function that would retrieve "Summary" at a given "date" and "time".
For example the function would have two arguments, the date and time, which wont be in date time formats. It needs to check if the date and time specified in the function argument is between the date and times in the DateStart and DateEnd in the file.
I am not sure how to retrieve time and date from the format specified above [i.e., 20100629T110000]. I was trying to use the following
line_time = datetime.strptime(time, "%Y%D%MT%H%M%S"), where time is "20100629T110000", but i am getting a lot of errors, like " datetime.datetime has not attribute strptime".
Whats the right way to do this function, thanks in advance.
....................EDIT................
Here is my error
Python 2.4.1 (#65, Mar 30 2005, 09:13:57) [MSC v.1310 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
****************************************************************
Personal firewall software may warn about the connection IDLE
makes to its subprocess using this computer's internal loopback
interface. This connection is not visible on any external
interface and no data is sent to or received from the Internet.
****************************************************************
>>>
Traceback (most recent call last):
File "C:\Python24\returnCalendarstatus", line 24, in -toplevel-
status = calendarstatus()
File "C:\Python24\returnCalendarstatus", line 16, in calendarstatus
line_time = datetime.strptime(time, "%Y%m%dT%H%M%S")
AttributeError: type object 'datetime.datetime' has no attribute 'strptime'
>>>
And here is my code
import os
import datetime
import time
from datetime import datetime
def calendarstatus():
g = open('calendaroutput.txt','r')
lines = g.readlines()
for line in lines:
line=line.strip()
info=line.split(";")
summary=info[1]
description=info[2]
time=info[5];
line_time = datetime.strptime(time, "%Y%m%dT%H%M%S")
return line_time.year
status = calendarstatus()
| [
"Don't confuse the datetime module with the datetime Objects in the module.\nThe module has no strptime function, but the Object does have a strptime class method:\n>>> time = \"20100629T110000\"\n>>> import datetime\n>>> line_time = datetime.strptime(time, \"%Y%m%dT%H%M%S\")\nTraceback (most recent call last):\n ... | [
6,
6
] | [] | [] | [
"datetime",
"python"
] | stackoverflow_0003447542_datetime_python.txt |
Q:
List all Tests Found by Nosetest
I use nosetests to run my unittests and it works well. I want to get a list of all the tests nostests finds without actually running them. Is there a way to do that?
A:
Version 0.11.1 is currently available. You can get a list of tests without running them as follows:
nosetests -v --collect-only
A:
I recommend using:
nosetests -vv --collect-only
While the -vv option is not described in man nosetests, "An Extended Introduction to the nose Unit Testing Framework" states that:
Using the -vv flag gives you verbose output from nose's test discovery algorithm. This will tell you whether or not nose is even looking in the right place(s) to find your tests.
The -vv option can save time when trying to determine why nosetests is only finding some of your tests. (In my case, it was because nosetests skipped certain tests because the .py scripts were executable.)
Bottom line is that the -vv option is incredibly handy, and I almost always use it instead of the -v option.
A:
There will be soon: a new --collect switch that produces this behavior was demo'd at PyCon last week. It should be on the trunk "soon" and will be in the 0.11 release.
The http://groups.google.com/group/nose-users list is a great resource for nose questions.
| List all Tests Found by Nosetest | I use nosetests to run my unittests and it works well. I want to get a list of all the tests nostests finds without actually running them. Is there a way to do that?
| [
"Version 0.11.1 is currently available. You can get a list of tests without running them as follows:\nnosetests -v --collect-only\n\n",
"I recommend using:\nnosetests -vv --collect-only\n\nWhile the -vv option is not described in man nosetests, \"An Extended Introduction to the nose Unit Testing Framework\" stat... | [
50,
18,
3
] | [] | [] | [
"nose",
"nosetests",
"python",
"unit_testing"
] | stackoverflow_0000712020_nose_nosetests_python_unit_testing.txt |
Q:
Python - Is my code effecient? Or are people going to have fun killing my server...?
Aight, basically, I have a database that looks like this:
id | parentid | type | name
---------------------------------------------
1 | 0 | heading | this is my heading
---------------------------------------------
2 | 1 | child | this is one of many child elements
I'm using Mako to go through that list of data and create nested UL's. It seems to work great... But I'm not sure if my code could be improved.
Here it is:
<%def name="getCategories(parentID)">
## This function creates the children LI for the main headings
## Parameters:
## parentID - Integer - ID of the heading you want to get the children for
<%
categories = [x for x in c.headings if x.type == 'category' and x.parentid == parentID]
categories.sort(key=lambda x: x.name)
%>
%for category in categories:
<li>
<ul>
<li>${category.name.title()}</li>
${getSubCategories(category.id)}
</ul>
</li>
%endfor
<%def name="getSubCategories(parentID)">
## Get the subcategories for the parent category
##
## This could eventually turn into a recursive function to get further subcategories
## which is why it has it's own function rather than just having another for loop above
##
## Parameters: Same as above
<%
categories = [x for x in c.headings if x.type == 'category' and x.parentid == parentID]
categories.sort(key=lambda x: x.name)
%>
%for category in categories:
<ul>
<li>${category.name.title()}</li>
</ul>
%endfor
</%def>
</%def>
If you're wondering why I have two functions that produce the same output, it's because they don't. The nested UL's produced from getSubCategories() are styled differently (HTML) than those produced from getCategories().
Is this slow? Will it die under a heavy load? Could it be improved?
I'd appreciate your advice. Cheers.
A:
First, there is no way to know if it's going to die under a heavy load without testing it. The only way to anwser you question honestly is to profile your code. Only you can do it.
Now, nested relations are always slow, but you seem to use only 2 levels of nesting, therefor it's O(n^2), nothing that could kill remotely a server.
Some ways to improve it:
Remove this mix between code and markup. It really hard to read and probably as hard to debug. I know Mako is flexible enough to let you do that, but it's not because you can, that you should. Try some MVC.
If it reveals itself to be slow, then explore alternatives such as closure tables. But since you just display the tree, it may have no impact at all. You may at best speed up the sorting.
Talking about sorting, try to sort and filter categories when you query the database, instead of in the code. It's better than you for doing this things.
Or if you don't, at least make only one loop to generate both lists. The filtering is the same, no need to go trough all the items twice.
I guess your categories won't change at every page loads. Cache it.
| Python - Is my code effecient? Or are people going to have fun killing my server...? | Aight, basically, I have a database that looks like this:
id | parentid | type | name
---------------------------------------------
1 | 0 | heading | this is my heading
---------------------------------------------
2 | 1 | child | this is one of many child elements
I'm using Mako to go through that list of data and create nested UL's. It seems to work great... But I'm not sure if my code could be improved.
Here it is:
<%def name="getCategories(parentID)">
## This function creates the children LI for the main headings
## Parameters:
## parentID - Integer - ID of the heading you want to get the children for
<%
categories = [x for x in c.headings if x.type == 'category' and x.parentid == parentID]
categories.sort(key=lambda x: x.name)
%>
%for category in categories:
<li>
<ul>
<li>${category.name.title()}</li>
${getSubCategories(category.id)}
</ul>
</li>
%endfor
<%def name="getSubCategories(parentID)">
## Get the subcategories for the parent category
##
## This could eventually turn into a recursive function to get further subcategories
## which is why it has it's own function rather than just having another for loop above
##
## Parameters: Same as above
<%
categories = [x for x in c.headings if x.type == 'category' and x.parentid == parentID]
categories.sort(key=lambda x: x.name)
%>
%for category in categories:
<ul>
<li>${category.name.title()}</li>
</ul>
%endfor
</%def>
</%def>
If you're wondering why I have two functions that produce the same output, it's because they don't. The nested UL's produced from getSubCategories() are styled differently (HTML) than those produced from getCategories().
Is this slow? Will it die under a heavy load? Could it be improved?
I'd appreciate your advice. Cheers.
| [
"First, there is no way to know if it's going to die under a heavy load without testing it. The only way to anwser you question honestly is to profile your code. Only you can do it.\nNow, nested relations are always slow, but you seem to use only 2 levels of nesting, therefor it's O(n^2), nothing that could kill re... | [
1
] | [] | [] | [
"performance",
"pylons",
"python",
"templates"
] | stackoverflow_0003445963_performance_pylons_python_templates.txt |
Q:
How can I sort the files on the basis of time stamp from the the below set of files?
File dir = new File(".");
FileFilter fileFilter = new WildcardFileFilter("sample*.java");
File[] files = dir.listFiles(fileFilter);
for (int i = 0; i < files.length; i++) {
System.out.println(files[i]);
}
for example:
If I have the files shown below in a directory:
FILE NAME DATE CREATED/MODIFIED
properties.txt 10/08/2010 06:19
sublime.dll 10/08/2010 08:01
css_stlyle.css 10/08/2010 10:00
BMW_tags.php 10/08/2010 19:03
cars.properties 10/08/2010 04:37
A:
How about this C# linq approach:
var query = Directory.GetFiles("D:\\", "*.txt", SearchOption.AllDirectories)
.Select(name => new FileInfo(name));
var orderedList = query.OrderBy(fileInfo => fileInfo.CreationTime).ToList();
A:
In Python, if I understand you correctly:
import os
sorted( os.listdir( "." ), key = lambda file: os.stat( file )[ 8 ] )
A:
Because your Example was in java, Use a Comparator
File dir = new File(".");
File[] files = dir.listFiles();
Arrays.sort(files, new Comparator<File>() {
public int compare(File arg0, File arg1) {
return (arg0.lastModified() < arg1.lastModified())? -1 : 1;
}
});
for (int i = 0; i < files.length; i++) {
System.out.println(files[i] + " : " + files[i].lastModified());
}
| How can I sort the files on the basis of time stamp from the the below set of files? | File dir = new File(".");
FileFilter fileFilter = new WildcardFileFilter("sample*.java");
File[] files = dir.listFiles(fileFilter);
for (int i = 0; i < files.length; i++) {
System.out.println(files[i]);
}
for example:
If I have the files shown below in a directory:
FILE NAME DATE CREATED/MODIFIED
properties.txt 10/08/2010 06:19
sublime.dll 10/08/2010 08:01
css_stlyle.css 10/08/2010 10:00
BMW_tags.php 10/08/2010 19:03
cars.properties 10/08/2010 04:37
| [
"How about this C# linq approach:\nvar query = Directory.GetFiles(\"D:\\\\\", \"*.txt\", SearchOption.AllDirectories)\n .Select(name => new FileInfo(name));\n\nvar orderedList = query.OrderBy(fileInfo => fileInfo.CreationTime).ToList();\n\n",
"In Python, if I understand you correctly:\nimport ... | [
1,
0,
0
] | [] | [] | [
"c#",
"python",
"ruby_on_rails"
] | stackoverflow_0003447537_c#_python_ruby_on_rails.txt |
Q:
Cannot read sections of config files containing []
Edited post
I'm not able to read the configuration file sections that contain []... for e.g if any section in ini file is something like [c:\\temp\\foo[1].txt] than my script fails to read that section..
config.read(dst_bkp)
for i in config.sections():
config.get(i,'FileName')
Thanks,
Vignesh
A:
Assuming that you use a builtin subclass of ConfigParser.RawConfigParser module: This is not supported. Even in the newest revision, the regex for section headers is just
SECTCRE = re.compile(
r'\[' # [
r'(?P<header>[^]]+)' # very permissive!
r'\]' # ]
)
There is no escaping mechanism, and the section header simply ends at the first closing brackets. You should only use simple strings without "special characters" as header names, not arbitrary strings like file names.
EDIT: Concerning Python 3, the equivalent code has been reorganized a bit, but the regex is the same:
_SECT_TMPL = r"""
\[ # [
(?P<header>[^]]+) # very permissive!
\] # ]
"""
EDIT 2: You can make your own subclass, as suggested in the other solution, or patch RawConfigParser directly:
import ConfigParser
import re
ConfigParser.RawConfigParser.SECTCRE = re.compile(r"\[(?P<header>.+)\]")
However, I'd suggest not doing any of these and avoid the brackets instead. If you have brackets in section headers, your configuration files are likely to be unportable.
A:
That happens because of the regexp used to parse the header -- it goes only as far as the first closing bracket.
You can fix it for your program by subclassing ConfigParser.ConfigParser:
import ConfigParser
import re
class MyConfigParser(ConfigParser.ConfigParser):
SECTCRE = re.compile(
r'\[' # [
r'(?P<header>.+)' # even more permissive!
r'\]' # ]
)
config = MyConfigParser()
config.read(dst_bkp)
for i in config.sections():
config.get(i,'FileName')
| Cannot read sections of config files containing [] | Edited post
I'm not able to read the configuration file sections that contain []... for e.g if any section in ini file is something like [c:\\temp\\foo[1].txt] than my script fails to read that section..
config.read(dst_bkp)
for i in config.sections():
config.get(i,'FileName')
Thanks,
Vignesh
| [
"Assuming that you use a builtin subclass of ConfigParser.RawConfigParser module: This is not supported. Even in the newest revision, the regex for section headers is just\nSECTCRE = re.compile(\n r'\\[' # [\n r'(?P<header>[^]]+)' # very permissive!\n r'\\]'... | [
3,
1
] | [] | [] | [
"python"
] | stackoverflow_0003448505_python.txt |
Q:
PyQt + QtWebkit behind a proxy
I'm writing a PyQt (Python bindings for the all-powerful Qt library) application and a small part of my application needs a web browser (hint, OAuth). So I started using QtWebkit, which is fantastic by the way. The only hitch is I would like to allow users behind a proxy to use my application.
I have read about the QNetworkProxy class in the QtNetwork package and figure it should do the trick. The only problem is when I create and apply the proxy, it works just fine over HTTP, but when I pass it a HTTPS (SSL) URL, it gives me the following errors:
QSslSocket: cannot call unresolved function SSLv3_client_method
QSslSocket: cannot call unresolved function SSL_CTX_new
QSslSocket: cannot call unresolved function SSL_library_init
QSslSocket: cannot call unresolved function ERR_get_error
QSslSocket: cannot call unresolved function ERR_error_string
Note: when I run...
QtNetwork.QSslSocket.supportsSsl()
.. it returns false. So that's proof of my problem.
Here's my main code (it's right before my creationg of my QApplication):
proxy = QtNetwork.QNetworkProxy()
proxy.setType(QtNetwork.QNetworkProxy.Socks5Proxy)
proxy.setHostName('localhost');
proxy.setPort(1337)
QtNetwork.QNetworkProxy.setApplicationProxy(proxy);
I got the code from here but the example was written in C++, not Python so I'm not quite sure if I translated it properly. That could be the problem.
EDIT: I've tried it over a SOCKS5 and an HTTP proxy and they both throw the same error.
A:
I was working on Windows XP (32-bit) with Python 2.6 and PyQt 4.7.4. The reason that...
QtNetwork.QSslSocket.supportsSsl()
was returning false was because I had not installed OpenSSL binaries to my system.
To solve the problem I went here to download the binaries. Before they would properly install I had to also get the Visual C++ 2008 Redistributables install from Microsoft.
Everything is working great now!
| PyQt + QtWebkit behind a proxy | I'm writing a PyQt (Python bindings for the all-powerful Qt library) application and a small part of my application needs a web browser (hint, OAuth). So I started using QtWebkit, which is fantastic by the way. The only hitch is I would like to allow users behind a proxy to use my application.
I have read about the QNetworkProxy class in the QtNetwork package and figure it should do the trick. The only problem is when I create and apply the proxy, it works just fine over HTTP, but when I pass it a HTTPS (SSL) URL, it gives me the following errors:
QSslSocket: cannot call unresolved function SSLv3_client_method
QSslSocket: cannot call unresolved function SSL_CTX_new
QSslSocket: cannot call unresolved function SSL_library_init
QSslSocket: cannot call unresolved function ERR_get_error
QSslSocket: cannot call unresolved function ERR_error_string
Note: when I run...
QtNetwork.QSslSocket.supportsSsl()
.. it returns false. So that's proof of my problem.
Here's my main code (it's right before my creationg of my QApplication):
proxy = QtNetwork.QNetworkProxy()
proxy.setType(QtNetwork.QNetworkProxy.Socks5Proxy)
proxy.setHostName('localhost');
proxy.setPort(1337)
QtNetwork.QNetworkProxy.setApplicationProxy(proxy);
I got the code from here but the example was written in C++, not Python so I'm not quite sure if I translated it properly. That could be the problem.
EDIT: I've tried it over a SOCKS5 and an HTTP proxy and they both throw the same error.
| [
"I was working on Windows XP (32-bit) with Python 2.6 and PyQt 4.7.4. The reason that...\nQtNetwork.QSslSocket.supportsSsl()\n\nwas returning false was because I had not installed OpenSSL binaries to my system.\nTo solve the problem I went here to download the binaries. Before they would properly install I had to a... | [
6
] | [] | [] | [
"https",
"pyqt",
"python",
"qtwebkit",
"ssl"
] | stackoverflow_0003444507_https_pyqt_python_qtwebkit_ssl.txt |
Q:
mail sending from website
I've developed a site with Python, hosted on Google Apps, and I want to send emails from that site.
Is that possible, and if so, where should I look to find out how?
A:
Use the Mail API.
A:
Here is a snippet for a quick start:
from google.appengine.api import mail
mail.send_mail(
sender='anything@your-app-id.appspotmail.com',
to='john.doe@acme.com',
subject="Hello, World!",
body="..."]
)
| mail sending from website | I've developed a site with Python, hosted on Google Apps, and I want to send emails from that site.
Is that possible, and if so, where should I look to find out how?
| [
"Use the Mail API.\n",
"Here is a snippet for a quick start:\nfrom google.appengine.api import mail\n\nmail.send_mail(\n sender='anything@your-app-id.appspotmail.com',\n to='john.doe@acme.com',\n subject=\"Hello, World!\",\n body=\"...\"]\n)\n\n"
] | [
9,
2
] | [] | [] | [
"email",
"google_app_engine",
"python"
] | stackoverflow_0003440463_email_google_app_engine_python.txt |
Q:
Python subprocess.call weird behavior with multiple calls
I am trying to call remote (ssh) commands using the subprocess.call function like this.
import shlex
from subprocess import call
cmd1='ssh user@example.com mkdir temp'
cmd2='scp test.txt user@example.com:temp'
call(shlex.split(cmd1))
call(shlex.split(cmd2))
When I call the above, the mkdir does not seem to execute - although the documentation for subprocess.call says it waits for execution before returning. The latency of the individual ssh calls is about 0.5 seconds. It seems to work fine on the gigabit LAN where the latency is almost zero.
However it seems to work fine when the calls are made like this:
call(shlex.split(cmd1)) & call(shlex.split(cmd2))
What is the problem with the first approach?
Thank you,
Miliana
A:
It looks like you don't look for the result of call in the first method.
if call(shlex.split(cmd1))!=0:
call(shlex.split(cmd2))
A:
Your problematic version always works for me. I would think this is a network problem especially since you indicate that it works in gigabit LANs.
| Python subprocess.call weird behavior with multiple calls | I am trying to call remote (ssh) commands using the subprocess.call function like this.
import shlex
from subprocess import call
cmd1='ssh user@example.com mkdir temp'
cmd2='scp test.txt user@example.com:temp'
call(shlex.split(cmd1))
call(shlex.split(cmd2))
When I call the above, the mkdir does not seem to execute - although the documentation for subprocess.call says it waits for execution before returning. The latency of the individual ssh calls is about 0.5 seconds. It seems to work fine on the gigabit LAN where the latency is almost zero.
However it seems to work fine when the calls are made like this:
call(shlex.split(cmd1)) & call(shlex.split(cmd2))
What is the problem with the first approach?
Thank you,
Miliana
| [
"It looks like you don't look for the result of call in the first method.\nif call(shlex.split(cmd1))!=0:\n call(shlex.split(cmd2))\n\n",
"Your problematic version always works for me. I would think this is a network problem especially since you indicate that it works in gigabit LANs.\n"
] | [
0,
0
] | [] | [] | [
"python",
"subprocess"
] | stackoverflow_0003196286_python_subprocess.txt |
Q:
python + Semicolon written to file is written on the next line
I have this simple python expression:
fscript.write (("update %s va set %s = %s where %s = %s;") % (argv[1],argv[2],vl[0],argv[3],vl[1]))
And I would expect to receive output like this
update some_table va set active_id = 1 where id = 5;
update some_table va set active_id = 1 where id = 3;
...more lines...
However, i'm getting this
update some_table va set active_id = 1 where id = 5
;update some_table va set active_id = 1 where id = 3
...more lines....
Anything i'm missing ?
Thanks in advance
A:
I would try adding a strip() to your latest parameter that could end with \n.
fscript.write (("update %s va set %s = %s where %s = %s;") % (argv[1],argv[2],vl[0],argv[3],vl[1].strip()))
A:
Some value of vl[1] is a string with a newline in it, not an integer.
| python + Semicolon written to file is written on the next line | I have this simple python expression:
fscript.write (("update %s va set %s = %s where %s = %s;") % (argv[1],argv[2],vl[0],argv[3],vl[1]))
And I would expect to receive output like this
update some_table va set active_id = 1 where id = 5;
update some_table va set active_id = 1 where id = 3;
...more lines...
However, i'm getting this
update some_table va set active_id = 1 where id = 5
;update some_table va set active_id = 1 where id = 3
...more lines....
Anything i'm missing ?
Thanks in advance
| [
"I would try adding a strip() to your latest parameter that could end with \\n.\nfscript.write ((\"update %s va set %s = %s where %s = %s;\") % (argv[1],argv[2],vl[0],argv[3],vl[1].strip()))\n\n",
"Some value of vl[1] is a string with a newline in it, not an integer. \n"
] | [
1,
1
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0003449358_python_python_3.x.txt |
Q:
how to make django custom template tag with variable length arg list
I'm writing a custom template tag 'firstnotnone', similar to the 'firstof' template tag of Django. How to use variable length arguments? The code below results in TemplateSyntaxError, firstnotnone takes 1 arguments.
Template:
{% load library %}
{% firstnotnone 'a' 'b' 'c' %}
Custom template tag library:
@register.simple_tag
def firstnotnone(*args):
print args
for arg in args:
if arg is not None:
return arg
A:
The firstof tag isn't implemented via the simple_tag decorator - it uses the long form of a template.Node subclass and a separate tag function. You can see the code in django.template.defaulttags - it should be fairly simple to change for your purposes.
A:
Custom templatetags:
from django.template import Library, Node, TemplateSyntaxError
from django.utils.encoding import smart_unicode
register = Library()
class FirstNotNoneNode(Node):
def __init__(self, vars):
self.vars = vars
def render(self, context):
for var in self.vars:
value = var.resolve(context, True)
if value is not None:
return smart_unicode(value)
return u''
def firstnotnone(parser,token):
"""
Outputs the first variable passed that is not None
"""
bits = token.split_contents()[1:]
if len(bits) < 1:
raise TemplateSyntaxError("'firstnotnone' statement requires at least one argument")
return FirstNotNoneNode([parser.compile_filter(bit) for bit in bits])
firstnotnone = register.tag(firstnotnone)
| how to make django custom template tag with variable length arg list | I'm writing a custom template tag 'firstnotnone', similar to the 'firstof' template tag of Django. How to use variable length arguments? The code below results in TemplateSyntaxError, firstnotnone takes 1 arguments.
Template:
{% load library %}
{% firstnotnone 'a' 'b' 'c' %}
Custom template tag library:
@register.simple_tag
def firstnotnone(*args):
print args
for arg in args:
if arg is not None:
return arg
| [
"The firstof tag isn't implemented via the simple_tag decorator - it uses the long form of a template.Node subclass and a separate tag function. You can see the code in django.template.defaulttags - it should be fairly simple to change for your purposes.\n",
"Custom templatetags:\nfrom django.template import Libr... | [
4,
2
] | [] | [] | [
"django",
"django_templates",
"python"
] | stackoverflow_0003449265_django_django_templates_python.txt |
Q:
Decode values from django request
How to decode the values from request from django FW.
GET:<QueryDict: {}>,
POST:<QueryDict: {u'objarrid': [u'1035', u'1036', u'1037', u'1038', u'1039', u'1040', u'1041', u'1042']}>,
def get_data(request):
try:
if request.method == 'GET':
r_c = request.GET
elif request.method == 'POST':
r_c = request.POST
except:
dict.update({'ret_status' : 1})
Decode all values of query dict
A:
Use .getlist('objarrid').
| Decode values from django request | How to decode the values from request from django FW.
GET:<QueryDict: {}>,
POST:<QueryDict: {u'objarrid': [u'1035', u'1036', u'1037', u'1038', u'1039', u'1040', u'1041', u'1042']}>,
def get_data(request):
try:
if request.method == 'GET':
r_c = request.GET
elif request.method == 'POST':
r_c = request.POST
except:
dict.update({'ret_status' : 1})
Decode all values of query dict
| [
"Use .getlist('objarrid').\n"
] | [
3
] | [] | [] | [
"django",
"django_models",
"django_views",
"python"
] | stackoverflow_0003449521_django_django_models_django_views_python.txt |
Q:
Is there anything similar to isfile() isdir() with ftp in Python?
Writing a script to retrieve logfiles from one server to NAS i need to determine if sth is a file or a directory.
Does anybody know a simple way to determine if an element of ftp.nlst() is a file or a directory??
Thanks in advance
A:
Consider the following code from here. It will append [F] to directories and leave the files as it is.
from ftplib import FTP
import os
ftp = FTP(self.host)
listdir = self.ftp.nlst()
for i in listdir:
if(self.ftp.sendcmd(os.path.isdir(bool(self.ftpdir + "/" + i)))):
self.list_box_2.Append("[F] " + i)
Check out os.path and this SO post.
| Is there anything similar to isfile() isdir() with ftp in Python? | Writing a script to retrieve logfiles from one server to NAS i need to determine if sth is a file or a directory.
Does anybody know a simple way to determine if an element of ftp.nlst() is a file or a directory??
Thanks in advance
| [
"Consider the following code from here. It will append [F] to directories and leave the files as it is.\nfrom ftplib import FTP\nimport os\nftp = FTP(self.host)\nlistdir = self.ftp.nlst()\nfor i in listdir:\n if(self.ftp.sendcmd(os.path.isdir(bool(self.ftpdir + \"/\" + i)))):\n self.list_box_2.Append(\"... | [
1
] | [] | [] | [
"ftp",
"python"
] | stackoverflow_0003449843_ftp_python.txt |
Q:
Help me understand why my trivial use of Python's ctypes module is failing
I am trying to understand the Python "ctypes" module. I have put together a trivial example that -- ideally -- wraps the statvfs() function call. The code looks like this:
from ctypes import *
class struct_statvfs (Structure):
_fields_ = [
('f_bsize', c_ulong),
('f_frsize', c_ulong),
('f_blocks', c_ulong),
('f_bfree', c_ulong),
('f_bavail', c_ulong),
('f_files', c_ulong),
('f_ffree', c_ulong),
('f_favail', c_ulong),
('f_fsid', c_ulong),
('f_flag', c_ulong),
('f_namemax', c_ulong),
]
libc = CDLL('libc.so.6')
libc.statvfs.argtypes = [c_char_p, POINTER(struct_statvfs)]
s = struct_statvfs()
res = libc.statvfs('/etc', byref(s))
print 'return = %d, f_bsize = %d, f_blocks = %d, f_bfree = %d' % (
res, s.f_bsize, s.f_blocks, s.f_bfree)
Running this invariably returns:
return = 0, f_bsize = 4096, f_blocks = 10079070, f_bfree = 5048834
*** glibc detected *** python: free(): invalid next size (fast): 0x0000000001e51780 ***
*** glibc detected *** python: malloc(): memory corruption (fast): 0x0000000001e517e0 ***
I haven't been able to find any examples of calling functions with complex types as parameters (there are lots of examples of functions that return complex types), but after staring at the ctypes documentation for a day or so I think my calling syntax is correct...and it is actually callling the statvfs() call and getting back correct results.
Am I misunderstanding the ctypes docs? Or is something else going on here?
Thanks!
A:
Execute this command to get the exact definition of struct statvfs on your system:
echo '#include <sys/statvfs.h>' | gcc -E - | less
Then press /struct statvfs<enter> to skip to the definition and browse from there.
Also take a look at my patch to fusepy, and their definition.
A:
The manpage for statvfs states that the struct it uses is "defined approximately as follows", so you can't necessarily take the manpage's field listings as complete.
My guess is that there are additional struct fields after the end of the struct as you've defined it. This causes the statvfs function to overwrite memory outside your struct. I made the problem go away for me by adding a huge padding field to the _fields_ in my struct definition:
("padding", c_int * 1000),
Keep in mind that my script manifested the problem differently than yours; I got a segfault, whereas you merely got some error messages. Still, I'm guessing that it's the same problem, so you should try adding some padding and see if the problem persists.
A:
As Eli indicates, looking in /usr/include/bits/statvfs.h, your struct is not defined properly.
On my 64 bit Gentoo system it would be:
class struct_statvfs (Structure):
_fields_ = [
('f_bsize', c_ulong),
('f_frsize', c_ulong),
('f_blocks', c_ulong),
('f_bfree', c_ulong),
('f_bavail', c_ulong),
('f_files', c_ulong),
('f_ffree', c_ulong),
('f_favail', c_ulong),
('f_fsid', c_ulong),
('f_flag', c_ulong),
('f_namemax', c_ulong),
('__f_space', c_int * 6) # you are missing this
]
A:
According to the successful pyfuse ctypes wrappers for Fuse, the following is used for struct statvfs on Linux:
class c_statvfs(Structure):
_fields_ = [
('f_bsize', c_ulong),
('f_frsize', c_ulong),
('f_blocks', c_fsblkcnt_t),
('f_bfree', c_fsblkcnt_t),
('f_bavail', c_fsblkcnt_t),
('f_files', c_fsfilcnt_t),
('f_ffree', c_fsfilcnt_t),
('f_favail', c_fsfilcnt_t)]
More info: http://code.google.com/p/fusepy/
| Help me understand why my trivial use of Python's ctypes module is failing | I am trying to understand the Python "ctypes" module. I have put together a trivial example that -- ideally -- wraps the statvfs() function call. The code looks like this:
from ctypes import *
class struct_statvfs (Structure):
_fields_ = [
('f_bsize', c_ulong),
('f_frsize', c_ulong),
('f_blocks', c_ulong),
('f_bfree', c_ulong),
('f_bavail', c_ulong),
('f_files', c_ulong),
('f_ffree', c_ulong),
('f_favail', c_ulong),
('f_fsid', c_ulong),
('f_flag', c_ulong),
('f_namemax', c_ulong),
]
libc = CDLL('libc.so.6')
libc.statvfs.argtypes = [c_char_p, POINTER(struct_statvfs)]
s = struct_statvfs()
res = libc.statvfs('/etc', byref(s))
print 'return = %d, f_bsize = %d, f_blocks = %d, f_bfree = %d' % (
res, s.f_bsize, s.f_blocks, s.f_bfree)
Running this invariably returns:
return = 0, f_bsize = 4096, f_blocks = 10079070, f_bfree = 5048834
*** glibc detected *** python: free(): invalid next size (fast): 0x0000000001e51780 ***
*** glibc detected *** python: malloc(): memory corruption (fast): 0x0000000001e517e0 ***
I haven't been able to find any examples of calling functions with complex types as parameters (there are lots of examples of functions that return complex types), but after staring at the ctypes documentation for a day or so I think my calling syntax is correct...and it is actually callling the statvfs() call and getting back correct results.
Am I misunderstanding the ctypes docs? Or is something else going on here?
Thanks!
| [
"Execute this command to get the exact definition of struct statvfs on your system:\necho '#include <sys/statvfs.h>' | gcc -E - | less\n\nThen press /struct statvfs<enter> to skip to the definition and browse from there.\nAlso take a look at my patch to fusepy, and their definition.\n",
"The manpage for statvfs s... | [
4,
2,
2,
0
] | [] | [] | [
"ctypes",
"malloc",
"python"
] | stackoverflow_0003449442_ctypes_malloc_python.txt |
Q:
Using python to provide application services
My company's web architecture has essentially got an extra layer due to client security requirements, which complicates the process of developing applications a bit. I'd like to get some input and suggestions on the best way to do so.
First, an overview:
presentation layer - this is mostly PHP, with some flex applications as well. We may be adding HTML5/Javascript(jQuery) to this soon. This tier cannot see our database layer, and is the only layer that is visible to the outside world.
app layer - this is currently mostly PHP. It has access to the database
db layer - this is reachable only from non-DMZ hosts.
Right now, Flex applications and client-side javascript that need to make calls to the app layer -- which is a fair number of them -- make it through a PHP proxy running on the presentation layer, which passes the request in to the app layer. These are usually AMF service requests, but we could proxy RESTful requests as well with minimal effort.
I have an opportunity to replace a lot of this stack right now, provided I can retain the basic security characteristics. What I want is to be able to write JavaScript or Flex apps that make RESTful calls to services visible in the presentation layer that will transparently (or transparently enough!) proxy into the app tier, where the actual work is done.
The thing is, every tutorial I see on (for example) Django or other pythonic web / REST frameworks seems to assume that the services provided by my presentation and application layers here are provided by one layer only. I need advice on how to write, essentially, web services using Python. The app layer must authenticate the client and maintain client sessions. The web layer proxy does not do that because it has no database access. This sort of thing is what pointed me at Django, with its cached session tracking, for example. But, truthfully, I'm open to anything that gets me away from writing PHP4 for this.
A:
django-piston is a mini-framework for Django for creating RESTful APIs, which I think should fulfill your requirements.
A:
I've found that Pylons has been just the ticket for providing this capability; extension is really easy, testing is simple, and it gives loads of control to me as a developerl
| Using python to provide application services | My company's web architecture has essentially got an extra layer due to client security requirements, which complicates the process of developing applications a bit. I'd like to get some input and suggestions on the best way to do so.
First, an overview:
presentation layer - this is mostly PHP, with some flex applications as well. We may be adding HTML5/Javascript(jQuery) to this soon. This tier cannot see our database layer, and is the only layer that is visible to the outside world.
app layer - this is currently mostly PHP. It has access to the database
db layer - this is reachable only from non-DMZ hosts.
Right now, Flex applications and client-side javascript that need to make calls to the app layer -- which is a fair number of them -- make it through a PHP proxy running on the presentation layer, which passes the request in to the app layer. These are usually AMF service requests, but we could proxy RESTful requests as well with minimal effort.
I have an opportunity to replace a lot of this stack right now, provided I can retain the basic security characteristics. What I want is to be able to write JavaScript or Flex apps that make RESTful calls to services visible in the presentation layer that will transparently (or transparently enough!) proxy into the app tier, where the actual work is done.
The thing is, every tutorial I see on (for example) Django or other pythonic web / REST frameworks seems to assume that the services provided by my presentation and application layers here are provided by one layer only. I need advice on how to write, essentially, web services using Python. The app layer must authenticate the client and maintain client sessions. The web layer proxy does not do that because it has no database access. This sort of thing is what pointed me at Django, with its cached session tracking, for example. But, truthfully, I'm open to anything that gets me away from writing PHP4 for this.
| [
"django-piston is a mini-framework for Django for creating RESTful APIs, which I think should fulfill your requirements.\n",
"I've found that Pylons has been just the ticket for providing this capability; extension is really easy, testing is simple, and it gives loads of control to me as a developerl\n"
] | [
1,
0
] | [] | [] | [
"architecture",
"python",
"web_services"
] | stackoverflow_0003255933_architecture_python_web_services.txt |
Q:
python whois for windows
I try to get whois in python. I use this
http://code.google.com/p/pywhois/
but it run only in linux. Is it posible to run it on windows? currently i get errors (because internal linux command whois used)
A:
On Windows just like on Linux, pywhois gives an error if the whois program is not installed. You could try this whois, for example.
The reason, of course, is in pywhois/init.py, line 11:
r = subprocess.Popen(['whois', domain], stdout=subprocess.PIPE)
Clearly this line needs to run some existing, installed whois command-line program (which accepts the domain to look up as a commandline argument), whatever OS it's running on.
A:
You could use :
os.system("whois %s" % hostname)
Or use urllib to connect http://www.whois.net and scrap content.
| python whois for windows | I try to get whois in python. I use this
http://code.google.com/p/pywhois/
but it run only in linux. Is it posible to run it on windows? currently i get errors (because internal linux command whois used)
| [
"On Windows just like on Linux, pywhois gives an error if the whois program is not installed. You could try this whois, for example.\nThe reason, of course, is in pywhois/init.py, line 11:\nr = subprocess.Popen(['whois', domain], stdout=subprocess.PIPE)\n\nClearly this line needs to run some existing, installed wh... | [
6,
1
] | [] | [] | [
"python",
"whois",
"windows"
] | stackoverflow_0003450339_python_whois_windows.txt |
Q:
Call a method at a specific time for Django/Python?
In my Django web app, an event's status changes from 'upcoming' to 'completed' at a certain date/time. However, I want to update the database as soon as the event object's date/time has passed. Any ideas how I would code this?
My only idea so far is to have a thread constantly running that that checks to see if the event object's date/time as passed. However, this would be a really garbage way of doing things because there are potentially hundreds of event objects I would have to do this for.
Thanks for your help,
Chris
A:
The django-chronograph app is one way to schedule jobs -- it relies on a cron job to automate scheduled running of django commands.
| Call a method at a specific time for Django/Python? | In my Django web app, an event's status changes from 'upcoming' to 'completed' at a certain date/time. However, I want to update the database as soon as the event object's date/time has passed. Any ideas how I would code this?
My only idea so far is to have a thread constantly running that that checks to see if the event object's date/time as passed. However, this would be a really garbage way of doing things because there are potentially hundreds of event objects I would have to do this for.
Thanks for your help,
Chris
| [
"The django-chronograph app is one way to schedule jobs -- it relies on a cron job to automate scheduled running of django commands.\n"
] | [
3
] | [] | [] | [
"call",
"datetime",
"django",
"methods",
"python"
] | stackoverflow_0003450249_call_datetime_django_methods_python.txt |
Q:
Google App Engine: Production versus Development Settings
How do you setup a settings file? One is for your local development server and another set of setting values for when you upload to Google App Engine?
For example, I would like to set up a settings file where I store the Absolute Root URL.
A:
It's not clear from your question if you're asking about the Java or Python runtime. I'll assume Python for now.
Just like any other Python webapp, the settings file can be wherever and whatever you want. I usually use a .py file called 'settings.py' or 'config.py' in the root directory of my app. For example, see Bloog's settings file.
As far as having different settings for production and development goes, you have two options:
Simply keep two branches in your source code repository, one for dev and one for prod, and periodically merge from dev to prod when you want to do a release. In this case, you just don't merge config.py.
Autodetect which platform you're running on, and apply settings as appropriate. The easiest way to do this is to check the value of os.environ['SERVER_SOFTWARE'], which will start with 'Dev' if it's the development server. You can use this to set a flag like so:
DEBUG = os.environ['SERVER_SOFTWARE'].startswith('Dev')
A:
You can find out the root URL from the request, and use that instead of configuring it manually. Or if you need further configuration, then use that to decide which config to use.
| Google App Engine: Production versus Development Settings | How do you setup a settings file? One is for your local development server and another set of setting values for when you upload to Google App Engine?
For example, I would like to set up a settings file where I store the Absolute Root URL.
| [
"It's not clear from your question if you're asking about the Java or Python runtime. I'll assume Python for now.\nJust like any other Python webapp, the settings file can be wherever and whatever you want. I usually use a .py file called 'settings.py' or 'config.py' in the root directory of my app. For example, se... | [
16,
1
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0000873949_google_app_engine_python.txt |
Q:
Is monkeypatching stdlib methods a good practice in Python?
Over time I found the need to override several stdlib methods from Python in order to overcome limitation or to add some missing functionality.
In all cases I added a wrapper function and replaced the original method from the module with my wrapper (the wrapper was calling the original method).
Why I did this? Just to be sure that all the calls to the method are using my new versions, even if these are called from other third-party modules.
I know that monkeypatching can be a bad thing but my question is if this is useful if you use it with care? Meaning that:
you still call the original methods, assuring that you are not missing anything when the original module is updated
you are not changing the original "meaning" of the methods
Examples:
add coloring support to python logging module.
make open() be able to recognize Unicode BOM masks when using text mode
adding logging support to os.system() or subprocess.Popen() - letting you output to console or/and redirect to another file.
implementing methods that are missing on your platform like os.chown() or os.lchown() that are missing on Windows.
Doing things like these appear to me as decent overrides but I would like to see how others are seeing them and specially what should be considered as an acceptable monkeypatch and what not.
A:
None of these things seem to require monkeypatching. All of them seem to have better, more robust and reliable solutions.
Adding a logging handler is easy. No monkeypatch.
Fixing open is done this way.
from io import open
That was easy. No patch.
Logging to os.system()? I'd think that a simple "wrapper" function would be far better than a complex patch. Further, I'd use subprocess.Popen, since that's the recommended replacement.
Adding missing methods to mask OS differences (like os.chown()) seems like a better use for try/except. But that's just me. I like explicit rather than implicit.
On balance, I still can't see a good reason for monkeypatching.
I'd hate to be locked in to legacy code (like os.system) because I was too dependent on my monkeypatches.
The concept of "subclass" applies to modules as well as classes. You can easily write your own modules which (a) import and (b) extend existing modules. You then use your new modules because they provided extra features. You don't need to monkeypatch.
even if these are called from other third-party modules
Dreadful idea. You can easily break another module by altering built-in features. If you have read the other module and are sure the monkeypatches won't break then what you've found is this.
The "other" module should have had room for customization. It should have had a place for a "dependency injection" or Strategy design pattern. Good thinking.
Once you've found this, the "other" module can be fixed to allow this customization. It may be as simple as a documentation change explaining how to modify an object. It may be an additional
parameter for construction to insert your customization.
You can then provide the revised module to the authors to see if they'll support your small update to their module. Many classes can use extra help supporting a "dependency injection" or Strategy design for extensions.
If you have not read the other module and are not sure your monkeypatches work... well... we still have hope that the monkeypatches don't break anything.
A:
Monkeypatching can be "the least of evils", sometimes -- mostly, when you need to test code which uses a subsystem that is not well designed for testability (doesn't support dependency injection &c). In those cases you will be monkeypatching (very temporarily, fortunately) in your test harness, and almost invariably monkeypatching with mocks or fakes for the purpose of isolating tests (i.e., making them unit tests, rather than integration tests).
This "bad but could be worse" use case does not appear to apply to your examples -- they can all be better architected by editing the application level code to call your appropriate wrapper functions (say myos.chown rather than the bare os.chown, for example) and putting your wrapper functions in your own intermediate modules (such as myown) that stand between the application level code and the standard library (or third-party extensions that you are thus wrapping -- there's nothing special about the standard library in this respect).
One problematic situation might arise when the "application level code" isn't really under your control -- it's a third party subsystem that you'd rather not modify. Nevertheless, I have found that in such situations modifying the third party subsystem to call wrappers (rather than the standard library functions directly) is way more productive in the long run -- then of course you submit the change to the maintainers of the third party subsystem in question, they roll your change into their subsystem's next release, and life gets better for everybody (you included, since once your changes are accepted they'll get routinely maintained and tested by others!-).
(As a side note, such wrappers may also be worth submitting as diffs to the standard library, but that is a different case since the standard library evolves very very slowly and cautiously, and in particular on the Python 2 line will never evolve any longer, since 2.7 is the last of that line and it's feature-frozen).
Of course, all of this presupposes an open-source culture. If for some mysterious reasons you're using a closed-source third party subsystem, therefore one which you cannot possibly maintain, then you are in another situation where monkey patching may be the lesser evil (but that's just because the evil of losing strategic control of your development by trusting in code you can't possibly maintain is such a bigger evil in itself;-). I've never found myself in this situation with a third-party package that was both closed-source and itself written in Python (if the latter condition doesn't hold your monkeypatches would do you no good;-).
Note that here the working definition of "closed-source" is really very strict: for example, even Microsoft 12+ years ago distributed sources of libraries such as MFC with Visual C++ (as their product was then called) -- closed-source because you couldn't redistribute their sources, but still, you DID have sources at hand, so when you met some terrible limitation or bug you COULD fix it (and submit the change to them for a future release, as well as publishing your change as a diff as long as it included absolutely none of their copyrighted code -- not trivial, but feasible).
Monkeypatching well beyond the strict confines within which such an approach is "the least of evil" is a frequent mistake of users of dynamic languages -- be careful not to fall into that trap yourself!
| Is monkeypatching stdlib methods a good practice in Python? | Over time I found the need to override several stdlib methods from Python in order to overcome limitation or to add some missing functionality.
In all cases I added a wrapper function and replaced the original method from the module with my wrapper (the wrapper was calling the original method).
Why I did this? Just to be sure that all the calls to the method are using my new versions, even if these are called from other third-party modules.
I know that monkeypatching can be a bad thing but my question is if this is useful if you use it with care? Meaning that:
you still call the original methods, assuring that you are not missing anything when the original module is updated
you are not changing the original "meaning" of the methods
Examples:
add coloring support to python logging module.
make open() be able to recognize Unicode BOM masks when using text mode
adding logging support to os.system() or subprocess.Popen() - letting you output to console or/and redirect to another file.
implementing methods that are missing on your platform like os.chown() or os.lchown() that are missing on Windows.
Doing things like these appear to me as decent overrides but I would like to see how others are seeing them and specially what should be considered as an acceptable monkeypatch and what not.
| [
"None of these things seem to require monkeypatching. All of them seem to have better, more robust and reliable solutions. \nAdding a logging handler is easy. No monkeypatch.\nFixing open is done this way.\nfrom io import open\n\nThat was easy. No patch.\nLogging to os.system()? I'd think that a simple \"wrapp... | [
7,
3
] | [] | [] | [
"monkeypatching",
"python",
"word_wrap"
] | stackoverflow_0003450332_monkeypatching_python_word_wrap.txt |
Q:
How to close file objects when downloading files over FTP using Twisted?
I've got the following code:
for f in fileListProtocol.files:
if f['filetype'] == '-':
filename = os.path.join(directory['filename'], f['filename'])
print 'Downloading %s...' % (filename)
newFile = open(filename, 'w+')
d = ftpClient.retrieveFile(filename, FileConsumer(newFile))
d.addCallback(closeFile, newFile)
Unfortunately, after downloading several hundred of the 1000+ files in the directory in question I get an IOError about too many open files. Why is this when I should be closing each file after they've been downloaded? If there's a more idiomatic way to approach the whole task of downloading lots of files too, I'd love to hear it. Thanks.
Update: Jean-Paul's DeferredSemaphore example plus Matt's FTPFile did the trick. For some reason using a Cooperator instead of DeferredSemaphore would download a few files and then fail because the FTP connection would have died.
A:
You're opening every file in fileListProtocol.files simultaneously, downloading contents to them, and then closing each when each download is complete. So, you have len(fileListProtocol.files) files open at the beginning of the process. If there are too many files in that list, then you'll try to open too many files.
You probably want to limit yourself to some fairly small number of parallel downloads at once (if FTP even supports parallel downloads, which I'm not entirely certain is the case).
http://jcalderone.livejournal.com/24285.html and Queue remote calls to a Python Twisted perspective broker? may be of some help in figuring out how to limit the number of downloads you start in parallel.
A:
Assuming that you're using FTPClient from twisted.protocols.ftp... and I certainly hesitate before contradicting JP..
It seems that the FileConsumer class you're passing to retrieveFile will be adapted to IProtocol by twisted.internet.protocol.ConsumerToProtocolAdapter, which doesn't call unregisterProducer, so FileConsumer doesn't close the file object.
I've knocked up a quick protocol that you can use to receive the files. I think it should only open the file when appropriate. Totally untested, you'd use it in place of FileConsumer in your code above and won't need the addCallback.
from twisted.python import log
from twisted.internet import interfaces
from zope.interface import implements
class FTPFile(object):
"""
A consumer for FTP input that writes data to a file.
@ivar filename: a filename to be opened for writing.
"""
implements(interfaces.IProtocol)
def __init__(self, filename):
self.fObj = None
self.filename = filename
def makeConnection(self,transport)
self.fObj = open(self.filename,'wb')
log.info('Opened %s for writing' % self.filename)
def connectionLost(self,reason):
self.fObj.close()
log.info('Closed %s' % self.filename)
def dataReceived(self, bytes):
self.fObj.write(bytes)
| How to close file objects when downloading files over FTP using Twisted? | I've got the following code:
for f in fileListProtocol.files:
if f['filetype'] == '-':
filename = os.path.join(directory['filename'], f['filename'])
print 'Downloading %s...' % (filename)
newFile = open(filename, 'w+')
d = ftpClient.retrieveFile(filename, FileConsumer(newFile))
d.addCallback(closeFile, newFile)
Unfortunately, after downloading several hundred of the 1000+ files in the directory in question I get an IOError about too many open files. Why is this when I should be closing each file after they've been downloaded? If there's a more idiomatic way to approach the whole task of downloading lots of files too, I'd love to hear it. Thanks.
Update: Jean-Paul's DeferredSemaphore example plus Matt's FTPFile did the trick. For some reason using a Cooperator instead of DeferredSemaphore would download a few files and then fail because the FTP connection would have died.
| [
"You're opening every file in fileListProtocol.files simultaneously, downloading contents to them, and then closing each when each download is complete. So, you have len(fileListProtocol.files) files open at the beginning of the process. If there are too many files in that list, then you'll try to open too many f... | [
1,
1
] | [] | [] | [
"ftp",
"ioerror",
"python",
"twisted"
] | stackoverflow_0003449901_ftp_ioerror_python_twisted.txt |
Q:
Sharepoint Filter for List Items(GetListItems)
I'm attempting to get a set of list items from sharepoint via the WebService. I want to query a small subset of items to be returned. My SOAP packet appears to be ordered properly, however, it still appears that the service is ignoring my set filter(query). Any ideas why this would still be happening?
<SOAP-ENV:Envelope xmlns:ns0="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://schemas.microsoft.com/sharepoint/soap/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Header/>
<ns0:Body>
<ns1:GetListItems>
<ns1:listName>MyCalendar</ns1:listName>
<query>
<Query>
<Where>
<Eq>
<FieldRef Name="EventDate"/>
<Value Type="DateTime">[Now+2Minute(s)]</Value>
</Eq>
</Where>
</Query>
</query>
</ns1:GetListItems>
</ns0:Body>
</SOAP-ENV:Envelope>
and here is the python suds code that i used to generate this soap:
Query = Element('Query')
where = Element('Where')
eq = Element('Eq')
eq.append(Element('FieldRef').append(Attribute('Name', 'EventDate')))
vt = Element('Value').append(Attribute('Type', 'DateTime')).setText('[Now+2Minute(s)]')
eq.append(vt)
where.append(eq)
Query.append(where)
query = Element('query')
query.append(Query)
EDIT:
Here is the proper soap packet and suds code for what eventually worked for me. I have some strange requirements around the filter, but i'll go ahead and post as is so that others may learn from this.
<SOAP-ENV:Envelope xmlns:ns0="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://schemas.microsoft.com/sharepoint/soap/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Header/>
<ns0:Body>
<ns1:GetListItems>
<ns1:listName>Economic Event Calendar</ns1:listName>
<ns1:query>
<Query>
<Where>
<And>
<Geq>
<FieldRef Name="EventDate"/>
<Value IncludeTimeValue="TRUE" Type="DateTime">2010-08-12T07:38:00</Value>
</Geq>
<Lt>
<FieldRef Name="EventDate"/>
<Value IncludeTimeValue="TRUE" Type="DateTime">2010-08-12T07:39:00</Value>
</Lt>
</And>
</Where>
</Query>
</ns1:query>
<ns1:rowLimit>5</ns1:rowLimit>
<viewFields>
<FieldRef Name="Description"/>
<FieldRef Name="EventDate"/>
</viewFields>
</ns1:GetListItems>
</ns0:Body>
</SOAP-ENV:Envelope>
and the python/suds code that got me here:
#craft our XML
Query = Element('Query')
where = Element('Where')
And = Element('And')
geq = Element('Geq')
geq.append(Element('FieldRef').append(Attribute('Name', 'EventDate')))
vt = Element('Value').append(Attribute('IncludeTimeValue', 'TRUE'))
vt.append(Attribute('Type', 'DateTime')).setText(convert_dt('now +' + str(alertBefore) + ' minutes', '%Y-%m-%dT%H:%M:00' ))
lt = Element('Lt')
lt.append(Element('FieldRef').append(Attribute('Name', 'EventDate')))
vt2 = Element('Value').append(Attribute('IncludeTimeValue', 'TRUE'))
vt2.append(Attribute('Type', 'DateTime')).setText(convert_dt('now +' + str((alertBefore + 1)) + ' minutes', '%Y-%m-%dT%H:%M:00' ))
#viewFields fragment, only show the Description and EventDate for returned rows
viewFields = Element('viewFields')
viewFields.append(Element('FieldRef').append(Attribute('Name','Description')))
viewFields.append(Element('FieldRef').append(Attribute('Name','EventDate')))
#pack all the XML fragments
geq.append(vt)
lt.append(vt2)
where.append(And)
And.append(geq)
And.append(lt)
Query.append(where)
query = Element('ns1:query')
query.append(Query)
#issue the query
results = c_lists.service.GetListItems(SPCal, None, query, None, 5, viewFields, None)
A:
Try using the IncludeTimeValue attribute on your Value element:
<Value Type="DateTime" IncludeTimeValue="TRUE">[Now+2Minute(s)]</Value>
According to MSDN:
IncludeTimeValue: Optional Boolean. Specifies to build DateTime queries based on time as well as date. If you do not set this attribute, the time portion of queries that involve date and time are ignored.
I haven't used a lot of DateTime filters in my CAML queries, but everything else about your SOAP packet looks correct.
| Sharepoint Filter for List Items(GetListItems) | I'm attempting to get a set of list items from sharepoint via the WebService. I want to query a small subset of items to be returned. My SOAP packet appears to be ordered properly, however, it still appears that the service is ignoring my set filter(query). Any ideas why this would still be happening?
<SOAP-ENV:Envelope xmlns:ns0="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://schemas.microsoft.com/sharepoint/soap/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Header/>
<ns0:Body>
<ns1:GetListItems>
<ns1:listName>MyCalendar</ns1:listName>
<query>
<Query>
<Where>
<Eq>
<FieldRef Name="EventDate"/>
<Value Type="DateTime">[Now+2Minute(s)]</Value>
</Eq>
</Where>
</Query>
</query>
</ns1:GetListItems>
</ns0:Body>
</SOAP-ENV:Envelope>
and here is the python suds code that i used to generate this soap:
Query = Element('Query')
where = Element('Where')
eq = Element('Eq')
eq.append(Element('FieldRef').append(Attribute('Name', 'EventDate')))
vt = Element('Value').append(Attribute('Type', 'DateTime')).setText('[Now+2Minute(s)]')
eq.append(vt)
where.append(eq)
Query.append(where)
query = Element('query')
query.append(Query)
EDIT:
Here is the proper soap packet and suds code for what eventually worked for me. I have some strange requirements around the filter, but i'll go ahead and post as is so that others may learn from this.
<SOAP-ENV:Envelope xmlns:ns0="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://schemas.microsoft.com/sharepoint/soap/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Header/>
<ns0:Body>
<ns1:GetListItems>
<ns1:listName>Economic Event Calendar</ns1:listName>
<ns1:query>
<Query>
<Where>
<And>
<Geq>
<FieldRef Name="EventDate"/>
<Value IncludeTimeValue="TRUE" Type="DateTime">2010-08-12T07:38:00</Value>
</Geq>
<Lt>
<FieldRef Name="EventDate"/>
<Value IncludeTimeValue="TRUE" Type="DateTime">2010-08-12T07:39:00</Value>
</Lt>
</And>
</Where>
</Query>
</ns1:query>
<ns1:rowLimit>5</ns1:rowLimit>
<viewFields>
<FieldRef Name="Description"/>
<FieldRef Name="EventDate"/>
</viewFields>
</ns1:GetListItems>
</ns0:Body>
</SOAP-ENV:Envelope>
and the python/suds code that got me here:
#craft our XML
Query = Element('Query')
where = Element('Where')
And = Element('And')
geq = Element('Geq')
geq.append(Element('FieldRef').append(Attribute('Name', 'EventDate')))
vt = Element('Value').append(Attribute('IncludeTimeValue', 'TRUE'))
vt.append(Attribute('Type', 'DateTime')).setText(convert_dt('now +' + str(alertBefore) + ' minutes', '%Y-%m-%dT%H:%M:00' ))
lt = Element('Lt')
lt.append(Element('FieldRef').append(Attribute('Name', 'EventDate')))
vt2 = Element('Value').append(Attribute('IncludeTimeValue', 'TRUE'))
vt2.append(Attribute('Type', 'DateTime')).setText(convert_dt('now +' + str((alertBefore + 1)) + ' minutes', '%Y-%m-%dT%H:%M:00' ))
#viewFields fragment, only show the Description and EventDate for returned rows
viewFields = Element('viewFields')
viewFields.append(Element('FieldRef').append(Attribute('Name','Description')))
viewFields.append(Element('FieldRef').append(Attribute('Name','EventDate')))
#pack all the XML fragments
geq.append(vt)
lt.append(vt2)
where.append(And)
And.append(geq)
And.append(lt)
Query.append(where)
query = Element('ns1:query')
query.append(Query)
#issue the query
results = c_lists.service.GetListItems(SPCal, None, query, None, 5, viewFields, None)
| [
"Try using the IncludeTimeValue attribute on your Value element:\n<Value Type=\"DateTime\" IncludeTimeValue=\"TRUE\">[Now+2Minute(s)]</Value>\n\nAccording to MSDN:\n\nIncludeTimeValue: Optional Boolean. Specifies to build DateTime queries based on time as well as date. If you do not set this attribute, the time po... | [
1
] | [] | [] | [
"python",
"sharepoint",
"soap"
] | stackoverflow_0003449039_python_sharepoint_soap.txt |
Q:
User store fails on dev_appserver when performing redirect to login page
I am using Python 2.7 as this seems to be only Python MSI downloadable at the moment from Python.org.
self.redirect(users.create_login_url(self.request.uri)) fails when running on dev_appserver
localhost:8081/_ah/login?continue=http%3A//localhost%3A8081/ returns a 500.
Although this does work: localhost:8081/_ah/admin/datastore
Stack Trace:
ERROR 2010-08-10 13:21:11,111 dev_appserver.py:3239] Exception encountered handling request
Traceback (most recent call last):
File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 3199, in _HandleRequest
self._Dispatch(dispatcher, self.rfile, outfile, env_dict)
File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 3142, in _Dispatch
base_env_dict=env_dict)
File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 524, in Dispatch
base_env_dict=base_env_dict)
File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 2449, in Dispatch
CGIDispatcher.Dispatch(self, *args, **kwargs)
File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 2401, in Dispatch
self._module_dict)
File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 2438, in curried_exec_cgi
return ExecuteCGI(*args, **kwargs)
File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 2309, in ExecuteCGI
logging.debug('Executing CGI with env:\n%s', pprint.pformat(env))
File "C:\Python27\lib\pprint.py", line 60, in pformat
return PrettyPrinter(indent=indent, width=width, depth=depth).pformat(object)
File "C:\Python27\lib\pprint.py", line 119, in pformat
self._format(object, sio, 0, 0, {}, 0)
File "C:\Python27\lib\pprint.py", line 137, in _format
rep = self._repr(object, context, level - 1)
File "C:\Python27\lib\pprint.py", line 230, in _repr
self._depth, level)
File "C:\Python27\lib\pprint.py", line 242, in format
return _safe_repr(object, context, maxlevels, level)
File "C:\Python27\lib\pprint.py", line 284, in _safe_repr
for k, v in _sorted(object.items()):
File "C:\Python27\lib\pprint.py", line 75, in _sorted
with warnings.catch_warnings():
File "C:\Python27\lib\warnings.py", line 327, in __init__
self._module = sys.modules['warnings'] if module is None else module
KeyError: 'warnings'
INFO 2010-08-10 13:21:11,117 dev_appserver.py:3268] "GET /_ah/login?continue=http%3A//localhost%3A8080/ HTTP/1.1" 500 -
A:
I would recommend that you use 2.5.4, which is the exact version used in production. You can get an MSI from here:
http://www.python.org/download/releases/2.5.4/
I haven't tried 2.7, but I initially tried 2.6 and found that sending mail didn't work. It worked fine once I downgraded to 2.5.4 though.
| User store fails on dev_appserver when performing redirect to login page | I am using Python 2.7 as this seems to be only Python MSI downloadable at the moment from Python.org.
self.redirect(users.create_login_url(self.request.uri)) fails when running on dev_appserver
localhost:8081/_ah/login?continue=http%3A//localhost%3A8081/ returns a 500.
Although this does work: localhost:8081/_ah/admin/datastore
Stack Trace:
ERROR 2010-08-10 13:21:11,111 dev_appserver.py:3239] Exception encountered handling request
Traceback (most recent call last):
File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 3199, in _HandleRequest
self._Dispatch(dispatcher, self.rfile, outfile, env_dict)
File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 3142, in _Dispatch
base_env_dict=env_dict)
File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 524, in Dispatch
base_env_dict=base_env_dict)
File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 2449, in Dispatch
CGIDispatcher.Dispatch(self, *args, **kwargs)
File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 2401, in Dispatch
self._module_dict)
File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 2438, in curried_exec_cgi
return ExecuteCGI(*args, **kwargs)
File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 2309, in ExecuteCGI
logging.debug('Executing CGI with env:\n%s', pprint.pformat(env))
File "C:\Python27\lib\pprint.py", line 60, in pformat
return PrettyPrinter(indent=indent, width=width, depth=depth).pformat(object)
File "C:\Python27\lib\pprint.py", line 119, in pformat
self._format(object, sio, 0, 0, {}, 0)
File "C:\Python27\lib\pprint.py", line 137, in _format
rep = self._repr(object, context, level - 1)
File "C:\Python27\lib\pprint.py", line 230, in _repr
self._depth, level)
File "C:\Python27\lib\pprint.py", line 242, in format
return _safe_repr(object, context, maxlevels, level)
File "C:\Python27\lib\pprint.py", line 284, in _safe_repr
for k, v in _sorted(object.items()):
File "C:\Python27\lib\pprint.py", line 75, in _sorted
with warnings.catch_warnings():
File "C:\Python27\lib\warnings.py", line 327, in __init__
self._module = sys.modules['warnings'] if module is None else module
KeyError: 'warnings'
INFO 2010-08-10 13:21:11,117 dev_appserver.py:3268] "GET /_ah/login?continue=http%3A//localhost%3A8080/ HTTP/1.1" 500 -
| [
"I would recommend that you use 2.5.4, which is the exact version used in production. You can get an MSI from here:\nhttp://www.python.org/download/releases/2.5.4/\nI haven't tried 2.7, but I initially tried 2.6 and found that sending mail didn't work. It worked fine once I downgraded to 2.5.4 though.\n"
] | [
0
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0003448670_google_app_engine_python.txt |
Q:
Python threading.Event() - Ensuring all waiting threads wake up on event.set()
I have a number of threads which wait on an event, perform some action, then wait on the event again. Another thread will trigger the event when it's appropriate.
I can't figure out a way to ensure that each waiting thread triggers exactly once upon the event being set. I currently have the triggering thread set it, sleep for a bit, then clear it. Unfortunately, this leads to the waiting threads grabbing the set event many times, or none at all.
I can't simply have the triggering thread spawn the response threads to run them once because they're responses to requests made from elsewhere.
In short: In Python, how can I have a thread set an event and ensure each waiting thread acts on the event exactly once before it gets cleared?
Update:
I've tried setting it up using a lock and a queue, but it doesn't work. Here's what I have:
# Globals - used to synch threads
waitingOnEvent = Queue.Queue
MainEvent = threading.Event()
MainEvent.clear() # Not sure this is necessary, but figured I'd be safe
mainLock = threading.Lock()
def waitCall():
mainLock.acquire()
waitingOnEvent.put("waiting")
mainLock.release()
MainEvent.wait()
waitingOnEvent.get(False)
waitingOnEvent.task_done()
#do stuff
return
def triggerCall():
mainLock.acquire()
itemsinq = waitingOnEvent.qsize()
MainEvent.set()
waitingOnEvent.join()
MainEvent.clear()
mainLock.release()
return
The first time, itemsinq properly reflects how many calls are waiting, but only the first waiting thread to make the call will make it through. From then on, itemsinq is always 1, and the waiting threads take turns; each time the trigger call happens, the next goes through.
Update 2
It appears as though only one of the event.wait() threads is waking up, and yet the queue.join() is working. This suggests to me that one waiting thread wakes up, grabs from the queue and calls task_done(), and that single get()/task_done() somehow empties the queue and allows the join(). The trigger thread then completes the join(), clears the event, and thus prevents the other waiting threads from going through. Why would the queue register as empty/finished after only one get/task_done call, though?
Only one seems to be waking up, even if I comment out the queue.get() and queue.task_done() and hang the trigger so it can't clear the event.
A:
You don't need an Event, and you don't need both a Lock and a Queue. All you need is a Queue.
Call queue.put to drop a message in without waiting for it to be delivered or processed.
Call queue.get in the worker thread to wait for a message to arrive.
import threading
import Queue
active_queues = []
class Worker(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.mailbox = Queue.Queue()
active_queues.append(self.mailbox)
def run(self):
while True:
data = self.mailbox.get()
if data == 'shutdown':
print self, 'shutting down'
return
print self, 'received a message:', data
def stop(self):
active_queues.remove(self.mailbox)
self.mailbox.put("shutdown")
self.join()
def broadcast_event(data):
for q in active_queues:
q.put(data)
t1 = Worker()
t2 = Worker()
t1.start()
t2.start()
broadcast_event("first event")
broadcast_event("second event")
broadcast_event("shutdown")
t1.stop()
t2.stop()
The messages don't have to be strings; they can be any Python object.
A:
If you want discrete, atomic events that can be processed sequentially by each thread, then do as krs1 & bot403 suggested and use a queue. The Python Queue class is synchronized - you do not have to worry about locking to use it.
If however your needs are simpler (the event tells you that you have data available to read, etc), you can subscribe/register your threads as observers of an object responsible for triggering the events. This object would maintain the list of observer threading.Event objects. On a trigger, it can then call set() on all of the threading.Event objects in the list.
A:
One solution I've used in the past is the Queue class for interthread communication. It is threadsafe and can be used to easy communication between threads when using both the multiprocessing and threading libraries. You could have the child threads waiting for something to enter the queue and then process the new entry. The Queue class also has a get() method which takes a handy blocking argument.
A:
I'm not a python programmer but if an event can only be processed once perhaps you need to switch to a message queue with the appropriate locking so that when one thread wakes up and receives the event message it will process it and remove it from the queue so its not there if other threads wake up and look in the queue.
| Python threading.Event() - Ensuring all waiting threads wake up on event.set() | I have a number of threads which wait on an event, perform some action, then wait on the event again. Another thread will trigger the event when it's appropriate.
I can't figure out a way to ensure that each waiting thread triggers exactly once upon the event being set. I currently have the triggering thread set it, sleep for a bit, then clear it. Unfortunately, this leads to the waiting threads grabbing the set event many times, or none at all.
I can't simply have the triggering thread spawn the response threads to run them once because they're responses to requests made from elsewhere.
In short: In Python, how can I have a thread set an event and ensure each waiting thread acts on the event exactly once before it gets cleared?
Update:
I've tried setting it up using a lock and a queue, but it doesn't work. Here's what I have:
# Globals - used to synch threads
waitingOnEvent = Queue.Queue
MainEvent = threading.Event()
MainEvent.clear() # Not sure this is necessary, but figured I'd be safe
mainLock = threading.Lock()
def waitCall():
mainLock.acquire()
waitingOnEvent.put("waiting")
mainLock.release()
MainEvent.wait()
waitingOnEvent.get(False)
waitingOnEvent.task_done()
#do stuff
return
def triggerCall():
mainLock.acquire()
itemsinq = waitingOnEvent.qsize()
MainEvent.set()
waitingOnEvent.join()
MainEvent.clear()
mainLock.release()
return
The first time, itemsinq properly reflects how many calls are waiting, but only the first waiting thread to make the call will make it through. From then on, itemsinq is always 1, and the waiting threads take turns; each time the trigger call happens, the next goes through.
Update 2
It appears as though only one of the event.wait() threads is waking up, and yet the queue.join() is working. This suggests to me that one waiting thread wakes up, grabs from the queue and calls task_done(), and that single get()/task_done() somehow empties the queue and allows the join(). The trigger thread then completes the join(), clears the event, and thus prevents the other waiting threads from going through. Why would the queue register as empty/finished after only one get/task_done call, though?
Only one seems to be waking up, even if I comment out the queue.get() and queue.task_done() and hang the trigger so it can't clear the event.
| [
"You don't need an Event, and you don't need both a Lock and a Queue. All you need is a Queue.\nCall queue.put to drop a message in without waiting for it to be delivered or processed.\nCall queue.get in the worker thread to wait for a message to arrive.\nimport threading\nimport Queue\n\nactive_queues = []\n\nclas... | [
13,
3,
2,
1
] | [] | [] | [
"events",
"multithreading",
"python"
] | stackoverflow_0003409593_events_multithreading_python.txt |
Q:
Python: determining if an object is file-like?
I'm writing some unit tests (using the unittest module) for my application, and want to write something which can verify that a method I'm calling returns a "file-like" object. Since this isn't a simple isinstance call, I wonder what the best-practice would be for determining this?
So, in outline:
possible_file = self.dao.get_file("anotherfile.pdf")
self.assertTrue(possible_file is file-like)
Perhaps I have to care which specific interface this file object implements, or which methods that make it file-like I want to support?
Thanks,
R
A:
There is no "official definition" of what objects are "sufficiently file-like", because the various uses of file-like objects have such different requirements -- e.g., some only require read or write methods, other require some subset of the various line-reading methods... all the ways to some requiring the fileno method, which can't even be supplied by the "very file-like objects" offered by StringIO and cStringIO modules in the standard library. It's definitely a question of "shades of gray", not a black-and-white taxonomy!
So, you need to determine which methods you need. To check for them, I recommended defining your own FileLikeEnoughForMe abstract base class with abstractmethod decorators, and checking the object with an isinstance for that class, if you're on Python 2.6 or better: this is the recommended idiom these days, rather than a bunch of hasattr checks which would be less readable and more complex (when properly beefed up with checks that those attributes are actually methods, etc;-).
A:
The classical Python mentality is that it's easier to ask forgiveness than permission. In other words, don't check, catch the exception caused by writeing to it.
The new way is to use an IO abstract base class in an isinstance check. This was introduced when people realised that duck typing is awesome, but sometimes you really do want an instance check.
In your case (unittesting), you probably want to try it and see:
thingy = ...
try:
thingy.write( ... )
thingy.writeline( ... )
...
thingy.read( )
except AttributeError:
...
A:
Check, if returned object provides interface you are looking for. Like this for example:
self.assert_(hasattr(possible_file, 'write'))
self.assert_(hasattr(possible_file, 'read'))
| Python: determining if an object is file-like? | I'm writing some unit tests (using the unittest module) for my application, and want to write something which can verify that a method I'm calling returns a "file-like" object. Since this isn't a simple isinstance call, I wonder what the best-practice would be for determining this?
So, in outline:
possible_file = self.dao.get_file("anotherfile.pdf")
self.assertTrue(possible_file is file-like)
Perhaps I have to care which specific interface this file object implements, or which methods that make it file-like I want to support?
Thanks,
R
| [
"There is no \"official definition\" of what objects are \"sufficiently file-like\", because the various uses of file-like objects have such different requirements -- e.g., some only require read or write methods, other require some subset of the various line-reading methods... all the ways to some requiring the fi... | [
7,
4,
2
] | [] | [] | [
"file",
"python",
"types"
] | stackoverflow_0003450857_file_python_types.txt |
Q:
How to wrap long lines in a text using Regular Expressions when you also need to indent the wrapped lines?
How can one change the following text
The quick brown fox jumps over the lazy dog.
to
The quick brown fox +
jumps over the +
lazy dog.
using regex?
UPDATE1
A solution for Ruby is still missing... A simple one I came to so far is
def textwrap text, width, indent="\n"
return text.split("\n").collect do |line|
line.scan( /(.{1,#{width}})(\s+|$)/ ).collect{|a|a[0]}.join indent
end.join("\n")
end
puts textwrap 'The quick brown fox jumps over the lazy dog.', width=19, indent=" + \n "
# >> The quick brown fox +
# >> jumps over the lazy +
# >> dog.
A:
Maybe use textwrap instead of regex:
import textwrap
text='The quick brown fox jumps over the lazy dog.'
print(' + \n'.join(
textwrap.wrap(text, initial_indent='', subsequent_indent=' '*4, width=20)))
yields:
The quick brown fox +
jumps over the +
lazy dog.
| How to wrap long lines in a text using Regular Expressions when you also need to indent the wrapped lines? | How can one change the following text
The quick brown fox jumps over the lazy dog.
to
The quick brown fox +
jumps over the +
lazy dog.
using regex?
UPDATE1
A solution for Ruby is still missing... A simple one I came to so far is
def textwrap text, width, indent="\n"
return text.split("\n").collect do |line|
line.scan( /(.{1,#{width}})(\s+|$)/ ).collect{|a|a[0]}.join indent
end.join("\n")
end
puts textwrap 'The quick brown fox jumps over the lazy dog.', width=19, indent=" + \n "
# >> The quick brown fox +
# >> jumps over the lazy +
# >> dog.
| [
"Maybe use textwrap instead of regex:\nimport textwrap\n\ntext='The quick brown fox jumps over the lazy dog.'\n\nprint(' + \\n'.join(\n textwrap.wrap(text, initial_indent='', subsequent_indent=' '*4, width=20)))\n\nyields:\nThe quick brown fox + \n jumps over the + \n lazy dog.\n\n"
] | [
5
] | [] | [] | [
"python",
"regex",
"ruby",
"word_wrap"
] | stackoverflow_0003451308_python_regex_ruby_word_wrap.txt |
Q:
Django: how do you serve media / stylesheets and link to them within templates
Variations of this question have been asked, but I'm still unable to get my stylesheets to load correctly when my templates are rendered.
I'm attempting to serve static media from the Django process during development - which is strongly discouraged in production, I'm aware. I'll post my configuration and my template, and hopefully someone can help me to understand where I'm going wrong.
Note that I did try to follow the example on the Django project website, however it doesn't mention how to refer to your stylesheets from a template. I've also tried many different variations of the same thing, so my code/settings may be a little off from what's described.
settings.py
MEDIA_ROOT = 'D:/Dev Tools/django_projects/dso/media'
MEDIA_URL = '/media/'
ADMIN_MEDIA_PREFIX = '/media/'
urls.py
from django.conf.urls.defaults import *
from django.conf import settings
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
(r'^admin/(.*)', admin.site.root),
(r'^ovramt/$', 'dso.ovramt.views.index'),
)
if settings.DEBUG:
urlpatterns += patterns('',
(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}),
)
Within my template:
<head>
<title> {% block title %} DSO Template {% endblock %} </title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" >
<link rel="stylesheet" type="text/css" href="../media/styles.css">
</head>
I assure you, the files (templates/media) are in the correct directory on my file system. If there's any extra information I need to provide, please post a comment.
Edit:
One of the problems I was having was the use of a '/' prepending my links. If the forward slash is prepended, the link is opened from the root of the site. If there is no forward slash, the link is opened in the current level. An example:
www.example.com/application/ has a link "/app2/ and a link "app3/".
app2 will open at www.example.com/app2/ and app3 will open at www.example.com/application/app3/. This was confusing me I think.
A:
I just had to figure this out myself.
settings.py:
MEDIA_ROOT = 'C:/Server/Projects/project_name/static/'
MEDIA_URL = '/static/'
ADMIN_MEDIA_PREFIX = '/media/'
urls.py:
from django.conf import settings
...
if settings.DEBUG:
urlpatterns += patterns('',
(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}),
)
template file:
<link rel="stylesheet" type="text/css" href="/static/css/style.css" />
With the file located here:
"C:/Server/Projects/project_name/static/css/style.css"
A:
Django already has a context process for MEDIA_URL, see Django's documentation.
It should be availbale by default (unless you've customized CONTEXT_PROCESSORS and forgot to add it) in a RequestContext.
A:
I usually make my own Template simple tag because Django isn't giving CSS/JavaScript files. Apache does it so my media url is usually http://static.mysite.com.
yourApp/templatetags/media_url.py:
from django.template import Library
from yourapp.settings import MEDIA_URL
register = Library()
@register.simple_tag
def media_url():
return MEDIA_URL
And in my template file:
{% load media_url %}
<link href="{{ media_url }}css/main.css" rel="stylesheet" type="text/css">
You could also make your own context preprocessor to add the media_url variable in every template.
A:
I just use absolute naming. Unless you're running the site in a deep path (or even if you are), I'd drop the .. and go for something like:
<link rel="stylesheet" type="text/css" href="/media/styles.css">
A:
I've got a couple of ideas, I don't know which one of them is working for me :)
Make sure to use a trailing slash, and to have this be different from the MEDIA_URL setting (since the same URL cannot be mapped onto two different sets of files).
That's from http://docs.djangoproject.com/en/dev/ref/settings/#admin-media-prefix
Secondly, it may be that you're confusing directories on your filesystem with url paths. Try using absolute urls, and then refine them down.
A:
Just thought I'd chime in quickly. While all the propositions here work just fine, and I do use Ty's example while developing, once you hit production you might want to opt to serve files via a straight Apache, or whichever else server you're using.
What I do is I setup a subdomain once I'm done developing, and replace all links to static media. For instance:
<link rel="stylesheet" type="text/css" href="http://static.mydomain.com/css/style.css" />
The reasons for doing this are two-fold. First, it just seems like it would be slower to have Django handle these requests when it's not needed. Second, since most browsers can actually download files simultaneously from 3 different domains, using a second sub-domain for your static files will actually speed up the download speed of your users.
A:
Another thing to add is that if you have a separate media server on a subdomain/different domain, you can disable cookies for your static media. Saves a little processing and bandwidth.
| Django: how do you serve media / stylesheets and link to them within templates | Variations of this question have been asked, but I'm still unable to get my stylesheets to load correctly when my templates are rendered.
I'm attempting to serve static media from the Django process during development - which is strongly discouraged in production, I'm aware. I'll post my configuration and my template, and hopefully someone can help me to understand where I'm going wrong.
Note that I did try to follow the example on the Django project website, however it doesn't mention how to refer to your stylesheets from a template. I've also tried many different variations of the same thing, so my code/settings may be a little off from what's described.
settings.py
MEDIA_ROOT = 'D:/Dev Tools/django_projects/dso/media'
MEDIA_URL = '/media/'
ADMIN_MEDIA_PREFIX = '/media/'
urls.py
from django.conf.urls.defaults import *
from django.conf import settings
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
(r'^admin/(.*)', admin.site.root),
(r'^ovramt/$', 'dso.ovramt.views.index'),
)
if settings.DEBUG:
urlpatterns += patterns('',
(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}),
)
Within my template:
<head>
<title> {% block title %} DSO Template {% endblock %} </title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" >
<link rel="stylesheet" type="text/css" href="../media/styles.css">
</head>
I assure you, the files (templates/media) are in the correct directory on my file system. If there's any extra information I need to provide, please post a comment.
Edit:
One of the problems I was having was the use of a '/' prepending my links. If the forward slash is prepended, the link is opened from the root of the site. If there is no forward slash, the link is opened in the current level. An example:
www.example.com/application/ has a link "/app2/ and a link "app3/".
app2 will open at www.example.com/app2/ and app3 will open at www.example.com/application/app3/. This was confusing me I think.
| [
"I just had to figure this out myself.\nsettings.py:\nMEDIA_ROOT = 'C:/Server/Projects/project_name/static/'\nMEDIA_URL = '/static/'\nADMIN_MEDIA_PREFIX = '/media/'\n\nurls.py:\nfrom django.conf import settings\n...\nif settings.DEBUG:\n urlpatterns += patterns('',\n (r'^static/(?P<path>.*)$', 'django.vie... | [
51,
11,
6,
2,
1,
1,
0
] | [] | [] | [
"css",
"django",
"django_templates",
"media",
"python"
] | stackoverflow_0000446026_css_django_django_templates_media_python.txt |
Q:
Can a JSON data structure be directly saved as a CouchDB document?
I'm a Python programmer with experience using the json module. I've just meet CouchDB and seems very interesting.
I wonder know if JSON data structures can be directly saved as a CouchDB document.
Thanks,
A:
You only need to provide an unique ID that will be used as part of the resource name (URI) when PUTting it or you use POST and take an auto-generated ID. You can use any JSON, that does not contain _id and _rev, because these fields are reserved for CouchDB itself.
A:
couchDB is inteded to work with JSON.
have a look here: http://wiki.apache.org/couchdb/HTTP_Document_API#POST
you just POST a json document for storage.
A:
CouchDB will accept any valid JSON Object as a document.
| Can a JSON data structure be directly saved as a CouchDB document? | I'm a Python programmer with experience using the json module. I've just meet CouchDB and seems very interesting.
I wonder know if JSON data structures can be directly saved as a CouchDB document.
Thanks,
| [
"You only need to provide an unique ID that will be used as part of the resource name (URI) when PUTting it or you use POST and take an auto-generated ID. You can use any JSON, that does not contain _id and _rev, because these fields are reserved for CouchDB itself.\n",
"couchDB is inteded to work with JSON.\nhav... | [
3,
0,
0
] | [] | [] | [
"couchdb",
"json",
"python"
] | stackoverflow_0003441057_couchdb_json_python.txt |
Q:
How to use named parameters and global vars with same name in Python?
Example code from a module:
somevar = "a"
def myfunc(somevar = None):
# need to access both somevars ???
# ... if somevar was specified print it or use the global value
pass
if __name__ == '__main__':
somevar = "b" # this is just for fun here
myfunc("c")
myfunc() # should print "a" (the value of global variable)
There are at least two reasons for using the same name:educational (to learn how to use local/globals) and usage in modules.
Let say that this code is part of your module: mymodule and you want to do things like:
import mymodule
mymodule.samevar = "default"
...
mymodule.myfunc(somevar = "a")
...
mymodule.myfunc()
As you can imagine in this example is simplified, imagine that somevar parameter is one of many optional parameters and that myfunc is called in many places.
A:
By far the best approach, as the other answers say, is to avoid this very, very bad design: just don't use the same names for two different things!
If you're locked into this terrible design, maybe because your company's Supreme Architect decreed it and it's just non-negotiable (e.g., there's tons of customer code relying on the names of both the global and the parameter), the first order of business for you is to make sure your resume is up to date, print it on the best printer, and start getting in touch with members of your social network to look for a job at a place that's run more sensibly; next, to avoid losing health insurance until a better job is found, try
def myfunc(somevar = None):
if somevar is None:
print globals().get('somevar')
else:
print somevar
I've also renamed your mufunc to myfunc because that's the name it's being called with (though given the incredibly bad design your hypothetical Supreme Architect seems to be able to perpetrate, maybe he's also specified that the function be called by a different name from the one it's defined with? seems to go with the systematic name conflict this hypothetical but already pretty hateful guy is assumed to have foisted on you!-).
A:
Why does you local variable have to have the same name as the global variable? Renaming one of them seems like a simple solution. Another option is to pass the global variable in as a parameter, but this will still just give you a different variable name to access the save value.
A:
Two solutions:
Rename the variable, ie to somevar_.
Move the global to a different module. You can write a module myappdefaults
import myappdefaults
print myappdefaults.somevar
A:
This is the correct way to do things.
somevar = "a"
def mufunc(_somevar = None):
global somevar
if _somevar:
print _somevar
else:
print somevar
if __name__ == '__main__':
global somevar
somevar = "b"
myfunc("c")
myfunc() $ should print "c"
| How to use named parameters and global vars with same name in Python? | Example code from a module:
somevar = "a"
def myfunc(somevar = None):
# need to access both somevars ???
# ... if somevar was specified print it or use the global value
pass
if __name__ == '__main__':
somevar = "b" # this is just for fun here
myfunc("c")
myfunc() # should print "a" (the value of global variable)
There are at least two reasons for using the same name:educational (to learn how to use local/globals) and usage in modules.
Let say that this code is part of your module: mymodule and you want to do things like:
import mymodule
mymodule.samevar = "default"
...
mymodule.myfunc(somevar = "a")
...
mymodule.myfunc()
As you can imagine in this example is simplified, imagine that somevar parameter is one of many optional parameters and that myfunc is called in many places.
| [
"By far the best approach, as the other answers say, is to avoid this very, very bad design: just don't use the same names for two different things!\nIf you're locked into this terrible design, maybe because your company's Supreme Architect decreed it and it's just non-negotiable (e.g., there's tons of customer cod... | [
6,
1,
0,
0
] | [] | [] | [
"global_variables",
"python",
"python_module"
] | stackoverflow_0003451533_global_variables_python_python_module.txt |
Q:
Is there a wxpython event like program_start?
OK, I'm trying to explain what I want to achieve in another way. Here's an example:
Say if it's an anti virus program, and user can choose between two ways to run the program, choice one, automatically start to scan disks for virus when the program starts up, choice two, hit the start button to make the program scan disks for virus after the program starts up any time the user wants. So, as a wxpython beginner, I know how to bind wx.EVT_BUTTON to let scanning start after the user hit the start button, but I don't know how to make the scanning start once the program starts up. I wonder if there's a program_start event I can bind? Hope you guys can help me out. Thanks!
A:
Why don't you run it just in module code? This way it will be run only once, because code in module is run only once per program instance.
A:
In wxPython you can override the OnInit method of your Application class to run code when the program launches. For example:
def OnInit(self):
# Check for a running instance for this user. Do not instantiate if found.
if self.checkInstance():
dbcon.cursor().callproc('post_mutex', (self.mutexname,))
dbcon.commit()
self.Cleanup()
return False
# Register for database events.
DataCache['dbListener'] = dbListener()
return True
There is of course another method on my Application class called checkInstance. Depending on it's return value, my application either launches, or triggers the other running instance to launch.
In wxPython you don't have to do anything special with your App class to get the binding to take place for your OnInit method. It'll happen automatically if you override it.
A:
In your init or OnInit method, do some kind of check to see if the program should run the startup process on startup (i.e. check a config file or some such). If yes, call the "scan" method using wx.CallAfter or wx.CallLater or call it after you Show() the frame.
| Is there a wxpython event like program_start? | OK, I'm trying to explain what I want to achieve in another way. Here's an example:
Say if it's an anti virus program, and user can choose between two ways to run the program, choice one, automatically start to scan disks for virus when the program starts up, choice two, hit the start button to make the program scan disks for virus after the program starts up any time the user wants. So, as a wxpython beginner, I know how to bind wx.EVT_BUTTON to let scanning start after the user hit the start button, but I don't know how to make the scanning start once the program starts up. I wonder if there's a program_start event I can bind? Hope you guys can help me out. Thanks!
| [
"Why don't you run it just in module code? This way it will be run only once, because code in module is run only once per program instance.\n",
"In wxPython you can override the OnInit method of your Application class to run code when the program launches. For example:\n def OnInit(self):\n # Check for a run... | [
1,
1,
0
] | [] | [] | [
"event_handling",
"python",
"wxpython"
] | stackoverflow_0003450525_event_handling_python_wxpython.txt |
Q:
Sending sqlite db over network
I have an sqlite database whose data I need to transfer over the network, the server needs to modify the data, and then I need to get the db back and either update my local version or overwrite it with the new db. How should I do this? My coworker at first wanted to scrap the db and just use an .ini file, but this is going to be data that we have to parse pretty frequently (it's a user defined schedule that can change at the user's will, as well as the server's). I said we should just transfer the entire .db as a binary file and let them do with it what they will and then take it back. Or is there a way in sqlite to dump the db to a .sql file like you can do in MySQL so we can transfer it as text?
Any other solutions? This is in python if it makes a difference
update: This is on an embedded platform running linux (I'm not sure what version/kernel or what OS commands we have except the basics that are obvious)
A:
Use the copy command in your OS. No reason to overthink this.
| Sending sqlite db over network | I have an sqlite database whose data I need to transfer over the network, the server needs to modify the data, and then I need to get the db back and either update my local version or overwrite it with the new db. How should I do this? My coworker at first wanted to scrap the db and just use an .ini file, but this is going to be data that we have to parse pretty frequently (it's a user defined schedule that can change at the user's will, as well as the server's). I said we should just transfer the entire .db as a binary file and let them do with it what they will and then take it back. Or is there a way in sqlite to dump the db to a .sql file like you can do in MySQL so we can transfer it as text?
Any other solutions? This is in python if it makes a difference
update: This is on an embedded platform running linux (I'm not sure what version/kernel or what OS commands we have except the basics that are obvious)
| [
"Use the copy command in your OS. No reason to overthink this.\n"
] | [
3
] | [] | [] | [
"binary_data",
"embedded",
"python",
"sqlite"
] | stackoverflow_0003451708_binary_data_embedded_python_sqlite.txt |
Q:
Why should I use python 3.1 instead of python 2.6?
After reading some benchmarks, I noticed that python 3.1 is slower than python 2.6, especially with I/Os.
So I wonder what could be the good reasons to switch to Python 3.x ?
A:
Largely because of the new I/O library. This, however, has been completely rewritten to C in Python 3.2 and 2.7. I think the performance numbers are pretty close right now if you compare it to 3.2.
edit: I confused the version numbers. Nevermind.
A:
Go to 3.1. Unless your code is run-once (which at almost never is). 2.6 has no future, and version 3 is the future, unless you are into time travel.
They are working on 3.1 and I can assure you the speeds will soon be up to par, and then exceed 2.6 speeds.
A:
Python 3 does introduce some new language features too. One of my favorite is the new nonlocal keyword, which finally lets you write certain closures nicely, such as:
def getter_setter():
x = 0
def getter():
return x
def setter(val):
nonlocal x
x = val
return (getter, setter)
| Why should I use python 3.1 instead of python 2.6? | After reading some benchmarks, I noticed that python 3.1 is slower than python 2.6, especially with I/Os.
So I wonder what could be the good reasons to switch to Python 3.x ?
| [
"Largely because of the new I/O library. This, however, has been completely rewritten to C in Python 3.2 and 2.7. I think the performance numbers are pretty close right now if you compare it to 3.2.\nedit: I confused the version numbers. Nevermind.\n",
"Go to 3.1. Unless your code is run-once (which at almost nev... | [
0,
0,
0
] | [] | [] | [
"performance",
"python"
] | stackoverflow_0003451149_performance_python.txt |
Q:
Why is Python 3 (or later) better than Python 2?
I learned Python as my first serious (non BASIC) language about 10 years ago. Since then, I have learned lots of others, but I tend to 'think' in Python. When I look at the list of changes I do not see one I need this feature. I usually say to myself, hmm that would been a good way of doing it, but why change it now?
Things like changing the default floor division could be a real pain to change for big projects. It seems like the major players are dragging their feet. What is the key feature that would make me want to invest in another learning curve?
A:
As a key feature, a lot of people seem to be pretty exited about (supposedly) transparent unicode support. They changed it from str (8-bit char array/default string type) and unicode (unicode string), to str (default (unicode compatable) string) and bytes (binary data as 8-bit 'string').
(I think seperation of byte lists from strings is great idea, but I also hate unicode, so if anything, this would be a worse for me personally.)
A:
A good discussion of this can be found in the python wiki; Should I use Python 2 or Python 3 for my development activity?
A:
Things like changing default floor
division could be a real pain to
change for big projects.
If you had started making the change 8 years ago when Python 2.2 was introduced with // and from __future__ import division, it wouldn't be a pain now. Personally, I'm glad to finally get rid of old-style division!
My second-favorite feature of Python 3.x is the str/bytes distinction. Besides making Unicode support easier, bytes is far more convenient for database BLOBs than buffer was.
A:
On Teaching Programming With Python 3.0, though a bit dated, is one of the best articles I've read on the advantages of Py3k.
| Why is Python 3 (or later) better than Python 2? | I learned Python as my first serious (non BASIC) language about 10 years ago. Since then, I have learned lots of others, but I tend to 'think' in Python. When I look at the list of changes I do not see one I need this feature. I usually say to myself, hmm that would been a good way of doing it, but why change it now?
Things like changing the default floor division could be a real pain to change for big projects. It seems like the major players are dragging their feet. What is the key feature that would make me want to invest in another learning curve?
| [
"As a key feature, a lot of people seem to be pretty exited about (supposedly) transparent unicode support. They changed it from str (8-bit char array/default string type) and unicode (unicode string), to str (default (unicode compatable) string) and bytes (binary data as 8-bit 'string'). \n(I think seperation of... | [
10,
3,
1,
0
] | [] | [] | [
"python",
"python_2.x",
"python_3.x"
] | stackoverflow_0003384361_python_python_2.x_python_3.x.txt |
Q:
Most memory-efficient way of holding base64 data in Python?
Suppose you have a MD5 hash encoded in base64. Then each
character needs only 6 bits to store each character in the
resultant 22-byte string (excluding the ending '=='). Thus, each
base64 md5 hash can shrink down to 6*22 = 132 bits, which
requires 25% less memory space compared to the original 8*22=176
bits string.
Is there any Python module or function that lets you store base64
data in the way described above?
A:
The most efficient way to store base64 encoded data is to decode it and store it as binary. base64 is a transport encoding - there's no sense in storing data in it, especially in memory, unless you have a compelling reason otherwise.
Also, nitpick: The output of a hash function is not a hex string - that's just a common representation. The output of a hash function is some number of bytes of binary data. If you're using the md5, sha, or hashlib modules, for example, you don't need to encode it as anything in the first place - just call .digest() instead of .hexdigest() on the hash object.
A:
Simply decode the base64 data to binary:
>>> b64 = "COIC09jwcwjiciOEIWIUNIUNE9832iun"
>>> len(b64)
32
>>> b = b64.decode("base64")
>>> b
'\x08\xe2\x02\xd3\xd8\xf0s\x08\xe2r#\x84!b\x144\x85\r\x13\xdf7\xda+\xa7'
>>> len(b)
24
A:
"store base64 data"
Don't.
Do. Not. Store. Base64. Data.
Base64 is built by encoding something to make it bigger.
Store the original something. Never store the base64 encoding of something.
A:
David gave an answer that works on all base64 strings.
Just use base64.decodestring in base64 module. That is,
import base64
binary = base64.decodestring(base64_string)
is a more memory efficient representation of the original base64 string. If you
are truncating trailing '==' in your base64 md5, use it like
base64.decodestring(md5+'==')
| Most memory-efficient way of holding base64 data in Python? | Suppose you have a MD5 hash encoded in base64. Then each
character needs only 6 bits to store each character in the
resultant 22-byte string (excluding the ending '=='). Thus, each
base64 md5 hash can shrink down to 6*22 = 132 bits, which
requires 25% less memory space compared to the original 8*22=176
bits string.
Is there any Python module or function that lets you store base64
data in the way described above?
| [
"The most efficient way to store base64 encoded data is to decode it and store it as binary. base64 is a transport encoding - there's no sense in storing data in it, especially in memory, unless you have a compelling reason otherwise.\nAlso, nitpick: The output of a hash function is not a hex string - that's just a... | [
8,
5,
4,
1
] | [] | [] | [
"algorithm",
"base64",
"data_structures",
"md5",
"python"
] | stackoverflow_0003430016_algorithm_base64_data_structures_md5_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.