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:
Parse a map of int -> list from a string
This should be a fairly straight forward python question, but I'm getting stuck getting the syntax right.
Let's say I have a string:
"1:a,b,c::2:e,f,g::3:h,i,j"
and I want to convert this to a map like so:
{'1': ['a', 'b', 'c'], '2': ['e', 'f', 'g'], '3': ['h', 'i', 'j']}
How would this be done?
I can figure out how to do it using nested for loops, but would be cool to just do it in a single line.
Thanks!
A:
Here's one approach:
dict((k, v.split(',')) for k,v in (x.split(':') for x in s.split('::')))
| Parse a map of int -> list from a string | This should be a fairly straight forward python question, but I'm getting stuck getting the syntax right.
Let's say I have a string:
"1:a,b,c::2:e,f,g::3:h,i,j"
and I want to convert this to a map like so:
{'1': ['a', 'b', 'c'], '2': ['e', 'f', 'g'], '3': ['h', 'i', 'j']}
How would this be done?
I can figure out how to do it using nested for loops, but would be cool to just do it in a single line.
Thanks!
| [
"Here's one approach:\ndict((k, v.split(',')) for k,v in (x.split(':') for x in s.split('::')))\n\n"
] | [
8
] | [] | [] | [
"python"
] | stackoverflow_0003918797_python.txt |
Q:
How to make sure a file exists or can be created before writing to it in Python?
I'm writing a function and I want it to touch a file so that I can write to that file. If the file doesn't exist, I will get an error. How can I say that?
A:
Just open the file for writing and it will be created if it doesn't exist (assuming you have proper permission to write to that location).
f = open('some_file_that_might_not_exist.txt', 'w')
f.write(data)
You will get an IOError if you can't open the file for writing.
A:
Per the docs, os.utime() will function similar to touch if you give it None as the time argument, for example:
os.utime("test_file", None)
When I tested this (on Linux and later Windows), I found that test_file had to already exist. YMMV on other OS's.
Of course, this doesn't really address writing to the file. As other answers have said, you usually want open for that and try ... except for catching exceptions when the file does not exist.
A:
if you actually want to raise an error if the file doesn't exist, you can use
import os
if not os.access('file'):
#raise error
f = open('file')
#etc.
| How to make sure a file exists or can be created before writing to it in Python? | I'm writing a function and I want it to touch a file so that I can write to that file. If the file doesn't exist, I will get an error. How can I say that?
| [
"Just open the file for writing and it will be created if it doesn't exist (assuming you have proper permission to write to that location).\nf = open('some_file_that_might_not_exist.txt', 'w')\nf.write(data)\n\nYou will get an IOError if you can't open the file for writing.\n",
"Per the docs, os.utime() will func... | [
12,
7,
0
] | [] | [] | [
"file_io",
"filesystems",
"python"
] | stackoverflow_0003918433_file_io_filesystems_python.txt |
Q:
How can I put only value after decimal
I have got output and I want to use only three values after decimal. How can i do that in Python?
A:
Use the following:
"%.3f" % x
it converts your number to a string with three decimal places.
A:
In Python 2.6 or newer you should use the str.format method:
>>> x = 15.23432
>>> '{0:.3f}'.format(x)
'15.234'
A:
round(number, 3)
http://docs.python.org/tutorial/floatingpoint.html
| How can I put only value after decimal | I have got output and I want to use only three values after decimal. How can i do that in Python?
| [
"Use the following:\n\"%.3f\" % x\n\nit converts your number to a string with three decimal places.\n",
"In Python 2.6 or newer you should use the str.format method:\n>>> x = 15.23432\n>>> '{0:.3f}'.format(x)\n'15.234'\n\n",
"round(number, 3)\nhttp://docs.python.org/tutorial/floatingpoint.html\n"
] | [
4,
4,
3
] | [] | [] | [
"floating_point",
"python"
] | stackoverflow_0003918878_floating_point_python.txt |
Q:
Object vs. class variable
This is a completely theoretical question. Suppose the following code:
>>> class C:
... a = 10
... def f(self): self.a = 999
...
>>>
>>> C.a
10
>>> c = C()
>>> c.a
10
>>> c.f()
>>> c.a
999
At this point, is class variable C.a still accessible through the object c?
A:
Yes, though c.__class__.a or type(c).a. The two differ slightly in that old-style classes (hopefully, those are all dead by now - but you never know...) have a type() of <type 'instance'> (and __class__ works as expected) while for new-style classes, type() is identical to __class__ except when the object overrides attribute access.
A:
All class variables are accessible through objects instantiated from that class.
>>> class C:
... a = 10
... def f(self): self.a = 999
...
>>> C.a
10
>>> c = C()
>>> c.a
10
>>> c.f()
>>> c.a
999
>>> c.__class__.a
10
>>> c.a
999
>>> del(c.a)
>>> c.a
10
Attributes are first searched within the object namespace and then class.
A:
Yes, you can access a from an object c, à la c.a. The value would initially be 10.
However, if you call c.f(), the value of c.a will now be 999, but C.a will still be 10. Likewise, if you now change C.a to, say, 1000, c.a will still be 999.
Basically, when you instantiate an instance of C, it will use the class variable as its own a value, until you change the value of that instance's a, in which case it will no longer "share" a with the class.
A:
After you assign to it on the class instance, there is both a class attribute named a and an instance attribute named a. I illustrate:
>>> class Foo(object):
... a = 10
...
>>> c = Foo()
>>> c.a
10
>>> c.a = 100 # this doesn't have to be done in a method
>>> c.a # a is now an instance attribute
100
>>> Foo.a # that is shadowing the class attribute
10
>>> del c.a # get rid of the instance attribute
>>> c.a # and you can see the class attribute again
10
>>>
The difference is that one exists as an entry in Foo.__dict__ and the other exists as an entry in c.__dict__. When you access instance.attribute, instance.__dict__['attribute'] is returned if it exists and if not then type(instance).__dict__['attribute'] is checked. Then the superclasses of the class are checked but that gets slightly more complicated.
But at any rate, the main point is that it doesn't have to be one or the other. A class and an instance can both have distinct attributes with identical names because they are stored in two separate dicts.
| Object vs. class variable | This is a completely theoretical question. Suppose the following code:
>>> class C:
... a = 10
... def f(self): self.a = 999
...
>>>
>>> C.a
10
>>> c = C()
>>> c.a
10
>>> c.f()
>>> c.a
999
At this point, is class variable C.a still accessible through the object c?
| [
"Yes, though c.__class__.a or type(c).a. The two differ slightly in that old-style classes (hopefully, those are all dead by now - but you never know...) have a type() of <type 'instance'> (and __class__ works as expected) while for new-style classes, type() is identical to __class__ except when the object override... | [
4,
1,
1,
1
] | [] | [] | [
"python",
"syntax",
"theory"
] | stackoverflow_0003918761_python_syntax_theory.txt |
Q:
Writing empty string to textfile in Python
Quite embarassing issue, though i come from web development and rarely have to deal with files i/o.
I wrote a simple config updater for use on my shared hosting. It scans the directory for subdirectories, and then writes config lines to a file - one line for each subdirectory. The problem is, when it detects there are config lines but no subdirectories, it's supposed to leave config empty - which doesn't work! Coming here with this because docs aren't mention it and google isn't helpful either. Its Python 2.6.6 on Debian Lenny.
file = open('path', 'r+')
config = file.read()
## all the code inbetween works fine
## config is .split()-ed, hence the list
if config == ['']:
config = ''
file.write(config)
file.close()
In this case, file isn't changed at all. The funny thing is, making it forget config and just do file.write('') doesn't empty the file either, but puts \n in seemingly random positon of the line.
A:
You're using the r+ read-write mode. All reads and all writes update the file's position.
Try:
file = open('path', 'r+')
config = file.read()
## all the code inbetween works fine
## config is .split()-ed, hence the list
if config == ['']:
config = ''
file.seek(0) # rewind the file
file.write(config)
file.close()
A:
You might want to use the 'w+' mode in the open call, to truncate the file.
A:
If you're trying to empty the file, use truncate:
f.truncate(0)
f.close()
| Writing empty string to textfile in Python | Quite embarassing issue, though i come from web development and rarely have to deal with files i/o.
I wrote a simple config updater for use on my shared hosting. It scans the directory for subdirectories, and then writes config lines to a file - one line for each subdirectory. The problem is, when it detects there are config lines but no subdirectories, it's supposed to leave config empty - which doesn't work! Coming here with this because docs aren't mention it and google isn't helpful either. Its Python 2.6.6 on Debian Lenny.
file = open('path', 'r+')
config = file.read()
## all the code inbetween works fine
## config is .split()-ed, hence the list
if config == ['']:
config = ''
file.write(config)
file.close()
In this case, file isn't changed at all. The funny thing is, making it forget config and just do file.write('') doesn't empty the file either, but puts \n in seemingly random positon of the line.
| [
"You're using the r+ read-write mode. All reads and all writes update the file's position.\nTry:\nfile = open('path', 'r+')\nconfig = file.read()\n## all the code inbetween works fine\n## config is .split()-ed, hence the list\nif config == ['']:\n config = ''\nfile.seek(0) # rewind the file\nfile.write(config... | [
3,
2,
2
] | [] | [] | [
"file_io",
"python"
] | stackoverflow_0003919382_file_io_python.txt |
Q:
How do I plot multiple X or Y axes in matplotlib?
I'm currently using matplotlib to plot a measurement against 2 or 3 other measurements (sometimes categorical) on the x-axis. Currently, I am grouping the data on the x-axis into tuples and sorting them before plotting... the result looks something like the left image below. What I would like to do is to plot the data with multiple x-axes as you see in the right image. The grouping of the "treatment" x-axis labels would be icing on the cake.
A:
First off, cool question! It's definitely possible with matplotlib >= 1.0.0. (The new spines functionality allows it)
It requires a fair bit of voodoo, though... My example is far from perfect, but hopefully it makes some sense:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
def main():
#-- Generate some data ----------------------------------------------------
nx = 10
x = np.linspace(0, 2*np.pi, 10)
y = 2 * np.sin(x)
groups = [('GroupA', (x[0], x[nx//3])),
('GroupB', (x[-2*nx//3], x[2*nx//3])),
('GroupC', (x[-nx//3], x[-1]))]
#-- Plot the results ------------------------------------------------------
fig = plt.figure()
ax = fig.add_subplot(111)
# Give ourselves a bit more room at the bottom
plt.subplots_adjust(bottom=0.2)
ax.plot(x,y, 'k^')
# Drop the bottom spine by 40 pts
ax.spines['bottom'].set_position(('outward', 40))
# Make a second bottom spine in the position of the original bottom spine
make_second_bottom_spine(label='Treatment')
# Annotate the groups
for name, xspan in groups:
annotate_group(name, xspan)
plt.xlabel('Dose')
plt.ylabel('Response')
plt.title('Experimental Data')
plt.show()
def annotate_group(name, xspan, ax=None):
"""Annotates a span of the x-axis"""
def annotate(ax, name, left, right, y, pad):
arrow = ax.annotate(name,
xy=(left, y), xycoords='data',
xytext=(right, y-pad), textcoords='data',
annotation_clip=False, verticalalignment='top',
horizontalalignment='center', linespacing=2.0,
arrowprops=dict(arrowstyle='-', shrinkA=0, shrinkB=0,
connectionstyle='angle,angleB=90,angleA=0,rad=5')
)
return arrow
if ax is None:
ax = plt.gca()
ymin = ax.get_ylim()[0]
ypad = 0.01 * np.ptp(ax.get_ylim())
xcenter = np.mean(xspan)
left_arrow = annotate(ax, name, xspan[0], xcenter, ymin, ypad)
right_arrow = annotate(ax, name, xspan[1], xcenter, ymin, ypad)
return left_arrow, right_arrow
def make_second_bottom_spine(ax=None, label=None, offset=0, labeloffset=20):
"""Makes a second bottom spine"""
if ax is None:
ax = plt.gca()
second_bottom = mpl.spines.Spine(ax, 'bottom', ax.spines['bottom']._path)
second_bottom.set_position(('outward', offset))
ax.spines['second_bottom'] = second_bottom
if label is not None:
# Make a new xlabel
ax.annotate(label,
xy=(0.5, 0), xycoords='axes fraction',
xytext=(0, -labeloffset), textcoords='offset points',
verticalalignment='top', horizontalalignment='center')
if __name__ == '__main__':
main()
A:
Joe's example is good. I'll throw mine in too. I was working on it a few hours ago, but then had to run off to a meeting. It steals from here.
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
## the following two functions override the default behavior or twiny()
def make_patch_spines_invisible(ax):
ax.set_frame_on(True)
ax.patch.set_visible(False)
for sp in ax.spines.itervalues():
sp.set_visible(False)
def make_spine_invisible(ax, direction):
if direction in ["right", "left"]:
ax.yaxis.set_ticks_position(direction)
ax.yaxis.set_label_position(direction)
elif direction in ["top", "bottom"]:
ax.xaxis.set_ticks_position(direction)
ax.xaxis.set_label_position(direction)
else:
raise ValueError("Unknown Direction : %s" % (direction,))
ax.spines[direction].set_visible(True)
data = (('A',0.01),('A',0.02),('B',0.10),('B',0.20)) # fake data
fig = plt.figure(1)
sb = fig.add_subplot(111)
sb.xaxis.set_major_locator(ticker.FixedLocator([0,1,2,3]))
sb.plot([i[1] for i in data],"*",markersize=10)
sb.set_xlabel("dose")
plt.subplots_adjust(bottom=0.17) # make room on bottom
par2 = sb.twiny() # create a second axes
par2.spines["bottom"].set_position(("axes", -.1)) # move it down
## override the default behavior for a twiny axis
make_patch_spines_invisible(par2)
make_spine_invisible(par2, "bottom")
par2.set_xlabel("treatment")
par2.plot([i[1] for i in data],"*",markersize=10) #redraw to put twiny on same scale
par2.xaxis.set_major_locator(ticker.FixedLocator([0,1,2,3]))
par2.xaxis.set_ticklabels([i[0] for i in data])
plt.show()
Produces:
| How do I plot multiple X or Y axes in matplotlib? | I'm currently using matplotlib to plot a measurement against 2 or 3 other measurements (sometimes categorical) on the x-axis. Currently, I am grouping the data on the x-axis into tuples and sorting them before plotting... the result looks something like the left image below. What I would like to do is to plot the data with multiple x-axes as you see in the right image. The grouping of the "treatment" x-axis labels would be icing on the cake.
| [
"First off, cool question! It's definitely possible with matplotlib >= 1.0.0. (The new spines functionality allows it) \nIt requires a fair bit of voodoo, though... My example is far from perfect, but hopefully it makes some sense:\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\n\... | [
21,
10
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0003918028_matplotlib_python.txt |
Q:
how to add python to system dependency on win7?
i've got a problem when i'm doing dev
I managed to use
python manage.py runserver in a CMD shell
but the system cant find python
How could I add python to the system dependency to make the commandline work?
A:
There are two basic ways you can do this in Windows.
Setting the PATH in the cmd shell
The first way is only local to the CMD shell you are currently in, and will have to be done again if you opened a new shell.
You can set your PATH to include the directory where python.exe is located.
In your CMD shell you can do:
set PATH=%PATH%;C:\path\to\python\install
So if Python was installed in C:\Python27, you would do this:
set PATH=%PATH%;C:\Python27
Setting the environment for your user throughout Windows
Alternatively, you can set your PATH permanently by changing the environment variable in Windows. Setting this will affect the rest of your Windows environment.
Right click "My Computer"
Select "Properties"
Click the "Advanced" tab in the new window.
Click on the "Environment Variables" button.
Edit the variable named PATH
Information about doing the latter at Microsoft: http://support.microsoft.com/kb/310519
| how to add python to system dependency on win7? | i've got a problem when i'm doing dev
I managed to use
python manage.py runserver in a CMD shell
but the system cant find python
How could I add python to the system dependency to make the commandline work?
| [
"There are two basic ways you can do this in Windows. \nSetting the PATH in the cmd shell\nThe first way is only local to the CMD shell you are currently in, and will have to be done again if you opened a new shell.\nYou can set your PATH to include the directory where python.exe is located.\nIn your CMD shell you ... | [
2
] | [] | [] | [
"django",
"installation",
"python"
] | stackoverflow_0003920151_django_installation_python.txt |
Q:
python number guessing question
import sys
print 'Content-Type: text/html'
print ''
print '<pre>'
# Read the form input which is a single line
guess = -1
data = sys.stdin.read()
# print data
if data == []:
print "Welcome to Josh's number game"
try:
guess = int(data[data.find('=')+1:])
except:
guess = -1
print 'Your guess is', guess
answer = 42
if guess < answer :
print 'Your guess is too low'
if guess == answer:
print 'Congratulations!'
if guess > answer :
print 'Your guess is too high'
print '</pre>'
print '''<form method="post" action="/">
Enter Guess: <input type="text" name="guess"><br>
<input type="submit">
</form>'''
Right now the program tells you if your guess is too low, too high or right on. I want to add two more messages, one for when someone does not enter any input in the field. And another one for someone who enters invalid input (like a string or something) instead of a number. My field
data == [] is meant to show no input in the field, but it doesn't work as I thought. Can you help?
A:
data is a string and will never equal [], which is a list. Try data.strip() == "".
EDIT: It just occurred to me that you probably meant to use sys.stdin.readlines(), which does return a list. But instead of "fixing" this, I strongly recommend you follow @Zack's advice regarding CGI.
A:
sys.stdin.read() will give you an empty string if there's no input, so data == [] should be
data == ''.
The message for invalid input is probably best put inside the except: clause that you already have (you'll need to rearrange your control flow a bit so that becomes exclusive with the number-checking part).
Also, you may find the cgi module useful for what it looks like you're doing.
| python number guessing question | import sys
print 'Content-Type: text/html'
print ''
print '<pre>'
# Read the form input which is a single line
guess = -1
data = sys.stdin.read()
# print data
if data == []:
print "Welcome to Josh's number game"
try:
guess = int(data[data.find('=')+1:])
except:
guess = -1
print 'Your guess is', guess
answer = 42
if guess < answer :
print 'Your guess is too low'
if guess == answer:
print 'Congratulations!'
if guess > answer :
print 'Your guess is too high'
print '</pre>'
print '''<form method="post" action="/">
Enter Guess: <input type="text" name="guess"><br>
<input type="submit">
</form>'''
Right now the program tells you if your guess is too low, too high or right on. I want to add two more messages, one for when someone does not enter any input in the field. And another one for someone who enters invalid input (like a string or something) instead of a number. My field
data == [] is meant to show no input in the field, but it doesn't work as I thought. Can you help?
| [
"data is a string and will never equal [], which is a list. Try data.strip() == \"\".\nEDIT: It just occurred to me that you probably meant to use sys.stdin.readlines(), which does return a list. But instead of \"fixing\" this, I strongly recommend you follow @Zack's advice regarding CGI.\n",
"sys.stdin.read() wi... | [
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0003920155_python.txt |
Q:
will yum break if I use rpms from the ius community project?
I followed this tutorial: http://blog.boxedice.com/2010/01/19/updating-python-on-rhelcentos/ because I wanted to install python2.6 on a CentOS 5.5 machine without breaking yum.
And i was successfully able install python2.6. My question is that after completing the above commands the next time I try installing packages will it automatically use the one from ius if the packages is conflicting? And if yes will it break something else?
I'm just worried that the next time someone runs yum it'll download a conflicting package from ius and break.
A:
I am the primary maintainer of the IUS Community Project. This question would be better asked via the 'answers' section of our project page on http://launchpad.net/ius.
Regardless, I am more than happy to clarify for you. IUS provides packages that strictly conflict with packages in RHEL... meaning if the original package is installed, and you attempt to install a replacement from IUS then Yum will bail with a conflict error. However, IUS also strictly does not obsolete anything in RHEL... meaning, nothing should automatically install from IUS unless you explicitly remove the original package, and replace it with something from IUS.
Be careful about installing python modules from RHEL repos with the new python runtime
This is actually not something to be concerned with for the python26 package as it is a parallel install (side-by-side) package and does not replace the system python or libraries (it is/was the only package in IUS that did not replace the system version).
On another note, python26 was EOL'd from IUS and moved to EPEL therefore the python26 package you installed is likely from EPEL. IUS relies on, and contributes to EPEL as well.
If you are concerned with Yum breakage due to subscription to third party repos, you may wish to read the Safe Repo Initiative which was written by and adhered to by the IUS Community Project
A:
It looks like you just installed a .rpm package from some third party. Everything should be fine. Be careful about installing python modules from RHEL repos with the new python runtime (ie watch out for bugs and breakage from third party modules that expected to run on python 2.5).
Since the ius python package is a higher version than the one from RHEL's repos, it will not be downgraded automatically by updates etc.
| will yum break if I use rpms from the ius community project? | I followed this tutorial: http://blog.boxedice.com/2010/01/19/updating-python-on-rhelcentos/ because I wanted to install python2.6 on a CentOS 5.5 machine without breaking yum.
And i was successfully able install python2.6. My question is that after completing the above commands the next time I try installing packages will it automatically use the one from ius if the packages is conflicting? And if yes will it break something else?
I'm just worried that the next time someone runs yum it'll download a conflicting package from ius and break.
| [
"I am the primary maintainer of the IUS Community Project. This question would be better asked via the 'answers' section of our project page on http://launchpad.net/ius. \nRegardless, I am more than happy to clarify for you. IUS provides packages that strictly conflict with packages in RHEL... meaning if the ori... | [
4,
1
] | [] | [] | [
"centos5",
"linux",
"python",
"rhel",
"rpm"
] | stackoverflow_0003916603_centos5_linux_python_rhel_rpm.txt |
Q:
Python: How to loop through blocks of lines
How to go through blocks of lines separated by an empty line? The file looks like the following:
ID: 1
Name: X
FamilyN: Y
Age: 20
ID: 2
Name: H
FamilyN: F
Age: 23
ID: 3
Name: S
FamilyN: Y
Age: 13
ID: 4
Name: M
FamilyN: Z
Age: 25
I want to loop through the blocks and grab the fields Name, Family name and Age in a list of 3 columns:
Y X 20
F H 23
Y S 13
Z M 25
A:
Here's another way, using itertools.groupby.
The function groupy iterates through lines of the file and calls isa_group_separator(line) for each line. isa_group_separator returns either True or False (called the key), and itertools.groupby then groups all the consecutive lines that yielded the same True or False result.
This is a very convenient way to collect lines into groups.
import itertools
def isa_group_separator(line):
return line=='\n'
with open('data_file') as f:
for key,group in itertools.groupby(f,isa_group_separator):
# print(key,list(group)) # uncomment to see what itertools.groupby does.
if not key: # however, this will make the rest of the code not work
data={} # as it exhausts the `group` iterator
for item in group:
field,value=item.split(':')
value=value.strip()
data[field]=value
print('{FamilyN} {Name} {Age}'.format(**data))
# Y X 20
# F H 23
# Y S 13
# Z M 25
A:
Use a generator.
def blocks( iterable ):
accumulator= []
for line in iterable:
if start_pattern( line ):
if accumulator:
yield accumulator
accumulator= []
# elif other significant patterns
else:
accumulator.append( line )
if accumulator:
yield accumulator
A:
import re
result = re.findall(
r"""(?mx) # multiline, verbose regex
^ID:.*\s* # Match ID: and anything else on that line
Name:\s*(.*)\s* # Match name, capture all characters on this line
FamilyN:\s*(.*)\s* # etc. for family name
Age:\s*(.*)$ # and age""",
subject)
Result will then be
[('X', 'Y', '20'), ('H', 'F', '23'), ('S', 'Y', '13'), ('M', 'Z', '25')]
which can be trivially changed into whatever string representation you want.
A:
If file is not huge you can read whole file with:
content = f.open(filename).read()
then you can split content to blocks using:
blocks = content.split('\n\n')
Now you can create function to parse block of text. I would use split('\n') to get lines from block and split(':') to get key and value, eventually with str.strip() or some help of regular expressions.
Without checking if block has required data code can look like:
f = open('data.txt', 'r')
content = f.read()
f.close()
for block in content.split('\n\n'):
person = {}
for l in block.split('\n'):
k, v = l.split(': ')
person[k] = v
print('%s %s %s' % (person['FamilyN'], person['Name'], person['Age']))
A:
If your file is too large to read into memory all at once, you can still use a regular expressions based solution by using a memory mapped file, with the mmap module:
import sys
import re
import os
import mmap
block_expr = re.compile('ID:.*?\nAge: \d+', re.DOTALL)
filepath = sys.argv[1]
fp = open(filepath)
contents = mmap.mmap(fp.fileno(), os.stat(filepath).st_size, access=mmap.ACCESS_READ)
for block_match in block_expr.finditer(contents):
print block_match.group()
The mmap trick will provide a "pretend string" to make regular expressions work on the file without having to read it all into one large string. And the find_iter() method of the regular expression object will yield matches without creating an entire list of all matches at once (which findall() does).
I do think this solution is overkill for this use case however (still: it's a nice trick to know...)
A:
import itertools
# Assuming input in file input.txt
data = open('input.txt').readlines()
records = (lines for valid, lines in itertools.groupby(data, lambda l : l != '\n') if valid)
output = [tuple(field.split(':')[1].strip() for field in itertools.islice(record, 1, None)) for record in records]
# You can change output to generator by
output = (tuple(field.split(':')[1].strip() for field in itertools.islice(record, 1, None)) for record in records)
# output = [('X', 'Y', '20'), ('H', 'F', '23'), ('S', 'Y', '13'), ('M', 'Z', '25')]
#You can iterate and change the order of elements in the way you want
# [(elem[1], elem[0], elem[2]) for elem in output] as required in your output
A:
This answer isn't necessarily better than what's already been posted, but as an illustration of how I approach problems like this it might be useful, especially if you're not used to working with Python's interactive interpreter.
I've started out knowing two things about this problem. First, I'm going to use itertools.groupby to group the input into lists of data lines, one list for each individual data record. Second, I want to represent those records as dictionaries so that I can easily format the output.
One other thing that this shows is how using generators makes breaking a problem like this down into small parts easy.
>>> # first let's create some useful test data and put it into something
>>> # we can easily iterate over:
>>> data = """ID: 1
Name: X
FamilyN: Y
Age: 20
ID: 2
Name: H
FamilyN: F
Age: 23
ID: 3
Name: S
FamilyN: Y
Age: 13"""
>>> data = data.split("\n")
>>> # now we need a key function for itertools.groupby.
>>> # the key we'll be grouping by is, essentially, whether or not
>>> # the line is empty.
>>> # this will make groupby return groups whose key is True if we
>>> care about them.
>>> def is_data(line):
return True if line.strip() else False
>>> # make sure this really works
>>> "\n".join([line for line in data if is_data(line)])
'ID: 1\nName: X\nFamilyN: Y\nAge: 20\nID: 2\nName: H\nFamilyN: F\nAge: 23\nID: 3\nName: S\nFamilyN: Y\nAge: 13\nID: 4\nName: M\nFamilyN: Z\nAge: 25'
>>> # does groupby return what we expect?
>>> import itertools
>>> [list(value) for (key, value) in itertools.groupby(data, is_data) if key]
[['ID: 1', 'Name: X', 'FamilyN: Y', 'Age: 20'], ['ID: 2', 'Name: H', 'FamilyN: F', 'Age: 23'], ['ID: 3', 'Name: S', 'FamilyN: Y', 'Age: 13'], ['ID: 4', 'Name: M', 'FamilyN: Z', 'Age: 25']]
>>> # what we really want is for each item in the group to be a tuple
>>> # that's a key/value pair, so that we can easily create a dictionary
>>> # from each item.
>>> def make_key_value_pair(item):
items = item.split(":")
return (items[0].strip(), items[1].strip())
>>> make_key_value_pair("a: b")
('a', 'b')
>>> # let's test this:
>>> dict(make_key_value_pair(item) for item in ["a:1", "b:2", "c:3"])
{'a': '1', 'c': '3', 'b': '2'}
>>> # we could conceivably do all this in one line of code, but this
>>> # will be much more readable as a function:
>>> def get_data_as_dicts(data):
for (key, value) in itertools.groupby(data, is_data):
if key:
yield dict(make_key_value_pair(item) for item in value)
>>> list(get_data_as_dicts(data))
[{'FamilyN': 'Y', 'Age': '20', 'ID': '1', 'Name': 'X'}, {'FamilyN': 'F', 'Age': '23', 'ID': '2', 'Name': 'H'}, {'FamilyN': 'Y', 'Age': '13', 'ID': '3', 'Name': 'S'}, {'FamilyN': 'Z', 'Age': '25', 'ID': '4', 'Name': 'M'}]
>>> # now for an old trick: using a list of column names to drive the output.
>>> columns = ["Name", "FamilyN", "Age"]
>>> print "\n".join(" ".join(d[c] for c in columns) for d in get_data_as_dicts(data))
X Y 20
H F 23
S Y 13
M Z 25
>>> # okay, let's package this all into one function that takes a filename
>>> def get_formatted_data(filename):
with open(filename, "r") as f:
columns = ["Name", "FamilyN", "Age"]
for d in get_data_as_dicts(f):
yield " ".join(d[c] for c in columns)
>>> print "\n".join(get_formatted_data("c:\\temp\\test_data.txt"))
X Y 20
H F 23
S Y 13
M Z 25
A:
Use a dict, namedtuple, or custom class to store each attribute as you come across it, then append the object to a list when you reach a blank line or EOF.
A:
simple solution:
result = []
for record in content.split('\n\n'):
try:
id, name, familyn, age = map(lambda rec: rec.split(' ', 1)[1], record.split('\n'))
except ValueError:
pass
except IndexError:
pass
else:
result.append((familyn, name, age))
A:
Along with the half-dozen other solutions I already see here, I'm a bit surprised that no one has been so simple-minded (that is, generator-, regex-, map-, and read-free) as to propose, for example,
fp = open(fn)
def get_one_value():
line = fp.readline()
if not line:
return None
parts = line.split(':')
if 2 != len(parts):
return ''
return parts[1].strip()
# The result is supposed to be a list.
result = []
while 1:
# We don't care about the ID.
if get_one_value() is None:
break
name = get_one_value()
familyn = get_one_value()
age = get_one_value()
result.append((name, familyn, age))
# We don't care about the block separator.
if get_one_value() is None:
break
for item in result:
print item
Re-format to taste.
| Python: How to loop through blocks of lines | How to go through blocks of lines separated by an empty line? The file looks like the following:
ID: 1
Name: X
FamilyN: Y
Age: 20
ID: 2
Name: H
FamilyN: F
Age: 23
ID: 3
Name: S
FamilyN: Y
Age: 13
ID: 4
Name: M
FamilyN: Z
Age: 25
I want to loop through the blocks and grab the fields Name, Family name and Age in a list of 3 columns:
Y X 20
F H 23
Y S 13
Z M 25
| [
"Here's another way, using itertools.groupby.\nThe function groupy iterates through lines of the file and calls isa_group_separator(line) for each line. isa_group_separator returns either True or False (called the key), and itertools.groupby then groups all the consecutive lines that yielded the same True or False ... | [
12,
5,
4,
2,
2,
2,
1,
0,
0,
0
] | [] | [] | [
"python",
"text_processing"
] | stackoverflow_0003914454_python_text_processing.txt |
Q:
Picking out symbols from a code base with Python
Given a code base (say for example a large C or Objective-C project) I would like to analyze the sourcecode files and pick out symbols of interest. They might be class declarations, variable names or types, or method names. Is there a Python module that could help me with this?
The only approach I can see going forward is to use regular expressions to gather these symbols, but I'm thinking this could get very ugly very quickly. I'm also not an expert in compilers or parsers, so something lighter-weight would be prefereable.
thanks for any suggestions.
------ update -----
thanks for all of the suggestions so far, definitely some promising leads. One other avenue that may be possible: what if I were able to compile the project I was trying to analyze. Would the debugging symbols (dsym) make this process any easier? I'm not looking for anything advanced, just a list of classes, with their ivar and method names. At this point, looking into the parsing tools suggested seem like more work than I can afford to invest in this project right now
A:
Regex is definitely not a good way to examine programming language code. I would suggest choosing a parsing module from the links provided below.
There are a few tools out there that you could use. They all provide parsing facility. You can always build your stuff on top of that:
http://code.google.com/p/pycparser/
Many tools at : http://wiki.python.org/moin/LanguageParsing
http://www.boost.org/doc/libs/1_44_0/libs/python/pyste/doc/introduction.html
pygccxml generates xml description from c++ program files. This might be closer to what you are trying to do:
http://www.language-binding.net/pygccxml/pygccxml.html
Also look at this, it generate navigable class tree representing the class structure.
http://sourceforge.net/projects/cppheaderparser/
A:
Regular expressions are not the way to go here. The languages already have a defined grammar, so use that.
A:
Our Search Engine has a facility for picking all identifiers using the langauge structure (it specifically handles C at this point, but not Objective C). The Search Engine provides an interactive query langauge for searching for various langauge constructs, displaying hits, and displaying source text that matches hits. We are about to release a version that finds definitions and uses, which would pick out function/type/variable declarations directly. This would be considered "lightweight".
Related is the Search Engine's big brother, the DMS Software Reengineeering Toolkit. DMS with its C Front End provides the ability to fully parse C code and find arbitrary symbol definitions. This would be considered "heavy duty" in that it has a full preprocessor and gets the definition information absolutely right, as well as providing complete access to the AST that associated with the symbol name (declaration, function, typedef, ...).
These are not Python modules, but do provide precise access to the kind of informaiton likely of interest.
| Picking out symbols from a code base with Python | Given a code base (say for example a large C or Objective-C project) I would like to analyze the sourcecode files and pick out symbols of interest. They might be class declarations, variable names or types, or method names. Is there a Python module that could help me with this?
The only approach I can see going forward is to use regular expressions to gather these symbols, but I'm thinking this could get very ugly very quickly. I'm also not an expert in compilers or parsers, so something lighter-weight would be prefereable.
thanks for any suggestions.
------ update -----
thanks for all of the suggestions so far, definitely some promising leads. One other avenue that may be possible: what if I were able to compile the project I was trying to analyze. Would the debugging symbols (dsym) make this process any easier? I'm not looking for anything advanced, just a list of classes, with their ivar and method names. At this point, looking into the parsing tools suggested seem like more work than I can afford to invest in this project right now
| [
"Regex is definitely not a good way to examine programming language code. I would suggest choosing a parsing module from the links provided below.\nThere are a few tools out there that you could use. They all provide parsing facility. You can always build your stuff on top of that:\n\nhttp://code.google.com/p/pycpa... | [
5,
1,
1
] | [] | [] | [
"parsing",
"python"
] | stackoverflow_0003919922_parsing_python.txt |
Q:
Running mysqldump through Python's subprocess module is slow and verbose
@cost_time
def dbdump_all():
"导出数据库所有数据至当前目录下以年月日命名的sql文件"
filename=datetime.datetime.now().strftime("%Y-%m-%d")
cmd="""mysqldump -u root -pzhoubt --opt --quick --database search > ./%s.sql"""%filename
args=shlex.split(cmd)
p=subprocess.Popen(args)
#stdout, stderr = p.communicate()
#print stdout,stderr
print "已将数据库表结构和数据导出到%s"%filename
I use the mysqldump command in a subprocess, and it outputs a lot of information about the exported data, even if I comment out the stdout, stderr = p.communicate() line. It's also very slow, even though I've tried the same command in a shell and it's very quick and succinct. How can I avoid all the verbosity when using subprocess, and speed up the time it takes to be more like running it directly from a shell?
A:
@cost_time
def dbdump_all():
"导出数据库所有数据至当前目录下以年月日命名的sql文件"
filename=datetime.datetime.now().strftime("%Y-%m-%d")+".sql"
cmd="""mysqldump -u root -pzhoubt --opt --quick --database search >./%s"""%filename
print cmd
p=subprocess.Popen(cmd,shell=True,cwd=os.getcwd())
sts = os.waitpid(p.pid, 0)[1]
print "返回状态%s"%sts
print "已将数据库表结构和数据导出到%s"%filename
finally i got it,
the key is us os.waitpid to wait mysql processing,
another point is when you use shell the cmd is a string not a list
| Running mysqldump through Python's subprocess module is slow and verbose | @cost_time
def dbdump_all():
"导出数据库所有数据至当前目录下以年月日命名的sql文件"
filename=datetime.datetime.now().strftime("%Y-%m-%d")
cmd="""mysqldump -u root -pzhoubt --opt --quick --database search > ./%s.sql"""%filename
args=shlex.split(cmd)
p=subprocess.Popen(args)
#stdout, stderr = p.communicate()
#print stdout,stderr
print "已将数据库表结构和数据导出到%s"%filename
I use the mysqldump command in a subprocess, and it outputs a lot of information about the exported data, even if I comment out the stdout, stderr = p.communicate() line. It's also very slow, even though I've tried the same command in a shell and it's very quick and succinct. How can I avoid all the verbosity when using subprocess, and speed up the time it takes to be more like running it directly from a shell?
| [
"@cost_time\ndef dbdump_all():\n \"导出数据库所有数据至当前目录下以年月日命名的sql文件\"\n filename=datetime.datetime.now().strftime(\"%Y-%m-%d\")+\".sql\"\n cmd=\"\"\"mysqldump -u root -pzhoubt --opt --quick --database search >./%s\"\"\"%filename\n print cmd\n p=subprocess.Popen(cmd,shell=True,cwd=os.getcwd())\n sts = o... | [
2
] | [] | [] | [
"import",
"mysql",
"python",
"subprocess"
] | stackoverflow_0003920473_import_mysql_python_subprocess.txt |
Q:
Now to convert this strings to date time object in Python or django?
Now to convert this strings to date time object in Python or django?
2010-08-17T19:00:00Z
2010-08-17T18:30:00Z
2010-08-17T17:05:00Z
2010-08-17T14:30:00Z
2010-08-10T22:20:00Z
2010-08-10T21:20:00Z
2010-08-10T20:25:00Z
2010-08-10T19:30:00Z
2010-08-10T19:00:00Z
2010-08-10T18:30:00Z
2010-08-10T17:30:00Z
2010-08-10T17:05:00Z
2010-08-10T17:05:00Z
2010-08-10T15:30:00Z
2010-08-10T14:30:00Z
whrn i do this datestr=datetime.strptime( datetime, "%Y-%m-%dT%H:%M:%S" )
it tell me that unconverted data remains: Z
A:
You can parse the strings as-is without the need to slice if you don't mind using the handy dateutil module. For e.g.
>>> from dateutil.parser import parse
>>> s = "2010-08-17T19:00:00Z"
>>> parse(s)
datetime.datetime(2010, 8, 17, 19, 0, tzinfo=tzutc())
>>>
A:
Use slicing to remove "Z" before supplying the string for conversion
datestr=datetime.strptime( datetime[:-1], "%Y-%m-%dT%H:%M:%S" )
>>> test = "2010-08-17T19:00:00Z"
>>> test[:-1]
'2010-08-17T19:00:00'
A:
Those seem to be ISO 8601 dates. If your timezone is always the same, just remove the last letter before parsing it with strptime (e.g by slicing).
The Z indicates the timezone, so be sure that you are taking that into account when converting it to a datetime of a different timezone. If the timezone can change in your application, you'll have to parse that information also and change the datetime object accordingly.
You could also use the pyiso8601 module to parse these ISO dates, it will most likely also work with slighty different ISO date formats. If your data may contain different timezones I would suggest to use this module.
A:
change your format string to ""%Y-%m-%dT%H:%M:%SZ" so that it includes the trailing Z (which makes it no longer unconverted). Note, however, that this Z perhaps is there to indicate that the time is in UTC which might be something you need to account for otherwise
| Now to convert this strings to date time object in Python or django? | Now to convert this strings to date time object in Python or django?
2010-08-17T19:00:00Z
2010-08-17T18:30:00Z
2010-08-17T17:05:00Z
2010-08-17T14:30:00Z
2010-08-10T22:20:00Z
2010-08-10T21:20:00Z
2010-08-10T20:25:00Z
2010-08-10T19:30:00Z
2010-08-10T19:00:00Z
2010-08-10T18:30:00Z
2010-08-10T17:30:00Z
2010-08-10T17:05:00Z
2010-08-10T17:05:00Z
2010-08-10T15:30:00Z
2010-08-10T14:30:00Z
whrn i do this datestr=datetime.strptime( datetime, "%Y-%m-%dT%H:%M:%S" )
it tell me that unconverted data remains: Z
| [
"You can parse the strings as-is without the need to slice if you don't mind using the handy dateutil module. For e.g.\n>>> from dateutil.parser import parse\n>>> s = \"2010-08-17T19:00:00Z\"\n>>> parse(s)\ndatetime.datetime(2010, 8, 17, 19, 0, tzinfo=tzutc())\n>>> \n\n",
"Use slicing to remove \"Z\" before suppl... | [
11,
7,
3,
2
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003918735_django_python.txt |
Q:
Basic Python Function and Constant Help
I'm not sure where to even start this assignment:
In shopping for a new house, you must consider several factors. In this problem the initial cost of the house, the estimated annual fuel costs, and the annual tax rate are available. Write a program that determines and displays the total cost of a house after a five-year period and execute the program for each of the following sets of data:
Initial House Cost Annual Fuel Cost Tax Rate
167,000 3,300 0.025
162,000 3,500 0.025
175,000 2,850 0.025
To calculate the house cost, add the initial cost to the fuel cost for five years, then add the taxes for five years. Taxes for one year are computed by multiplying the tax rate by the initial cost. Show testing for your program as discussed in lab and lecture.
Any help with writing the initial function and the constants would be greatly appreciated!
A:
To calculate the house cost, add the initial cost
initial_cost
to the fuel cost for five years,
YEARS = 5
initial_cost + YEARS * annual_fuel_cost
then add the taxes for five years. Taxes for one year are computed by multiplying the tax rate by the initial cost.
initial_cost + YEARS * annual_fuel_cost + YEARS * initial_cost * tax_rate
A:
You should start by reading the basics at python.org.
Then you just do T=A+B*5+A*C*5 for each of your data sets.
Finally consult your lab and lecture notes to see how to show testing.
| Basic Python Function and Constant Help | I'm not sure where to even start this assignment:
In shopping for a new house, you must consider several factors. In this problem the initial cost of the house, the estimated annual fuel costs, and the annual tax rate are available. Write a program that determines and displays the total cost of a house after a five-year period and execute the program for each of the following sets of data:
Initial House Cost Annual Fuel Cost Tax Rate
167,000 3,300 0.025
162,000 3,500 0.025
175,000 2,850 0.025
To calculate the house cost, add the initial cost to the fuel cost for five years, then add the taxes for five years. Taxes for one year are computed by multiplying the tax rate by the initial cost. Show testing for your program as discussed in lab and lecture.
Any help with writing the initial function and the constants would be greatly appreciated!
| [
"To calculate the house cost, add the initial cost \ninitial_cost\n\nto the fuel cost for five years, \nYEARS = 5\ninitial_cost + YEARS * annual_fuel_cost\n\nthen add the taxes for five years. Taxes for one year are computed by multiplying the tax rate by the initial cost.\ninitial_cost + YEARS * annual_fuel_cost +... | [
2,
0
] | [] | [] | [
"constants",
"function",
"python"
] | stackoverflow_0003920856_constants_function_python.txt |
Q:
using python module in java with jython
I have a couple of python modules in an existing Python project that I wish to make use of in my Java app.
I found an article and followed the steps mentioned there. In particular, I need to import the java interface:
package jyinterface.interfaces;
public interface EmployeeType {
.
.
}
into the module:
from jyinterface.interfaces import EmployeeType
class Employee(EmployeeType)
:
I have a question - With this method, does this means that I cannot use this module in my existing python project after making the changes, even with a Jython or Python interpreter?
A:
You can use it with Jython but not with CPython, the standard implementation.
How ever, there is an effort to provide full access to java class libraries when you use CPython.
http://jpype.sourceforge.net/
| using python module in java with jython | I have a couple of python modules in an existing Python project that I wish to make use of in my Java app.
I found an article and followed the steps mentioned there. In particular, I need to import the java interface:
package jyinterface.interfaces;
public interface EmployeeType {
.
.
}
into the module:
from jyinterface.interfaces import EmployeeType
class Employee(EmployeeType)
:
I have a question - With this method, does this means that I cannot use this module in my existing python project after making the changes, even with a Jython or Python interpreter?
| [
"You can use it with Jython but not with CPython, the standard implementation.\nHow ever, there is an effort to provide full access to java class libraries when you use CPython. \n\nhttp://jpype.sourceforge.net/\n\n"
] | [
1
] | [] | [] | [
"java",
"jython",
"python"
] | stackoverflow_0003921000_java_jython_python.txt |
Q:
how to format variables before db to avoid errors
I am recieving errors like this one:
_mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 't Stop.mp3' LIMIT 1' at line 1")
Because I am trying to compare a URL that exists in my DB to one in a variable before I choose to insert it or not with the below code:
`#see if any links in the DB match the crawled link
check_exists_sql = "SELECT * FROM LINKS WHERE link = '%s' LIMIT 1" % item['link'].encode("utf-8")
cursor.execute(check_exists_sql)`
Obviously the ' character and perhaps other characters are causing problems.
How do I format these URLs to avoid this?
A:
Let the MySQLdb module do the interpolation:
cursor.execute("""SELECT * FROM LINKS WHERE link = %s LIMIT 1""",
(item['link'].encode("utf-8"),)
)
The execute() function can be passed items to be substituted into the query (see the documentation for execute()). It will automatically escape things as necessary for the DB query.
If you prefer to use a dict instead of a tuple to specify the things to substitute in:
cursor.execute("""SELECT * FROM LINKS WHERE link = %(link)s LIMIT 1""",
{'link': item['link'].encode("utf-8")}
)
| how to format variables before db to avoid errors | I am recieving errors like this one:
_mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 't Stop.mp3' LIMIT 1' at line 1")
Because I am trying to compare a URL that exists in my DB to one in a variable before I choose to insert it or not with the below code:
`#see if any links in the DB match the crawled link
check_exists_sql = "SELECT * FROM LINKS WHERE link = '%s' LIMIT 1" % item['link'].encode("utf-8")
cursor.execute(check_exists_sql)`
Obviously the ' character and perhaps other characters are causing problems.
How do I format these URLs to avoid this?
| [
"Let the MySQLdb module do the interpolation:\ncursor.execute(\"\"\"SELECT * FROM LINKS WHERE link = %s LIMIT 1\"\"\",\n (item['link'].encode(\"utf-8\"),)\n)\n\nThe execute() function can be passed items to be substituted into the query (see the documentation for execute()). It will automatically escape things a... | [
3
] | [] | [] | [
"mysql",
"python"
] | stackoverflow_0003921075_mysql_python.txt |
Q:
Serializing decimal points in Django, getting error: 'ValuesListQuerySet' object has no attribute '_meta'
Is there a way I can serialize a FloatField model instance in django? I have the following in a management command:
def chart_data(request):
i = 1
chart = open_flash_chart()
chart.title = t
for manager in FusionManagers.objects.all():
net_data = manager.netio_set.values_list('Net', flat=True)
clean = serializers.serialize('json', [ net_data, ])
new = line()
new.values = clean
locals()["graph_" + str(i)] = new
chart.add_element(locals()["graph_" + str(i)])
i = i + 1
return HttpResponse(chart.render())
But I get the error: 'ValuesListQuerySet' object has no attribute '_meta'
The 'Net' fields are floatfields, and the values are filtered to 2 decimal places, so I get 400.23, etc... Can these be serialized?
A:
The Django serialization module only works on lists/querysets of full Django objects; ValuesListQuerySet contains tuples, not Django objects.
I am quoting from a comment attached to Django ticket #8090. You'll need to get a QuerySet if you want to use Django's built in serialization. If not, you'll have to use a custom serializing module.
| Serializing decimal points in Django, getting error: 'ValuesListQuerySet' object has no attribute '_meta' | Is there a way I can serialize a FloatField model instance in django? I have the following in a management command:
def chart_data(request):
i = 1
chart = open_flash_chart()
chart.title = t
for manager in FusionManagers.objects.all():
net_data = manager.netio_set.values_list('Net', flat=True)
clean = serializers.serialize('json', [ net_data, ])
new = line()
new.values = clean
locals()["graph_" + str(i)] = new
chart.add_element(locals()["graph_" + str(i)])
i = i + 1
return HttpResponse(chart.render())
But I get the error: 'ValuesListQuerySet' object has no attribute '_meta'
The 'Net' fields are floatfields, and the values are filtered to 2 decimal places, so I get 400.23, etc... Can these be serialized?
| [
"\nThe Django serialization module only works on lists/querysets of full Django objects; ValuesListQuerySet contains tuples, not Django objects.\n\nI am quoting from a comment attached to Django ticket #8090. You'll need to get a QuerySet if you want to use Django's built in serialization. If not, you'll have to us... | [
1
] | [] | [] | [
"django",
"django_models",
"json",
"python"
] | stackoverflow_0003921124_django_django_models_json_python.txt |
Q:
python - need help inserting text files with open() into mysql
Can someone help me out with the mysql connection statement to instert a textfile into a mysql table (field type is long blob)?
For example:
cursor.execute("insert into mytable (file_contents) values ('"+open(filename,"r").read()+"')")
Obviously that's not very practical, can someone post a better way to do this?
A:
It is dangerous to append content of a file directly into an SQL query, because of special characters (quotes!) or malicious SQL commands.
Try this:
with open(filename,"r") as infile:
cursor.execute("insert into mytable (file_contents) values (%s)", (infile.read(), ))
| python - need help inserting text files with open() into mysql | Can someone help me out with the mysql connection statement to instert a textfile into a mysql table (field type is long blob)?
For example:
cursor.execute("insert into mytable (file_contents) values ('"+open(filename,"r").read()+"')")
Obviously that's not very practical, can someone post a better way to do this?
| [
"It is dangerous to append content of a file directly into an SQL query, because of special characters (quotes!) or malicious SQL commands.\nTry this:\nwith open(filename,\"r\") as infile:\n cursor.execute(\"insert into mytable (file_contents) values (%s)\", (infile.read(), ))\n\n"
] | [
1
] | [] | [] | [
"python"
] | stackoverflow_0003920889_python.txt |
Q:
Multiple-instance Django forum software
Does anyone know of a django forum plugin that allows each member to have his own forum? If there isn't anything, than what would be the best way to accomplish this with a "regular" forum plugin for Django?
A:
I once created a feature matrix of all Django forum apps I could find. It might be a bit outdated now, though (contributions welcome).
At least django-threadedcomments uses generic foreign keys, so you can attach a message thread to any database object, including users.
A:
Look at DjangoBB.
A:
Yep, the forum app of SCT can be used for this - simply set it up and create multiple "community Groups" (these are similar to vhosts) and map them to subdomains - each community group would have separate forum categories, can have separate templates, separate user permissions, etc. (but they will obviously share the same django users and their profiles) - as an example.. the following websites are all hosted on the same instance:
SCT website
My personal website/blog (the blog is also based on SCTs forum)
ShelfShare Community
A:
Check out diamanda. I'm not sure it does what you need as far as the each user having its forums, but that's probably not too hard to hack on top. Probably as simple as adding a few ForeignKeys into auth.User to the diamanda models. In general django pluggables and djangoapps are good places to look for django stuff that is already written. Also, check out pinax.
A:
I believe the Sphene Community Tools can do this.
| Multiple-instance Django forum software | Does anyone know of a django forum plugin that allows each member to have his own forum? If there isn't anything, than what would be the best way to accomplish this with a "regular" forum plugin for Django?
| [
"I once created a feature matrix of all Django forum apps I could find. It might be a bit outdated now, though (contributions welcome).\nAt least django-threadedcomments uses generic foreign keys, so you can attach a message thread to any database object, including users. \n",
"Look at DjangoBB.\n",
"Yep, the f... | [
4,
2,
1,
0,
0
] | [] | [] | [
"django",
"forum",
"python"
] | stackoverflow_0000546753_django_forum_python.txt |
Q:
Linear Regression with Python numpy
I'm trying to make a simple linear regression function but continue to encounter a
numpy.linalg.linalg.LinAlgError: Singular matrix error
Existing function (with debug prints):
def makeLLS(inputData, targetData):
print "In makeLLS:"
print " Shape inputData:",inputData.shape
print " Shape targetData:",targetData.shape
term1 = np.dot(inputData.T, inputData)
term2 = np.dot(inputData.T, targetData)
print " Shape term1:",term1.shape
print " Shape term2:",term2.shape
#print term1
#print term2
result = np.linalg.solve(term1, term2)
return result
The output to the console with my test data is:
In makeLLS:
Shape trainInput1: (773, 10)
Shape trainTargetData: (773, 1)
Shape term1: (10, 10)
Shape term2: (10, 1)
Then it errors on the linalg.solve line. This is a textbook linear regression function and I can't seem to figure out why it's failing.
What is the singular matrix error?
A:
As explained in the other answer linalg.solve expects a full rank matrix. This is because it tries to solve a matrix equation rather than do linear regression which should work for all ranks.
There are a few methods for linear regression. The simplest one I would suggest is the standard least squares method. Just use numpy.linalg.lstsq instead. The documentation including an example is here.
A:
A singular matrix is one for which the determinant is zero. This indicates that your matrix has rows that aren't linearly independent. For instance, if one of the rows is not linearly independent of the others, then it can be constructed by a linear combination of the other rows. I'll use numpy's linalg.solve example to demonstrate. Here is the doc's example:
>>> import numpy as np
>>> a = np.array([[3,1], [1,2]])
>>> b = np.array([9,8])
>>> x = np.linalg.solve(a, b)
>>> x
array([ 2., 3.])
Now, I'll change a to make it singular.
>>> a = np.array([[2,4], [1,2]])
>>> x = np.linalg.solve(a, b)
...
LinAlgError: Singular matrix
This is a very obvious example because the first row is just double the second row, but hopefully you get the point.
| Linear Regression with Python numpy | I'm trying to make a simple linear regression function but continue to encounter a
numpy.linalg.linalg.LinAlgError: Singular matrix error
Existing function (with debug prints):
def makeLLS(inputData, targetData):
print "In makeLLS:"
print " Shape inputData:",inputData.shape
print " Shape targetData:",targetData.shape
term1 = np.dot(inputData.T, inputData)
term2 = np.dot(inputData.T, targetData)
print " Shape term1:",term1.shape
print " Shape term2:",term2.shape
#print term1
#print term2
result = np.linalg.solve(term1, term2)
return result
The output to the console with my test data is:
In makeLLS:
Shape trainInput1: (773, 10)
Shape trainTargetData: (773, 1)
Shape term1: (10, 10)
Shape term2: (10, 1)
Then it errors on the linalg.solve line. This is a textbook linear regression function and I can't seem to figure out why it's failing.
What is the singular matrix error?
| [
"As explained in the other answer linalg.solve expects a full rank matrix. This is because it tries to solve a matrix equation rather than do linear regression which should work for all ranks.\nThere are a few methods for linear regression. The simplest one I would suggest is the standard least squares method. Just... | [
19,
8
] | [] | [] | [
"linear_regression",
"numpy",
"python"
] | stackoverflow_0003920571_linear_regression_numpy_python.txt |
Q:
Reverting the 'global ' statement
I am learning Python and just had this question. It possibly has no practical worth, I'm asking this out maybe because of a pedantic curiosity.
I have a function:
def f():
x = 12 #this is a local variable
global x #this is a global I declared before
x = 14 #changes global x
<How can I return the local x?>
I'm aware that this is ugly and I do get a Syntax Warning. Just wanted to know how to "get back" my local variable.
Thanks to everyone.
A:
Your code isn't doing what you think it is and there's no way to change it do what you describe. You can't "revert" what globals does since it has no effect at run time.
The global keyword is interpreted at compile time so in the first line of f() where you set x = 12 this is modifying the global x since the compiler has decided the x refers to the x in the global namespace throughout the whole function, not just after the global statement.
You can test this easily:
>>> def g():
... x = 12
... y = 13
... global x
... print "locals:",locals()
...
<stdin>:4: SyntaxWarning: name 'x' is assigned to before global declaration
>>> g()
locals: {'y': 13}
The locals() function gives us a view of the local namespace and we can see that there's no x in there.
The documentation says the following:
Names listed in a global statement must not be used in the same code block textually preceding that global statement.
Names listed in a global statement must not be defined as formal parameters or in a for loop control target, class definition, function definition, or import statement.
The current implementation does not enforce the latter two restrictions, but programs should not abuse this freedom, as future implementations may enforce them or silently change the meaning of the program.
Just give the local variable a different name.
A:
I very much doubt that it can be done.
>>> x = 1
>>> def f():
... x = 12
... global x
... print x
...
<stdin>:3: SyntaxWarning: name 'x' is assigned to before global declaration
>>> f()
12
>>> x
12
As you can see, even without an explicit assignment to x after the global keyword, python syncs up the the values of the two. To see why, you have to disassemble it.
>>> dis.dis(f) # different f with print statement removed for clarity
2 0 LOAD_CONST 1 (12)
3 STORE_GLOBAL 0 (x)
3 6 LOAD_CONST 0 (None)
9 RETURN_VALUE
>>>
The global keyword isn't represented here at all but the assignment statement gets compiled as STORE_GLOBAL. After you do it, it's done. Use globals with care and the global keyword with greater care.
A:
It is not possible to undo the effect of a global statement.
A global statement applies for the entire duration of the function in which it appears, regardless of where in the function it is, and regardless of whether it's executed. So, for example, in the assignment in the following function:
def f():
x = 3
if False:
global x
x is still treated as global.
So it wouldn't make sense to have another statement to undo its effect afterwards, since a global "statement" is not so much a statement, that is executed at some point during the function, as a declaration about the behavior of the function as a whole.
| Reverting the 'global ' statement | I am learning Python and just had this question. It possibly has no practical worth, I'm asking this out maybe because of a pedantic curiosity.
I have a function:
def f():
x = 12 #this is a local variable
global x #this is a global I declared before
x = 14 #changes global x
<How can I return the local x?>
I'm aware that this is ugly and I do get a Syntax Warning. Just wanted to know how to "get back" my local variable.
Thanks to everyone.
| [
"Your code isn't doing what you think it is and there's no way to change it do what you describe. You can't \"revert\" what globals does since it has no effect at run time.\nThe global keyword is interpreted at compile time so in the first line of f() where you set x = 12 this is modifying the global x since the c... | [
7,
4,
1
] | [] | [] | [
"global",
"local",
"python",
"scope"
] | stackoverflow_0003921822_global_local_python_scope.txt |
Q:
wxPython and py2app, CreateActCtx error 0x00000008 (Not enough disk space available)
I've been developing an application that uses wxPython as the GUI librar, and py2exe so that I can easily distribute it, however I have just now tested py2exe and the following error appears when the executable is launched.
12:13:08: Debug: src/helpers.cpp(140): 'CreateActCtx' failed with error 0x00000008 (Not enough disk space available.).
Traceback (most recent call last):
File "eYoutubeMacros3.py", line 1, in <module>
File "zipextimporter.pyo", line 82, in load_module
File "application\application.pyo", line 5, in <module>
File "zipextimporter.pyo", line 82, in load_module
File "application\backend\backend.pyo", line 4, in <module>
File "zipextimporter.pyo", line 82, in load_module
File "application\backend\extractor.pyo", line 5, in <module>
File "zipextimporter.pyo", line 82, in load_module
File "twisted\web\client.pyo", line 17, in <module>
File "zipextimporter.pyo", line 82, in load_module
File "twisted\web\error.pyo", line 188, in <module>
ImportError: cannot import name resource
The function causing the error in src/helpers.cpp is
static ULONG_PTR wxPySetActivationContext()
{
OSVERSIONINFO info;
wxZeroMemory(info);
info.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
GetVersionEx(&info);
if (info.dwMajorVersion < 5)
return 0;
ULONG_PTR cookie = 0;
HANDLE h;
ACTCTX actctx;
TCHAR modulename[MAX_PATH];
GetModuleFileName(wxGetInstance(), modulename, MAX_PATH);
wxZeroMemory(actctx);
actctx.cbSize = sizeof(actctx);
actctx.lpSource = modulename;
actctx.lpResourceName = MAKEINTRESOURCE(2);
actctx.hModule = wxGetInstance();
actctx.dwFlags = ACTCTX_FLAG_HMODULE_VALID | ACTCTX_FLAG_RESOURCE_NAME_VALID;
h = CreateActCtx(&actctx);
if (h == INVALID_HANDLE_VALUE) {
wxLogLastError(wxT("CreateActCtx"));
return 0;
}
if (! ActivateActCtx(h, &cookie))
wxLogLastError(wxT("ActivateActCtx"));
return cookie;
}
And lastly my code for py2exe
setup(
console = [self.target], # Contains some build info, is this is relevant I'll add it
zipfile = 'library.dat',
options = {
'py2exe' : {
'bundle_files' : 1,
'dll_excludes' : ['w9xpopen.exe'],
'optimize' : 2,
'dist_dir' : '../dist/executables/',
'compressed' : True,
#'excludes' : ['doctest', 'pdb', 'unittest', 'difflib', 'inspect'],
}
}
)
Edit: Yes the second error seems to be from twisted but I doubt that causes the first error.
Edit2: Hmm perhaps the first one is just a warning.
A:
That means common controls stuff does not load. The second error could be a result of the first error which is non fatal and program continues to run.
try first :
(Don't bundle option) and check if the issue still appears. This should typically work.
bundle_files = 3
try next:
Since, you are using bundle option 1 , Can you check which MSVC runtime DLL is located in the dist directory along side the executable. I would suggest that you also find out all MSVCRXX.dll on your machine and see if there are version issues
A:
Turned out #1 was just a warning, and #2 was fixed with an explicit module include
| wxPython and py2app, CreateActCtx error 0x00000008 (Not enough disk space available) | I've been developing an application that uses wxPython as the GUI librar, and py2exe so that I can easily distribute it, however I have just now tested py2exe and the following error appears when the executable is launched.
12:13:08: Debug: src/helpers.cpp(140): 'CreateActCtx' failed with error 0x00000008 (Not enough disk space available.).
Traceback (most recent call last):
File "eYoutubeMacros3.py", line 1, in <module>
File "zipextimporter.pyo", line 82, in load_module
File "application\application.pyo", line 5, in <module>
File "zipextimporter.pyo", line 82, in load_module
File "application\backend\backend.pyo", line 4, in <module>
File "zipextimporter.pyo", line 82, in load_module
File "application\backend\extractor.pyo", line 5, in <module>
File "zipextimporter.pyo", line 82, in load_module
File "twisted\web\client.pyo", line 17, in <module>
File "zipextimporter.pyo", line 82, in load_module
File "twisted\web\error.pyo", line 188, in <module>
ImportError: cannot import name resource
The function causing the error in src/helpers.cpp is
static ULONG_PTR wxPySetActivationContext()
{
OSVERSIONINFO info;
wxZeroMemory(info);
info.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
GetVersionEx(&info);
if (info.dwMajorVersion < 5)
return 0;
ULONG_PTR cookie = 0;
HANDLE h;
ACTCTX actctx;
TCHAR modulename[MAX_PATH];
GetModuleFileName(wxGetInstance(), modulename, MAX_PATH);
wxZeroMemory(actctx);
actctx.cbSize = sizeof(actctx);
actctx.lpSource = modulename;
actctx.lpResourceName = MAKEINTRESOURCE(2);
actctx.hModule = wxGetInstance();
actctx.dwFlags = ACTCTX_FLAG_HMODULE_VALID | ACTCTX_FLAG_RESOURCE_NAME_VALID;
h = CreateActCtx(&actctx);
if (h == INVALID_HANDLE_VALUE) {
wxLogLastError(wxT("CreateActCtx"));
return 0;
}
if (! ActivateActCtx(h, &cookie))
wxLogLastError(wxT("ActivateActCtx"));
return cookie;
}
And lastly my code for py2exe
setup(
console = [self.target], # Contains some build info, is this is relevant I'll add it
zipfile = 'library.dat',
options = {
'py2exe' : {
'bundle_files' : 1,
'dll_excludes' : ['w9xpopen.exe'],
'optimize' : 2,
'dist_dir' : '../dist/executables/',
'compressed' : True,
#'excludes' : ['doctest', 'pdb', 'unittest', 'difflib', 'inspect'],
}
}
)
Edit: Yes the second error seems to be from twisted but I doubt that causes the first error.
Edit2: Hmm perhaps the first one is just a warning.
| [
"That means common controls stuff does not load. The second error could be a result of the first error which is non fatal and program continues to run.\ntry first : \n(Don't bundle option) and check if the issue still appears. This should typically work.\nbundle_files = 3 \n\ntry next: \nSince, you are using bundle... | [
2,
0
] | [] | [] | [
"py2exe",
"python",
"twisted",
"wxpython"
] | stackoverflow_0003590440_py2exe_python_twisted_wxpython.txt |
Q:
python beautifulsoup related problem
i have some problem to extract some data from html source.
following is sniffit of my html source code, and i want to extract string value in every
following
<td class="gamedate">10/12 00:59</b></td>
<td class="gametype">오버언더</b></td>
<td class="legue"><nobr style="width:100%;overflow:hidden;letter-spacing:-1;font-size:11px;"><nobr style='display:block; overflow:hidden;'><img src='../data/banner/25' border='0' width='20' height='13' alt='' align='absmiddle'></a> 그리스 D2</nobr>
<td class="bet" id="team1_27771" class="homeTeam1">Pas Giannina (↑오버)</td>
<td class="bet" id="bet1_27771" class="homeTeam2" align="right">1.65</td>
<td class="pointer muSelect" id="chk_27771_3" num='27771' bet='2.5' sp='오버언더' bgcolor="f0f0f0" class="handy handy1" ><span id="bet3_27771">2.5</span></td>
<td class="bet" id="bet2_27771" class="awayTeam2" align="left">1.95</td>
<td class="bet" id="team2_27771" class="awayTeam1">Pierikos (↓언더)</td>
so what i want extracted final value is
10/12 00:59
오버언더
그리스 D2
Pas Giannina (↑오버)
1.65
2.5
1.95
Pierikos (↓언더)
following is my html full source
help me please! thanks in advance!
because html source is some big so i was upload to pastebin.com
http://pastebin.com/Gdun0jhf
A:
Why not just do a replace on the string
html.replace("AAAAAA", "Put what you want for AAAAAA here")
and do this for all of the things you want to replace?
Ignore, I miss read the question completely my brain must not be on today
A:
You may use HTMLParser
A:
Something like this works on a basic table:
soup = BeautifulSoup.BeautifulSoup(YOUR_HTML)
table = soup.find('TABLE_ID')
for td in table.findAll('td'):
print td.string
but it looks like the html you are dealing with is a bit messier. SO maybe it would be best to go after each of the TDs by class name? e.g.
soup = BeautifulSoup.BeautifulSoup(YOUR_HTML)
#game date
game_dates = soup.findAll('td', {class: 'gamedate' })
for game_date in game_dates:
print game_date
#bets
bets = soup.findAll('td', {class: 'bet' })
for bet in bets:
print bet
| python beautifulsoup related problem | i have some problem to extract some data from html source.
following is sniffit of my html source code, and i want to extract string value in every
following
<td class="gamedate">10/12 00:59</b></td>
<td class="gametype">오버언더</b></td>
<td class="legue"><nobr style="width:100%;overflow:hidden;letter-spacing:-1;font-size:11px;"><nobr style='display:block; overflow:hidden;'><img src='../data/banner/25' border='0' width='20' height='13' alt='' align='absmiddle'></a> 그리스 D2</nobr>
<td class="bet" id="team1_27771" class="homeTeam1">Pas Giannina (↑오버)</td>
<td class="bet" id="bet1_27771" class="homeTeam2" align="right">1.65</td>
<td class="pointer muSelect" id="chk_27771_3" num='27771' bet='2.5' sp='오버언더' bgcolor="f0f0f0" class="handy handy1" ><span id="bet3_27771">2.5</span></td>
<td class="bet" id="bet2_27771" class="awayTeam2" align="left">1.95</td>
<td class="bet" id="team2_27771" class="awayTeam1">Pierikos (↓언더)</td>
so what i want extracted final value is
10/12 00:59
오버언더
그리스 D2
Pas Giannina (↑오버)
1.65
2.5
1.95
Pierikos (↓언더)
following is my html full source
help me please! thanks in advance!
because html source is some big so i was upload to pastebin.com
http://pastebin.com/Gdun0jhf
| [
"Why not just do a replace on the string\nhtml.replace(\"AAAAAA\", \"Put what you want for AAAAAA here\")\n\nand do this for all of the things you want to replace?\nIgnore, I miss read the question completely my brain must not be on today\n",
"You may use HTMLParser \n",
"Something like this works on a basic ta... | [
1,
0,
0
] | [] | [] | [
"beautifulsoup",
"python"
] | stackoverflow_0003911201_beautifulsoup_python.txt |
Q:
Python/Django: Adding custom model methods?
Using for example
class model(models.Model)
....
def my_custom_method(self, *args, **kwargs):
#do something
When I try to call this method during pre_save, save, post_save etc, Python raises a TypeError; unbound method.
How can one add custom model methods which can be executed in the same way like model.objects.get(), etc?
Edit: tried using super(model, self).my_custom_method(*args, **kwargs) but in that case Python says that model does not have attribute my_custom_method
A:
How are you calling this method? You have defined an instance method, which can only be called on an instance of the class, not the class itself. In other words, once you have an instance of model called mymodelinstance, you can do mymodelinstance.my_custom_method().
If you want to call it on the class, you need to define a classmethod. You can do this with the @classmethod decorator on your method. Note that by convention the first parameter to a classmethod is cls, not self. See the Python documentation for details on classmethod.
However, if what you actually want to do is to add a method that does a queryset-level operation, like objects.filter() or objects.get(), then your best bet is to define a custom Manager and add your method there. Then you will be able to do model.objects.my_custom_method(). Again, see the Django documentation on Managers.
A:
If you are implementing a Signal for your model it does not necessarily need to be defined in the model class only. You can define it outside the class and pass the class name as the parameter to the connect function.
However, in your case you need the model object to access the method.
| Python/Django: Adding custom model methods? | Using for example
class model(models.Model)
....
def my_custom_method(self, *args, **kwargs):
#do something
When I try to call this method during pre_save, save, post_save etc, Python raises a TypeError; unbound method.
How can one add custom model methods which can be executed in the same way like model.objects.get(), etc?
Edit: tried using super(model, self).my_custom_method(*args, **kwargs) but in that case Python says that model does not have attribute my_custom_method
| [
"How are you calling this method? You have defined an instance method, which can only be called on an instance of the class, not the class itself. In other words, once you have an instance of model called mymodelinstance, you can do mymodelinstance.my_custom_method().\nIf you want to call it on the class, you need ... | [
42,
0
] | [] | [] | [
"django",
"methods",
"model",
"python"
] | stackoverflow_0003921619_django_methods_model_python.txt |
Q:
Matching Popen.communicate() output with regular expressions doesn't work
I have code that roughly looks like this (the entire code is a bit too long to copy here):
import re
from subprocess import Popen, PIPE
goodOutput = re.compile(r'\S+: 0x[0-9a-fA-F]{8} \d \d\s+->\s+0x[0-9a-fA-F]{8}')
p = Popen(['/tmp/myexe', param], stdout=PIPE, stderr=PIPE, cwd='/tmp')
stdout, stderr = p.communicate()
ret = goodOutput.match(stdout)
if ret == None:
print "No match in: " + stdout
match() doesn't match this, but if I copy the stdout from the print statement and use that string in the above script as the value for stdout, it matches. So the regexp pattern should be all right. Also, if I read the string from stdin (stdout = sys.input.read()) it again works.
I've tried to rstrip() stdout as well, but that didn't help either (besides, shouldn't match() make this unnecessary?).
When I print stdout with repr() the string looks like
'xxx[a]: 0xff2eff00 4 7\t->\t0xff2eff00\n'
and if I try to match() to this it doesn't match. Is this an issue with the tab and newline characters and if so, what should I do?
A:
There still seem to be either typos in your regex or errors that lead to it not matching (extraneous }, too much whitespace).
Try
goodOutput = re.compile(r"\s*[^:]:s*0x[0-9a-fA-F]{8}\s+\d\s+\d\s+->\s+0x[0-9a-fA-F]{8}"`
and see if that helps.
Also, try re.search() vs. re.match() and see if that makes any difference.
A:
Are you sure there is no leading space or such invisible characters in stdout ? If you copy paste what follow them but not these characters it would explain why your test 'by hand' works.
If so maybe you want to perform a re.search (match anywhere) instead of re.match (match at beginning) or remove these leading characters.
A:
Your regex has some random characters, with correct version of it everything matches:
>>> s = 'xxx[a]: 0xff2eff00 4 7\t->\t0xff2eff00\n'
>>> re.match(r'\S+: 0x[0-9a-f]{8} \d \d\s+->\s+0x[0-9a-f]{8}', s, re.I).group()
'xxx[a]: 0xff2eff00 4 7\t->\t0xff2eff00'
| Matching Popen.communicate() output with regular expressions doesn't work | I have code that roughly looks like this (the entire code is a bit too long to copy here):
import re
from subprocess import Popen, PIPE
goodOutput = re.compile(r'\S+: 0x[0-9a-fA-F]{8} \d \d\s+->\s+0x[0-9a-fA-F]{8}')
p = Popen(['/tmp/myexe', param], stdout=PIPE, stderr=PIPE, cwd='/tmp')
stdout, stderr = p.communicate()
ret = goodOutput.match(stdout)
if ret == None:
print "No match in: " + stdout
match() doesn't match this, but if I copy the stdout from the print statement and use that string in the above script as the value for stdout, it matches. So the regexp pattern should be all right. Also, if I read the string from stdin (stdout = sys.input.read()) it again works.
I've tried to rstrip() stdout as well, but that didn't help either (besides, shouldn't match() make this unnecessary?).
When I print stdout with repr() the string looks like
'xxx[a]: 0xff2eff00 4 7\t->\t0xff2eff00\n'
and if I try to match() to this it doesn't match. Is this an issue with the tab and newline characters and if so, what should I do?
| [
"There still seem to be either typos in your regex or errors that lead to it not matching (extraneous }, too much whitespace).\nTry \ngoodOutput = re.compile(r\"\\s*[^:]:s*0x[0-9a-fA-F]{8}\\s+\\d\\s+\\d\\s+->\\s+0x[0-9a-fA-F]{8}\"`\n\nand see if that helps.\nAlso, try re.search() vs. re.match() and see if that make... | [
1,
0,
0
] | [] | [] | [
"python",
"regex",
"stdout",
"subprocess"
] | stackoverflow_0003921106_python_regex_stdout_subprocess.txt |
Q:
problem with running jpype with mod_python
As Python's urllib module is too slow, I'm using Java code wrapped with JPype in my web site. When I tested my web site with Django web server, there was no problem. However when I switched the web server to apache2 + mod_python, following error occurs. I googled many times but couldn't find the answer. Is there any solution to the error?
MOD_PYTHON ERROR
ProcessId: 4831
Interpreter: 'localhost'
ServerName: 'localhost'
DocumentRoot: '/home/www/mysite'
URI: '/javamodule.py/'
Location: '/'
Directory: None
Filename: '/home/www/mysite/javamodule.py'
PathInfo: '/'
Phase: 'PythonHandler'
Handler: 'django.core.handlers.modpython'
Traceback (most recent call last):
File "/usr/lib/python2.6/dist-packages/mod_python/importer.py", line 1537, in HandlerDispatch
default=default_handler, arg=req, silent=hlist.silent)
File "/usr/lib/python2.6/dist-packages/mod_python/importer.py", line 1229, in _process_target
result = _execute_target(config, req, object, arg)
File "/usr/lib/python2.6/dist-packages/mod_python/importer.py", line 1128, in _execute_target
result = object(arg)
File "/usr/lib/pymodules/python2.6/django/core/handlers/modpython.py", line 228, in handler
return ModPythonHandler()(req)
File "/usr/lib/pymodules/python2.6/django/core/handlers/modpython.py", line 183, in __call__
os.environ.update(req.subprocess_env)
File "/usr/lib/python2.6/os.py", line 486, in update
self[k] = dict[k]
File "/usr/lib/python2.6/os.py", line 471, in __setitem__
putenv(key, item)
A:
Another solution for your original problem: find other ways to get faster url retrieval.
httplib2 might already be a good solution: no problem to get it working as it's just a python library, but support for Keep-Alive connections can speed up things a lot, plus the caching support will help too (but only if you are often requesting the same url of course). And it's very easy to use.
If that doesn't get you far enought: PyCurl, the python binding for libcurl is probably the most obvious choice (there are also wrappers to make PyCurl easier to use, as PyCurl is apparently a bit low-level).
Anyway, just to say there are options that do not require java, that are easier to get working (and that will be probably end up faster as well)
| problem with running jpype with mod_python | As Python's urllib module is too slow, I'm using Java code wrapped with JPype in my web site. When I tested my web site with Django web server, there was no problem. However when I switched the web server to apache2 + mod_python, following error occurs. I googled many times but couldn't find the answer. Is there any solution to the error?
MOD_PYTHON ERROR
ProcessId: 4831
Interpreter: 'localhost'
ServerName: 'localhost'
DocumentRoot: '/home/www/mysite'
URI: '/javamodule.py/'
Location: '/'
Directory: None
Filename: '/home/www/mysite/javamodule.py'
PathInfo: '/'
Phase: 'PythonHandler'
Handler: 'django.core.handlers.modpython'
Traceback (most recent call last):
File "/usr/lib/python2.6/dist-packages/mod_python/importer.py", line 1537, in HandlerDispatch
default=default_handler, arg=req, silent=hlist.silent)
File "/usr/lib/python2.6/dist-packages/mod_python/importer.py", line 1229, in _process_target
result = _execute_target(config, req, object, arg)
File "/usr/lib/python2.6/dist-packages/mod_python/importer.py", line 1128, in _execute_target
result = object(arg)
File "/usr/lib/pymodules/python2.6/django/core/handlers/modpython.py", line 228, in handler
return ModPythonHandler()(req)
File "/usr/lib/pymodules/python2.6/django/core/handlers/modpython.py", line 183, in __call__
os.environ.update(req.subprocess_env)
File "/usr/lib/python2.6/os.py", line 486, in update
self[k] = dict[k]
File "/usr/lib/python2.6/os.py", line 471, in __setitem__
putenv(key, item)
| [
"Another solution for your original problem: find other ways to get faster url retrieval. \nhttplib2 might already be a good solution: no problem to get it working as it's just a python library, but support for Keep-Alive connections can speed up things a lot, plus the caching support will help too (but only if you... | [
0
] | [] | [] | [
"java",
"mod_python",
"python"
] | stackoverflow_0003921583_java_mod_python_python.txt |
Q:
Reading data from memcache sometimes fails
I've written a gevent-based program that allows its web clients to quickly exchange messages through it (so it works like a hub).
Since I only support polling mechanism at this moment, I've written it to store messages that need to be delivered to a specific client in its 'inbox' at the server side. While the client list is stored in MySQL, these inboxes are stored in memcache for faster access. When a client connects to the hub, it pulls all the messages that have accumulated in its inbox.
The question
The problem is that once upon a short while the recipients do not receive their messages when pulling the contents of their inbox - they receive an empty array.
What puzzles me even more is that if I restart the hub, the messages that were not received by the clients will suddenly materialize and get delivered to their destinations.
Can you point me if there's a glaring defect in my code? Do you have any explanation to this effect?
push is the method that gets executed to place a message into a client's inbox. pull is the method that retrieves the list of all the accumulated messages as a list and returns it to the main processing function.
def __push(self, domain, message, tid=None):
if tid:
try:
messages = self.mc.get("%s_inbox" % tid.encode('utf8'))
except:
logging.error("__push memcached failure", exc_info=1)
if messages:
messages = fromjson(messages)
messages.append(message)
self.mc.set("%s_inbox" % tid.encode('utf8'), tojson(messages))
print "Pushed to", "%s_inbox" % tid.encode('utf8')
def __pull(self, tid):
try:
messages = self.mc.get("%s_inbox" % tid.encode('utf8'))
if messages:
self.mc.set("%s_inbox" % tid.encode('utf8'), "[]")
return fromjson(messages)
else:
return []
except:
logging.error("__pull failure", exc_info=1)
return []
A:
I think I got it: it's a bug in the python-memcache module.
| Reading data from memcache sometimes fails | I've written a gevent-based program that allows its web clients to quickly exchange messages through it (so it works like a hub).
Since I only support polling mechanism at this moment, I've written it to store messages that need to be delivered to a specific client in its 'inbox' at the server side. While the client list is stored in MySQL, these inboxes are stored in memcache for faster access. When a client connects to the hub, it pulls all the messages that have accumulated in its inbox.
The question
The problem is that once upon a short while the recipients do not receive their messages when pulling the contents of their inbox - they receive an empty array.
What puzzles me even more is that if I restart the hub, the messages that were not received by the clients will suddenly materialize and get delivered to their destinations.
Can you point me if there's a glaring defect in my code? Do you have any explanation to this effect?
push is the method that gets executed to place a message into a client's inbox. pull is the method that retrieves the list of all the accumulated messages as a list and returns it to the main processing function.
def __push(self, domain, message, tid=None):
if tid:
try:
messages = self.mc.get("%s_inbox" % tid.encode('utf8'))
except:
logging.error("__push memcached failure", exc_info=1)
if messages:
messages = fromjson(messages)
messages.append(message)
self.mc.set("%s_inbox" % tid.encode('utf8'), tojson(messages))
print "Pushed to", "%s_inbox" % tid.encode('utf8')
def __pull(self, tid):
try:
messages = self.mc.get("%s_inbox" % tid.encode('utf8'))
if messages:
self.mc.set("%s_inbox" % tid.encode('utf8'), "[]")
return fromjson(messages)
else:
return []
except:
logging.error("__pull failure", exc_info=1)
return []
| [
"I think I got it: it's a bug in the python-memcache module.\n"
] | [
0
] | [] | [] | [
"gevent",
"memcached",
"python"
] | stackoverflow_0003904547_gevent_memcached_python.txt |
Q:
TKinter: how to create a histogram?
How can I create a histogram with TKinter and python ?
A:
this will help : http://effbot.org/tkinterbook/canvas.htm or http://infohost.nmt.edu/tcc/help/pubs/tkinter/canvas.html
A:
I don't know any out-of-the-box histogram widget. You may have to write your own. You may be interested by the Widget Construction Kit to help you in this task.
| TKinter: how to create a histogram? | How can I create a histogram with TKinter and python ?
| [
"this will help : http://effbot.org/tkinterbook/canvas.htm or http://infohost.nmt.edu/tcc/help/pubs/tkinter/canvas.html\n",
"I don't know any out-of-the-box histogram widget. You may have to write your own. You may be interested by the Widget Construction Kit to help you in this task.\n"
] | [
1,
1
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0003921912_python_tkinter.txt |
Q:
app engine DeadlineExceededError for cron jobs and task queue for wikipedia crawler
I am trying to build a wikipedia link crawler on google app engine. I wanted to store an index in the datastore. But I run into the DeadlineExceededError for both cron jobs and task queue.
for the cron job I have this code:
def buildTree(self):
start=time.time()
self.log.info(" Start Time: %f" % start)
nobranches=TreeNode.all()
for tree in nobranches:
if tree.branches==[]:
self.addBranches(tree)
time.sleep(1)
if (time.time()-start) > 10 :
break
self.log.info("Time Eclipsed: %f" % (time.time()-start))
self.log.info(" End Time:%f" % time.clock())
I don't understand why the for loop doesn't break after 10 seconds. It does on the dev server. Something must be wrong with the time.time() on the server. Is there another function I can use?
for the task queue I have this code:
def addNewBranch(self, keyword, level=0):
self.log.debug("Add Tree")
self.addBranches(keyword)
t=TreeNode.gql("WHERE name=:1", keyword).get()
branches=t.nodes
if level < 3:
for branch in branches:
if branch.branches == []:
taskqueue.add(url="/addTree/%s" % branch.name)
self.log.debug("url:%s" % "/addTree/%s" % branch.name)
The logs show that they both run into the DeadlineExceededError. Shouldn't background processing have a longer that the 30 seconds for the page request. Is there a way around the exception?
Here is the code for addBranch()
def addBranches(self, keyword):
tree=TreeNode.gql("WHERE name=:1", keyword).get()
if tree is None:
tree=TreeNode(name=keyword)
self.log.debug("in addBranches arguments: tree %s", tree.name)
t=urllib2.quote(tree.name.encode('utf8'))
s="http://en.wikipedia.org/w/api.php?action=query&titles=%s&prop=links&pllimit=500&format=xml" % t
self.log.debug(s)
try:
usock = urllib2.urlopen(s)
except :
self.log.error( "Could not retrieve doc: %s" % tree.name)
usock=None
if usock is not None:
try:
xmldoc=minidom.parse(usock)
except Exception , error:
self.log.error("Parse Error: %s" % error)
return None
usock.close()
try:
pyNode= xmldoc.getElementsByTagName('pl')
self.log.debug("Nodes to be added: %d" % pyNode.length)
except Exception, e:
pyNode=None
self.log.error("Getting Nodes Error: %s" % e)
return None
newNodes=[]
if pyNode is not None:
for child in pyNode:
node=None
node= TreeNode.gql("WHERE name=:1", child.attributes["title"].value).get()
if node is None:
newNodes.append(TreeNode(name=child.attributes["title"].value))
else:
tree.branches.append(node.key())
db.put(newNodes)
for node in newNodes:
tree.branches.append(node.key())
self.log.debug("Node Added: %s" % node.name)
tree.put()
return tree.branches
A:
I have had great success with datetimes on GAE.
from datetime import datetime, timedelta
time_start = datetime.now()
time_taken = datetime.now() - time_start
time_taken will be a timedelta. You can compare it against another timedelta that has the duration you are interested in.
ten_seconds = timedelta(seconds=10)
if time_taken > ten_seconds:
....do something quick.
It sounds like you would be far better served using mapreduce or Task Queues. Both are great fun for dealing with huge numbers of records.
A cleaner pattern for the code you have is to fetch only some records.
nobranches=TreeNode.all().fetch(100)
This code will only pull 100 records. If you have a full 100, when you are done, you can throw another item on the queue to launch off more.
-- Based on comment about needing trees without branches --
I do not see your model up there, but if I were trying to create a list of all of the trees without branches and process them, I would: Fetch the keys only for trees in blocks of 100 or so. Then, I would fetch all of the branches that belong to those trees using an In query. Order by the tree key. Scan the list of branches, the first time you find a tree's key, pull the key tree from the list. When done, you will have a list of "branchless" tree keys. Schedule each one of them for processing.
A simpler version is to use MapReduce on the trees. For each tree, find one branch that matches its ID. If you cannot, flag the tree for follow up. By default, this function will pull batches of trees (I think 25) with 8 simultaneous workers. And, it manages the job queues internally so you don't have to worry about timing out.
A:
There is not a way "around" the deadline exception aside from making your code execute within the proper timeframe.
A:
When DeadlineExcededErrors happen you want the request to eventually succeed if called again. This may require that your crawling state is guaranteed to have made some progress that can be skipped the next time. (Not addressed here)
Parallelized calls can help tremendously.
Urlfetch
Datastore Put (mixed entities together using db.put)
Datastore Query (queries in parallel - asynctools)
Urlfetch:
When you make your urlfetch calls be sure to use the asynchronous mode to collapse your loop.
Datastore
Combine Entities being put into a single round trip call.
# put newNodes+tree at the same time
db.put(newNodes+tree)
Pull TreeNode.gql from inside loop up into parallel query tool like asynctools
http://asynctools.googlecode.com
Asynctools Example
if pyNode is not None:
runner = AsyncMultiTask()
for child in pyNode:
title = child.attributes["title"].value
query = db.GqlQuery("SELECT __key__ FROM TreeNode WHERE name = :1", title)
runner.append(QueryTask(query, limit=1, client_state=title))
# kick off the work
runner.run()
# peel out the results
treeNodes = []
for task in runner:
task_result = task.get_result() # will raise any exception that occurred for the given query
treeNodes.append(task_result)
for node in treeNodes:
if node is None:
newNodes.append(TreeNode(name=child.attributes["title"].value))
else:
tree.branches.append(node.key())
for node in newNodes:
tree.branches.append(node.key())
self.log.debug("Node Added: %s" % node.name)
# put newNodes+tree at the same time
db.put(newNodes+tree)
return tree.branches
DISCLOSURE: I am associated with asynctools.
A:
The problem here is that you're doing a query operation for every link in your document. Since wikipedia pages can contain a lot of links, this means a lot of queries - and hence, you run out of processing time. This approach is also going to consume your quota at a fantastic rate!
Instead, you should use the page name of the Wikipedia page as the key name of the entity. Then, you can collect up all the links from the document into a list, construct keys from them (which is an entirely local operation), and do a single batch db.get for all of them. Once you've updated and/or created them as appropriate, you can do a batch db.put to store them all to the datastore - reducing your total datastore operations from numlinks*2 to just 2!
| app engine DeadlineExceededError for cron jobs and task queue for wikipedia crawler | I am trying to build a wikipedia link crawler on google app engine. I wanted to store an index in the datastore. But I run into the DeadlineExceededError for both cron jobs and task queue.
for the cron job I have this code:
def buildTree(self):
start=time.time()
self.log.info(" Start Time: %f" % start)
nobranches=TreeNode.all()
for tree in nobranches:
if tree.branches==[]:
self.addBranches(tree)
time.sleep(1)
if (time.time()-start) > 10 :
break
self.log.info("Time Eclipsed: %f" % (time.time()-start))
self.log.info(" End Time:%f" % time.clock())
I don't understand why the for loop doesn't break after 10 seconds. It does on the dev server. Something must be wrong with the time.time() on the server. Is there another function I can use?
for the task queue I have this code:
def addNewBranch(self, keyword, level=0):
self.log.debug("Add Tree")
self.addBranches(keyword)
t=TreeNode.gql("WHERE name=:1", keyword).get()
branches=t.nodes
if level < 3:
for branch in branches:
if branch.branches == []:
taskqueue.add(url="/addTree/%s" % branch.name)
self.log.debug("url:%s" % "/addTree/%s" % branch.name)
The logs show that they both run into the DeadlineExceededError. Shouldn't background processing have a longer that the 30 seconds for the page request. Is there a way around the exception?
Here is the code for addBranch()
def addBranches(self, keyword):
tree=TreeNode.gql("WHERE name=:1", keyword).get()
if tree is None:
tree=TreeNode(name=keyword)
self.log.debug("in addBranches arguments: tree %s", tree.name)
t=urllib2.quote(tree.name.encode('utf8'))
s="http://en.wikipedia.org/w/api.php?action=query&titles=%s&prop=links&pllimit=500&format=xml" % t
self.log.debug(s)
try:
usock = urllib2.urlopen(s)
except :
self.log.error( "Could not retrieve doc: %s" % tree.name)
usock=None
if usock is not None:
try:
xmldoc=minidom.parse(usock)
except Exception , error:
self.log.error("Parse Error: %s" % error)
return None
usock.close()
try:
pyNode= xmldoc.getElementsByTagName('pl')
self.log.debug("Nodes to be added: %d" % pyNode.length)
except Exception, e:
pyNode=None
self.log.error("Getting Nodes Error: %s" % e)
return None
newNodes=[]
if pyNode is not None:
for child in pyNode:
node=None
node= TreeNode.gql("WHERE name=:1", child.attributes["title"].value).get()
if node is None:
newNodes.append(TreeNode(name=child.attributes["title"].value))
else:
tree.branches.append(node.key())
db.put(newNodes)
for node in newNodes:
tree.branches.append(node.key())
self.log.debug("Node Added: %s" % node.name)
tree.put()
return tree.branches
| [
"I have had great success with datetimes on GAE.\nfrom datetime import datetime, timedelta\ntime_start = datetime.now()\ntime_taken = datetime.now() - time_start\n\ntime_taken will be a timedelta. You can compare it against another timedelta that has the duration you are interested in.\nten_seconds = timedelta(seco... | [
2,
1,
1,
1
] | [] | [] | [
"cron",
"google_app_engine",
"python",
"wikipedia"
] | stackoverflow_0003919337_cron_google_app_engine_python_wikipedia.txt |
Q:
How can I base64-encode unicode strings in JavaScript and Python?
I need an encript arithmetic, which encript text to text.
the input text could be unicode, and the output should be a-z A-Z 0-9 - . (64 char max)
and it could be decrypt to unicode again.
it should implement in javascript and python.
If there is already some library could do this, great, if there is not, could you tell me.
Let me talk about why
To cheat China Greate Fire Wall , and GAE https has been blocked at china. Angry for this damn goverment.
A:
You might want to look at the base64 module. In Python 2.x (starting with 2.4):
>>> import base64
>>> s=u"Rückwärts"
>>> s
u'R\xfcckw\xe4rts'
>>> b=base64.b64encode(s.encode("utf-8"))
>>> b
'UsO8Y2t3w6RydHM='
>>> d=base64.b64decode(b)
>>> d
'R\xc3\xbcckw\xc3\xa4rts'
>>> d.decode("utf-8")
u'R\xfcckw\xe4rts'
>>> print d.decode("utf-8")
Rückwärts
A:
You are looking for a base64 encoding. In JavaScript and Python 2 this is a bit complicated as the latter doesn't support unicode natively and for the former you would need to implement an Unicode encoding yourself.
Python 3 solution
>>> from base64 import b64encode, b64decode
>>> b64encode( 'Some random text with unicode symbols: äöü今日は'.encode() )
b'U29tZSByYW5kb20gdGV4dCB3aXRoIHVuaWNvZGUgc3ltYm9sczogw6TDtsO85LuK5pel44Gv'
>>> b64decode( b'U29tZSByYW5kb20gdGV4dCB3aXRoIHVuaWNvZGUgc3ltYm9sczogw6TDtsO85LuK5pel44Gv' )
b'Some random text with unicode symbols: \xc3\xa4\xc3\xb6\xc3\xbc\xe4\xbb\x8a\xe6\x97\xa5\xe3\x81\xaf'
>>> _.decode()
'Some random text with unicode symbols: äöü今日は'
| How can I base64-encode unicode strings in JavaScript and Python? | I need an encript arithmetic, which encript text to text.
the input text could be unicode, and the output should be a-z A-Z 0-9 - . (64 char max)
and it could be decrypt to unicode again.
it should implement in javascript and python.
If there is already some library could do this, great, if there is not, could you tell me.
Let me talk about why
To cheat China Greate Fire Wall , and GAE https has been blocked at china. Angry for this damn goverment.
| [
"You might want to look at the base64 module. In Python 2.x (starting with 2.4):\n>>> import base64\n>>> s=u\"Rückwärts\"\n>>> s\nu'R\\xfcckw\\xe4rts'\n>>> b=base64.b64encode(s.encode(\"utf-8\"))\n>>> b\n'UsO8Y2t3w6RydHM='\n>>> d=base64.b64decode(b)\n>>> d\n'R\\xc3\\xbcckw\\xc3\\xa4rts'\n>>> d.decode(\"utf-8\")\nu'... | [
10,
4
] | [] | [] | [
"base64",
"encoding",
"javascript",
"python"
] | stackoverflow_0003922314_base64_encoding_javascript_python.txt |
Q:
GAE simple app question
I am learning GAE with python. I am trying to build the simplest possible application: get name from user; write name to datastore; retrieve name and display page. I tried the tutorial but I still do not understand how to do this. I appreciate any answers. Thank you
A:
i´m going to post a little snippet:
Create a file in your root directory, name it main.py
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app
# Pagina principal
class MainPage(webapp.RequestHandler):
def get(self):
if users.get_current_user():
url = users.create_logout_url(self.request.uri)
url_linktext = "Bem Vindo: "+ str(users.get_current_user()) + ". Logout "
else:
url = users.create_login_url(self.request.uri)
url_linktext = ' Entrar '
values = {
'url': url,
'url_linktext': url_linktext,
}
self.response.out.write(template.render('templates/index.html', values))
application = webapp.WSGIApplication([
('/', MainPage),
],debug=True)
def main():
run_wsgi_app(application)
if __name__ == "__main__":
main()
then create a folder in your root directory, name it templates. Inside templates create a file and name it base.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<link href="styles/style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="mainContainer">
<!--menu-->
<div id="menu">
<ul id="menuUl">
<li class="selected"><a href="/"> Inicio </a> </li>
<li><a href="#">Sobre</a></li>
<li><a href="#">Else</a></li>
<li><a href="#">Portfolio</a></li>
<li><a href="#">Contacto</a></li>
</ul>
</div>
<!--End menu-->
</div>
<hr />
<!--End Navigation-->
<div id="header" >
{% block header %} {% endblock %}
</div>
<div id="contentContainer">
<!--content-->
<div id="content">
{% block main %} {% endblock %}
</div>
<div id="contentBottom" >
<div id="contentBottomLeft"></div>
<div id="contentBottomRight"></div>
</div>
</div>
<div id="footer">
<div id="footerMenu">
<ul>
<li class="selected"><a href="/"> Inicio </a> </li>
<li><a href="#">Sobre</a></li>
<li><a href="#">Ipca</a></li>
<li><a href="#">Portfolio</a></li>
<li><a href="#">Contacto</a></li>
</ul>
</div>
<p>Copyright © 2010 Martin . Todos os direitos reservados.</p>
</div>
</div>
</div>
</body>
</html>
This page is static. This code {% block main %} {% endblock %} and this {% block header %} {% endblock %} This code represents a variable that will receive a template. So if you want to put content on the header and content, you must create a new file, let's call index.html.
{% extends "base.html" %}
{% block header %}
<div class="hello">
<a href="{{ url }}">{{ url_linktext }}</a>
</div>
{% endblock %}
{% block main %}
<h1>Um pouco de palha</h1>
<p class="smallSubtitle">Isto e mais palha .......</p>
{% endblock %}
When you create a new template file, you have to put this code {% extends "base.html" %} and then you´ll call the block from header and content and fill it up.
What this does is present a page with Login info in it´s header. If you haven´t login yet it redirects you to login, else (it means, you´ve already login) shows the Logout button. Then presents dummy content on content block
| GAE simple app question | I am learning GAE with python. I am trying to build the simplest possible application: get name from user; write name to datastore; retrieve name and display page. I tried the tutorial but I still do not understand how to do this. I appreciate any answers. Thank you
| [
"i´m going to post a little snippet:\nCreate a file in your root directory, name it main.py\nfrom google.appengine.api import users\nfrom google.appengine.ext import webapp\nfrom google.appengine.ext.webapp import template\nfrom google.appengine.ext.webapp.util import run_wsgi_app\n\n# Pagina principal\nclass MainP... | [
3
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0003920371_google_app_engine_python.txt |
Q:
How to add Google Analytics to reStructuredText?
I am using reStructured text to create some easy websites.
So I have got a lot of *.rst files in which I want to add the Google Analytics code.
But as far as I know it is not possible to add something like this?!
I am using rst2html to convert the files to html.
A:
I've just discovered an easy way to add custom content to .rst files. All you need to do it to modify the template for html files.
Make a new template template.txt and the following contents to it (based on the default template):
%(head_prefix)s
%(head)s
<!--your tracking code-->
%(stylesheet)s
%(body_prefix)s
%(body_pre_docinfo)s
%(docinfo)s
%(body)s
%(body_suffix)s
The format is pretty self explanatory and its also a good way to remove the default CSS and specify a link to another one in the template etc.
Now you can use your custom template with the rst2html writer:
rst2html.py --template=template.txt document.rst
A:
I guess, you'd have to extend the docutils HTML Translator or Writer to include GA.
If possible, I'd recommend to abandon rst2html and plain docutils and use Sphinx instead. It is based on docutils, but far more powerful. Its HTML templates can easily be extended to include arbitrary HTML like script tags for Google Analytics.
A:
You can insert html to rst files using the .. raw:: directive.
A:
As a workaround to your problem, you could use a mass search/replace tool to add the Google Analytics code to the files after they have been through the translator. Just search for the </body> tag and replace it with <!--your tracking code--></body>.
I checked to see if you can include raw HTML in reStructuredText (and have it be untouched), but it doesn't seem possible...
| How to add Google Analytics to reStructuredText? | I am using reStructured text to create some easy websites.
So I have got a lot of *.rst files in which I want to add the Google Analytics code.
But as far as I know it is not possible to add something like this?!
I am using rst2html to convert the files to html.
| [
"I've just discovered an easy way to add custom content to .rst files. All you need to do it to modify the template for html files. \nMake a new template template.txt and the following contents to it (based on the default template):\n%(head_prefix)s\n%(head)s\n<!--your tracking code-->\n%(stylesheet)s\n%(body_prefi... | [
7,
2,
2,
1
] | [] | [] | [
"docutils",
"python",
"restructuredtext"
] | stackoverflow_0003176258_docutils_python_restructuredtext.txt |
Q:
Getting a result from a modal window in pygtk
I need to open a new window from my applications main window. This new window need to be
modal, I need to be able to get a result from the modal window based on user interaction with it.
I have figured out how to make the window modal. But I can't figure out how to return a result from the modal window and pass it back to the main window when user close the modal window.
A:
You probably want to make your window a gtk.Dialog and launch it via the run() method. This is designed to do exactly what you are looking for.
See pygtk docs for gtk.Dialog.run
| Getting a result from a modal window in pygtk | I need to open a new window from my applications main window. This new window need to be
modal, I need to be able to get a result from the modal window based on user interaction with it.
I have figured out how to make the window modal. But I can't figure out how to return a result from the modal window and pass it back to the main window when user close the modal window.
| [
"You probably want to make your window a gtk.Dialog and launch it via the run() method. This is designed to do exactly what you are looking for. \nSee pygtk docs for gtk.Dialog.run\n"
] | [
1
] | [] | [] | [
"modal_dialog",
"pygtk",
"python"
] | stackoverflow_0003922829_modal_dialog_pygtk_python.txt |
Q:
Pythonic way to write create dictionary from dict comprehension, + something else
I want to do something like this:
parsetable = {
# ...
declarations: {
token: 3 for token in [_id, _if, _while, _lbrace, _println]
}.update({_variable: 2}),
#...
}
However this doesn't work because update doesn't return anything. Is there any easy way to do this besides writing the entire dict explicitly?
It should be possible using dict() and a list comprehension of tuples + the extra part, but that is awkward.
A:
I think the approach you mentioned using dict() and a list of tuples is the way I would do it:
dict([(x, 3) for x in [_id, _if, _while, _lbrace, _println]] + [(_variable, 2)])
If you really want to use a dict comprehension you can do something like this:
{ x : 2 if x == _variable else 3
for x in [_id, _if, _while, _lbrace, _println, _variable] }
A:
however, just to let you know, if you want update return somethign, you can write a func like:
import copy
def updated_dict(first_dict, second_dict):
f = copy.deepcopy(first_dict)
f.update(second_dict)
return f
A:
I'd split it up for clarity then apply @Mark Byers' second suggestion for a dict comprehension:
type2 = [_variable]
type3 = [_id, _if, _while, _lbrace, _println]
parsetable = {
declarations: { token : 2 if token in type2 else 3 for token in type2+type3 }
}
This makes things very clear and is extensible, while keeping related items together for look up ease and/or modification.
A:
Here's something similar to what @Ant mentioned shown applied to your sample data:
def merged_dicts(dict1, *dicts):
for dict_ in dicts:
dict1.update(dict_)
return dict1
parsetable = {
declarations:
merged_dicts(
{ token: 3 for token in [_id, _if, _while, _lbrace, _println] },
{ _variable: 2 }
),
}
I left the preliminary copy.deepcopy() out since it's unnecessary for usage of this kind.
| Pythonic way to write create dictionary from dict comprehension, + something else | I want to do something like this:
parsetable = {
# ...
declarations: {
token: 3 for token in [_id, _if, _while, _lbrace, _println]
}.update({_variable: 2}),
#...
}
However this doesn't work because update doesn't return anything. Is there any easy way to do this besides writing the entire dict explicitly?
It should be possible using dict() and a list comprehension of tuples + the extra part, but that is awkward.
| [
"I think the approach you mentioned using dict() and a list of tuples is the way I would do it:\ndict([(x, 3) for x in [_id, _if, _while, _lbrace, _println]] + [(_variable, 2)])\n\nIf you really want to use a dict comprehension you can do something like this:\n{ x : 2 if x == _variable else 3\n for x in [_id, _if,... | [
4,
1,
1,
1
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0003918059_dictionary_python.txt |
Q:
How to interchange data between two python applications?
I have two python applications. I need to send commands and data between them (between two processes).
What is the best way to do that?
One program is a daemon who should accept commands and parameters from another GUI application.
How can I make daemon to monitor comands from GUI, while making it's job?
I prefer solution would be crossplatform.
p.s. I use pyqt4 and python.
A:
You can use the following methods for data interchange:
Socket Programming : In Qt you can access QtNetwork module. See qt assistant for examples
IPC : Use shared Memory implemented in QSharedMemory class.
If this application will run on unix os only, then you can try Posix based message queue etc. for data interchange
DBUS : You will find both python and Qt have DBus based support. In Case of python you need to find the relevant module.
Using Multi Processing module
Using Posix/SystemV based IPC mechanism aka pipes, queue, etc.
A:
While it's not related to the way of the communication, I recommend checking out the pickle/cPickle module (which can encode objects into string streams and vice versa). Very useful.
A:
Example.
Program_1.py
import pickle
import sys
for i in range(100):
pickle.dump(i,sys.stdout)
Program_2.py
from __future__ import print_function
import pickle
import sys
while True:
obj= pickle.load(sys.stdin)
print( obj )
Usage:
Program_1.py | Program_2.py
Under Windows, this may exhibit bad behavior because of the way Windows botches up simple file IO redirects.
| How to interchange data between two python applications? | I have two python applications. I need to send commands and data between them (between two processes).
What is the best way to do that?
One program is a daemon who should accept commands and parameters from another GUI application.
How can I make daemon to monitor comands from GUI, while making it's job?
I prefer solution would be crossplatform.
p.s. I use pyqt4 and python.
| [
"You can use the following methods for data interchange:\n\nSocket Programming : In Qt you can access QtNetwork module. See qt assistant for examples\nIPC : Use shared Memory implemented in QSharedMemory class.\nIf this application will run on unix os only, then you can try Posix based message queue etc. for data i... | [
10,
2,
0
] | [] | [] | [
"pid",
"process",
"pyqt4",
"python"
] | stackoverflow_0003922135_pid_process_pyqt4_python.txt |
Q:
set key with new bulkloader
I am converting a script to use the new bulkloader. (What was wrong
with the original bulkloader? - I prefer writing Python to editing
configuration files...)
Anyway, I want to prevent duplicates by assigning a combination of
properties to the key.
The docs say:
If you want to use or calculate a key
from the import data, specify a key
using the same syntax as the property
map; that is, external_name,
import_template, and so on.
All the examples apply a transform to the current property. How do I
instead use a combination of other properties?
Should be something like:
- property: __key__
external_name: key
import_transform: entity.first_name + entity.last_name
A:
You can do this using the 'import_template' property (documented here) instead of 'import_transform':
- property: __key__
import_template: "%(first_name)s %(last_name)s"
| set key with new bulkloader | I am converting a script to use the new bulkloader. (What was wrong
with the original bulkloader? - I prefer writing Python to editing
configuration files...)
Anyway, I want to prevent duplicates by assigning a combination of
properties to the key.
The docs say:
If you want to use or calculate a key
from the import data, specify a key
using the same syntax as the property
map; that is, external_name,
import_template, and so on.
All the examples apply a transform to the current property. How do I
instead use a combination of other properties?
Should be something like:
- property: __key__
external_name: key
import_transform: entity.first_name + entity.last_name
| [
"You can do this using the 'import_template' property (documented here) instead of 'import_transform':\n- property: __key__\n import_template: \"%(first_name)s %(last_name)s\"\n\n"
] | [
1
] | [] | [] | [
"backup",
"bulkloader",
"google_app_engine",
"python"
] | stackoverflow_0003920171_backup_bulkloader_google_app_engine_python.txt |
Q:
Split a string in python
a="aaaa#b:c:"
>>> for i in a.split(":"):
... print i
... if ("#" in i): //i=aaaa#b
... print only b
In the if loop if i=aaaa#b how to get the value after the hash.should we use rsplit to get the value?
A:
The following can replace your if statement.
for i in a.split(':'):
print i.partition('#')[2]
A:
a = "aaaa#b:c:"
print(a.split(":")[0].split("#")[1])
A:
I'd suggest from: Python Docs
str.rsplit([sep[, maxsplit]])
Return a list of the words in the string, using sep as the delimiter
string. If maxsplit is given, at most maxsplit splits are done, the
rightmost ones. If sep is not specified or None, any whitespace string
is a separator. Except for splitting from the right, rsplit() behaves
like split() which is described in detail below.
so to answer your question yes.
EDIT:
It depends on how you wish to index your strings too, it looks like Rstring does it from the right, so if your data is always "rightmost" you could index by 0 (or 1, not sure how python indexes), every time, rather then having to do a size check of the returned array.
A:
>>> a="aaaa#b:c:"
>>> a.split(":",2)[0].split("#")[-1]
'b'
A:
do you really need to use split? split create a list, so isn't so efficient...
what about something like this:
>>> a = "aaaa#b:c:"
>>> a[a.find('#') + 1]
'b'
or if you need particular occurence, use regex instead...
| Split a string in python | a="aaaa#b:c:"
>>> for i in a.split(":"):
... print i
... if ("#" in i): //i=aaaa#b
... print only b
In the if loop if i=aaaa#b how to get the value after the hash.should we use rsplit to get the value?
| [
"The following can replace your if statement.\nfor i in a.split(':'):\n print i.partition('#')[2]\n\n",
"a = \"aaaa#b:c:\"\nprint(a.split(\":\")[0].split(\"#\")[1])\n\n",
"I'd suggest from: Python Docs\n\nstr.rsplit([sep[, maxsplit]])\nReturn a list of the words in the string, using sep as the delimiter\n s... | [
2,
1,
1,
1,
0
] | [
"split would do the job nicely. Use rsplit only if you need to split from the last '#'.\na=\"aaaa#b:c:\"\n>>> for i in a.split(\":\"):\n... print i\n... b = i.split('#',1)\n... if len(b)==2:\n... print b[1]\n\n"
] | [
-1
] | [
"python",
"string"
] | stackoverflow_0003914659_python_string.txt |
Q:
Understanding what files in the TCL are required for distributing frozen Python Tkinter apps
I'm trying to figure out which files in Python's (Python 2.6/Python 2.7) tcl folder are required in order to distribute frozen Python Tkinter apps using Py2exe or similar.
The quick and dirty way to do this (using pyexe as an example) is to follow the 2nd example on the following page and then xcopy your python's tcl folder to your dist folder (as a tcl sub-folder).
http://www.py2exe.org/index.cgi/TixSetup
The problem with the xcopy tcl technique is that it copies 100's of extra files that may not be needed for distribution.
For example, my experiments show that the following tcl folders may(???) not be needed when freezing Python 2.7 Tkinter applications:
Note: The numeric sizes are the sum of all the files in each of these paths.
tcl\tcl8.5\encoding 1415K (delete non-applicable encodings? any needed for UTF-8/Unicode?)
tcl\tcl8.5\tzdata 1450K (timezone data for a tcl clock demo?)
tcl\tcl8.5*.tcl 256K
tcl\tix8.4.3\demos 246K
tcl\tk8.5\demos 685K
Am I on the right path or will not including the above tcl content bite me in the butt down the road?
Even better, is there some sort of documentation regarding the files in Python's tcl folder?
Thank you,
Malcolm
A:
You don't need the demos (I hope; if you do, that's gross!) but everything else is potentially required; the encodings are used to convert between the outside world's bytes and Tcl's characters, and the tzdata is used to make the time processing work. You can trim the encodings and tzdata if you are delivering the app to a small target market – indeed, on Unix you might be able to leave out the whole of tzdata because the system will have an up-to-date version – but you should be aware that you are restricting the code's portability.
A:
Donal is right, of course. Your question is one that motivates at least several other people, though; if you'd like to pursue it more, I strongly recommend you check in with the Tkinter mailing list and associated Wiki.
| Understanding what files in the TCL are required for distributing frozen Python Tkinter apps | I'm trying to figure out which files in Python's (Python 2.6/Python 2.7) tcl folder are required in order to distribute frozen Python Tkinter apps using Py2exe or similar.
The quick and dirty way to do this (using pyexe as an example) is to follow the 2nd example on the following page and then xcopy your python's tcl folder to your dist folder (as a tcl sub-folder).
http://www.py2exe.org/index.cgi/TixSetup
The problem with the xcopy tcl technique is that it copies 100's of extra files that may not be needed for distribution.
For example, my experiments show that the following tcl folders may(???) not be needed when freezing Python 2.7 Tkinter applications:
Note: The numeric sizes are the sum of all the files in each of these paths.
tcl\tcl8.5\encoding 1415K (delete non-applicable encodings? any needed for UTF-8/Unicode?)
tcl\tcl8.5\tzdata 1450K (timezone data for a tcl clock demo?)
tcl\tcl8.5*.tcl 256K
tcl\tix8.4.3\demos 246K
tcl\tk8.5\demos 685K
Am I on the right path or will not including the above tcl content bite me in the butt down the road?
Even better, is there some sort of documentation regarding the files in Python's tcl folder?
Thank you,
Malcolm
| [
"You don't need the demos (I hope; if you do, that's gross!) but everything else is potentially required; the encodings are used to convert between the outside world's bytes and Tcl's characters, and the tzdata is used to make the time processing work. You can trim the encodings and tzdata if you are delivering the... | [
5,
3
] | [] | [] | [
"freeze",
"py2exe",
"python",
"tcl",
"tkinter"
] | stackoverflow_0003900375_freeze_py2exe_python_tcl_tkinter.txt |
Q:
How to validate an xml file against an XSD Schema using Amara library in Python?
High bounty for the following Q:
Hello,
Here is what I tried on Ubuntu 9.10 using Python 2.6, Amara2
(by the way, test.xsd was created using xml2xsd tool):
g@spot:~$ cat test.xml; echo =====o=====; cat test.xsd; echo ====
o=====; cat test.py; echo =====o=====; ./test.py; echo =====o=====
<?xml version="1.0" encoding="utf-8"?>==; ./test.py` >
test.txttest.xsd; echo ===
<test>abcde</test>
=====o=====
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
elementFormDefault="qualified">
<xs:element name="test" type="xs:NCName"/>
</xs:schema>
=====o=====
#!/usr/bin/python2.6
# I wish to validate an xml file against an external XSD schema.
from amara import bindery, parse
source = 'test.xml'
schema = 'test.xsd'
#help(bindery.parse)
#doc = bindery.parse(source, uri=schema, validate=True) # These 2 seem
to fail in the same way.
doc = parse(source, uri=schema, validate=True) # So, what is the
difference anyway?
#
=====o=====
Traceback (most recent call last):
File "./test.py", line 14, in <module>
doc = parse(source, uri=schema, validate=True)
File "/usr/local/lib/python2.6/dist-packages/Amara-2.0a4-py2.6-linux-
x86_64.egg/amara/tree.py", line 50, in parse
return _parse(inputsource(obj, uri), flags,
entity_factory=entity_factory)
amara.ReaderError: In file:///home/g/test.xml, line 2, column 0:
Missing document type declaration
g@spot:~$
=====o=====
So, why am I seeing this error? Is this functionality not supported?
How can I validate an XML file against an XSD while having the
flexibility to point to any XSD file?
Thanks, and let me know if you have questions.
A:
If you're open to using another library besides amara, try lxml. It supports what you're trying to do pretty easily:
from lxml import etree
source_file = 'test.xml'
schema_file = 'test.xsd'
with open(schema_file) as f_schema:
schema_doc = etree.parse(f_schema)
schema = etree.XMLSchema(schema_doc)
parser = etree.XMLParser(schema = schema)
with open(source_file) as f_source:
try:
doc = etree.parse(f_source, parser)
except etree.XMLSyntaxError as e:
# this exception is thrown on schema validation error
print e
A:
I'll recommend you to use noNamespaceSchemaLocation attribute to bind the XML file to the XSD schema. Then your XML file test.xml will be
<?xml version="1.0" encoding="utf-8"?>
<test xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="test.xsd">abcde</test>
where the file test.xsd
<?xml version="1.0" encoding="utf-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
elementFormDefault="qualified">
<xs:element name="test" type="xs:NCName"/>
</xs:schema>
should be placed in the same directory as the test.xsd. It is general technique to reference the XML schema from the XML file and it should work in Python.
The advantage is that you don't need to know the schema file for every XML file. It will be automatically found during parsing (etree.parse) of the XML file.
| How to validate an xml file against an XSD Schema using Amara library in Python? | High bounty for the following Q:
Hello,
Here is what I tried on Ubuntu 9.10 using Python 2.6, Amara2
(by the way, test.xsd was created using xml2xsd tool):
g@spot:~$ cat test.xml; echo =====o=====; cat test.xsd; echo ====
o=====; cat test.py; echo =====o=====; ./test.py; echo =====o=====
<?xml version="1.0" encoding="utf-8"?>==; ./test.py` >
test.txttest.xsd; echo ===
<test>abcde</test>
=====o=====
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
elementFormDefault="qualified">
<xs:element name="test" type="xs:NCName"/>
</xs:schema>
=====o=====
#!/usr/bin/python2.6
# I wish to validate an xml file against an external XSD schema.
from amara import bindery, parse
source = 'test.xml'
schema = 'test.xsd'
#help(bindery.parse)
#doc = bindery.parse(source, uri=schema, validate=True) # These 2 seem
to fail in the same way.
doc = parse(source, uri=schema, validate=True) # So, what is the
difference anyway?
#
=====o=====
Traceback (most recent call last):
File "./test.py", line 14, in <module>
doc = parse(source, uri=schema, validate=True)
File "/usr/local/lib/python2.6/dist-packages/Amara-2.0a4-py2.6-linux-
x86_64.egg/amara/tree.py", line 50, in parse
return _parse(inputsource(obj, uri), flags,
entity_factory=entity_factory)
amara.ReaderError: In file:///home/g/test.xml, line 2, column 0:
Missing document type declaration
g@spot:~$
=====o=====
So, why am I seeing this error? Is this functionality not supported?
How can I validate an XML file against an XSD while having the
flexibility to point to any XSD file?
Thanks, and let me know if you have questions.
| [
"If you're open to using another library besides amara, try lxml. It supports what you're trying to do pretty easily:\nfrom lxml import etree\n\nsource_file = 'test.xml'\nschema_file = 'test.xsd'\n\nwith open(schema_file) as f_schema:\n\n schema_doc = etree.parse(f_schema)\n schema = etree.XMLSchema(schema_do... | [
5,
1
] | [] | [] | [
"amara",
"python",
"python_2.6",
"xsd_validation"
] | stackoverflow_0003330366_amara_python_python_2.6_xsd_validation.txt |
Q:
How do I down-cast a c++ object from a python SWIG wrapper?
The problem: I've wrapped some c++ code in python using SWIG. On the python side, I want to take a wrapped c++ pointer and down-cast it to be a pointer to a subclass. I've added a new c++ function to the SWIG .i file that does this down-casting, but when I call it from python, I get a TypeError.
Here are the details:
I have two c++ classes, Base and Derived. Derived is a subclass of Base. I have a third class, Container, which contains a Derived, and provides an accessor to it. The accessor returns the Derived as a const Base&, as shown:
class Container {
public:
const Base& GetBase() const {
return derived_;
}
private:
Derived derived_;
};
I've wrapped these classes in python using SWIG. In my python code, I would like to down-cast the Base reference back down to a Derived. To do this, I've written into the swig .i file a helper function in c++ which does the down-casting:
%inline %{
Derived* CastToDerived(Base* base) {
return static_cast<Derived*>(base);
}
%}
In my python code, I call this down-casting function:
base = container.GetBase()
derived = CastToDerived(base)
When I do so, I get the following error:
TypeError: in method 'CastToDerived', argument 1 of type 'Base *'
Why might this be happening?
For reference, here are the relevant bits of the .cxx file generated by SWIG; namely the original function, and its python-interface-ified doppelganger:
Derived* CastToDerived(Base* base) {
return static_cast<Derived*>(base);
}
// (lots of other generated code omitted)
SWIGINTERN PyObject *_wrap_CastToDerived(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
PyObject *resultobj = 0;
Base *arg1 = (Base *) 0 ;
void *argp1 = 0 ;
int res1 = 0 ;
PyObject * obj0 = 0 ;
Derived *result = 0 ;
if (!PyArg_ParseTuple(args,(char *)"O:CastToDerived",&obj0)) SWIG_fail;
res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_Base, 0 | 0 );
if (!SWIG_IsOK(res1)) {
SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "CastToDerived" "', argument " "1"" of type '" "Base *""'");
}
arg1 = reinterpret_cast< Base * >(argp1);
result = (Derived *)CastToDerived(arg1);
resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_Derived, 0 | 0 );
return resultobj;
fail:
return NULL;
}
Any help would be greatly appreciated.
-- Matt
A:
As I commented above, this seems to work ok with swig 1.3.40.
Here are my files:
c.h:
#include <iostream>
class Base {};
class Derived : public Base
{
public:
void f() const { std::cout << "In Derived::f()" << std::endl; }
};
class Container {
public:
const Base& GetBase() const {
return derived_;
}
private:
Derived derived_;
};
c.i
%module c
%{
#define SWIG_FILE_WITH_INIT
#include "c.h"
%}
%inline %{
Derived* CastToDerived(Base* base) {
return static_cast<Derived*>(base);
}
%}
class Base
{
};
class Derived : public Base
{
public:
void f() const;
};
class Container {
public:
const Base& GetBase() const;
};
ctest.py
import c
container = c.Container()
b = container.GetBase()
d = c.CastToDerived(b)
d.f()
print "ok"
A run:
$ swig -c++ -python c.i
$ g++ -fPIC -I/usr/include/python2.6 -c -g c_wrap.cxx
$ g++ -shared -o _c.so c_wrap.o
$ python ctest.py
In Derived::f()
ok
A:
2 things I notice in your code 1st GetBase returns a reference to const and second that CastToDerived expects a pointer to non-const Base.
Even in C++ you'd have enough trouble making this work. I can't tell what else should be wrong but I would try to get this fxied first.
A:
Is it possible that you are defining the Base class multiple times? I've had similar problems with ctypes where I unwittingly defined the same structure class in two different modules. I've also had something similar happen in pure Python, where I used imp.load_module to load a plugin class, created an object of that class, then reloaded the module - poof! the created object would no longer pass an isinstance test of the class, since the reloaded class, even though it had the same name, was a different class, with different id. (More complete description in this blog entry.)
| How do I down-cast a c++ object from a python SWIG wrapper? | The problem: I've wrapped some c++ code in python using SWIG. On the python side, I want to take a wrapped c++ pointer and down-cast it to be a pointer to a subclass. I've added a new c++ function to the SWIG .i file that does this down-casting, but when I call it from python, I get a TypeError.
Here are the details:
I have two c++ classes, Base and Derived. Derived is a subclass of Base. I have a third class, Container, which contains a Derived, and provides an accessor to it. The accessor returns the Derived as a const Base&, as shown:
class Container {
public:
const Base& GetBase() const {
return derived_;
}
private:
Derived derived_;
};
I've wrapped these classes in python using SWIG. In my python code, I would like to down-cast the Base reference back down to a Derived. To do this, I've written into the swig .i file a helper function in c++ which does the down-casting:
%inline %{
Derived* CastToDerived(Base* base) {
return static_cast<Derived*>(base);
}
%}
In my python code, I call this down-casting function:
base = container.GetBase()
derived = CastToDerived(base)
When I do so, I get the following error:
TypeError: in method 'CastToDerived', argument 1 of type 'Base *'
Why might this be happening?
For reference, here are the relevant bits of the .cxx file generated by SWIG; namely the original function, and its python-interface-ified doppelganger:
Derived* CastToDerived(Base* base) {
return static_cast<Derived*>(base);
}
// (lots of other generated code omitted)
SWIGINTERN PyObject *_wrap_CastToDerived(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
PyObject *resultobj = 0;
Base *arg1 = (Base *) 0 ;
void *argp1 = 0 ;
int res1 = 0 ;
PyObject * obj0 = 0 ;
Derived *result = 0 ;
if (!PyArg_ParseTuple(args,(char *)"O:CastToDerived",&obj0)) SWIG_fail;
res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_Base, 0 | 0 );
if (!SWIG_IsOK(res1)) {
SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "CastToDerived" "', argument " "1"" of type '" "Base *""'");
}
arg1 = reinterpret_cast< Base * >(argp1);
result = (Derived *)CastToDerived(arg1);
resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_Derived, 0 | 0 );
return resultobj;
fail:
return NULL;
}
Any help would be greatly appreciated.
-- Matt
| [
"As I commented above, this seems to work ok with swig 1.3.40.\nHere are my files:\nc.h:\n#include <iostream>\nclass Base {};\nclass Derived : public Base\n{\n public:\n void f() const { std::cout << \"In Derived::f()\" << std::endl; }\n};\nclass Container {\n public:\n const Base& GetBase() const {\n... | [
3,
0,
0
] | [] | [] | [
"c++",
"downcast",
"python",
"swig",
"typeerror"
] | stackoverflow_0003921294_c++_downcast_python_swig_typeerror.txt |
Q:
translating arrays from c to python ctypes
I have the below arrays on C how can i interpert them to ctypes datatypes inside structre
struct a {
BYTE a[30];
CHAR b[256];
};
should i interpert a fixed array as the datatype * the size i want like the below and if yes how can i
call this structure as a parameter to fun that takes instance from this structure
class a(structure) :
_fields_ = [ ("a",c_bytes*30 ),
("b",c_char*256 ),]
A:
You're on the right track. You're probably just missing the byref() function. Assuming the function you want to call is named *print_struct*, do the following:
from ctypes import *
class MyStruct(Structure):
_fields_ = [('a',c_byte*30), ('b',c_char*256)]
s = MyStruct() # Allocates a new instance of the structure from Python
s.a[5] = 10 # Use as normal
d = CDLL('yourdll.so')
d.print_struct( byref(s) ) # byref() passes a pointer rather than passing by copy
A:
This should work:
from ctypes import Structure, c_bytes, c_char
class A(Structure):
_fields_ = [("a", c_bytes*30), ("b", c_char*256)]
Then you can simply access the fields of the structure using the dot operator:
>>> my_a = A()
>>> my_a.a[4] = 127
>>> my_a.a[4]
127
>>> my_a.b = "test string"
>>> my_a.b
'test string'
>>> my_a.b[2]
's'
You can also pass the structure directly to an arbitrary Python function:
def my_func(a):
print "a[0] + a[1] = %d" % (a.a[0] + a.a[1], )
print "Length of b = %d" % len(a.b)
>>> my_a = A()
>>> my_a.a[0:2] = 19, 23
>>> my_a.b = "test"
>>> my_func(my_a)
a[0] + a[1] = 42
Length of b = 4
| translating arrays from c to python ctypes | I have the below arrays on C how can i interpert them to ctypes datatypes inside structre
struct a {
BYTE a[30];
CHAR b[256];
};
should i interpert a fixed array as the datatype * the size i want like the below and if yes how can i
call this structure as a parameter to fun that takes instance from this structure
class a(structure) :
_fields_ = [ ("a",c_bytes*30 ),
("b",c_char*256 ),]
| [
"You're on the right track. You're probably just missing the byref() function. Assuming the function you want to call is named *print_struct*, do the following:\nfrom ctypes import *\n\nclass MyStruct(Structure):\n _fields_ = [('a',c_byte*30), ('b',c_char*256)]\n\ns = MyStruct() # Allocates a new instance of the... | [
3,
0
] | [] | [] | [
"ctypes",
"python"
] | stackoverflow_0003922290_ctypes_python.txt |
Q:
Py2Exe + FTDI driver
Is it at all possible to somehow include the FTDI driver in a py2exe installer? If not, are there any ways to combine the two together in one easy installer?
A:
Include the FTDI driver folders in your distribution using py2exe's data_files option.
You can run code like this to make the drivers visible to your application even if they aren't installed in system32:
os.environ['PATH'] = '%s;%s' % (os.environ['PATH'], os.path.abspath('./driver/i386'))
os.environ['PATH'] = '%s;%s' % (os.environ['PATH'], os.path.abspath('./driver/amd64'))
Of course, once a device is plugged in, Windows will ask for a driver. At least you can point it to where your app is installed to find it.
| Py2Exe + FTDI driver | Is it at all possible to somehow include the FTDI driver in a py2exe installer? If not, are there any ways to combine the two together in one easy installer?
| [
"Include the FTDI driver folders in your distribution using py2exe's data_files option.\nYou can run code like this to make the drivers visible to your application even if they aren't installed in system32:\nos.environ['PATH'] = '%s;%s' % (os.environ['PATH'], os.path.abspath('./driver/i386'))\nos.environ['PATH'] = ... | [
0
] | [] | [] | [
"driver",
"ftdi",
"installation",
"py2exe",
"python"
] | stackoverflow_0003923644_driver_ftdi_installation_py2exe_python.txt |
Q:
Python solution to allow photo uploading via email to my Django website
I am learning Python/Django and my pet project is a photo sharing website. I would like to give users the ability to upload their photos using an email address like Posterous, Tumblr. Research has led me to believe I need to use the following:
-- cron job
-- python mail parser
-- cURL or libcurl
-- something that updates my database
How all these parts will work together is still where I need clarification. I know the cron will run a script that parses the email (sounds simple when reading), but how to get started with all these things is daunting. Any help in pointing me in the right direction, tutorials, or an answer would be greatly appreciated.
A:
Read messages from maildir. It's not optimized but show how You can parse emails. Of course you should store information about files and users to database. Import models into this code and make right inserts.
import mailbox
import sys
import email
import os
import errno
import mimetypes
mdir = mailbox.Maildir(sys.argv [1], email.message_from_file)
for mdir_msg in mdir:
counter = 1
msg = email.message_from_string(str(mdir_msg))
for part in msg.walk():
# multipart/* are just containers
if part.get_content_maintype() == 'multipart':
continue
# Applications should really sanitize the given filename so that an
# email message can't be used to overwrite important files
filename = part.get_filename()
if not filename:
ext = mimetypes.guess_extension(part.get_content_type())
if not ext:
# Use a generic bag-of-bits extension
ext = '.bin'
filename = 'part-%03d%s' % (counter, ext)
counter += 1
fp = open(os.path.join('kupa', filename), 'wb')
fp.write(part.get_payload(decode=True))
fp.close()
#photomodel imported from yourapp.models
photo = PhotoModel()
photo.name = os.path.join('kupa', filename)
photo.email = ....
photo.save()
A:
Not sure what you need cURL for in that list - what's it supposed to be doing?
You don't really say where you're having trouble. It seems to me you can do all this in a Django management command, which can be triggered on a regular cron. The standard Python library contains everything you need to access the mailbox (smtplib) and parse the message to get the image (email and email.message). The script can then simply save the image file to the relevant place on disk, and create a matching entry in the database via the normal Django ORM.
| Python solution to allow photo uploading via email to my Django website | I am learning Python/Django and my pet project is a photo sharing website. I would like to give users the ability to upload their photos using an email address like Posterous, Tumblr. Research has led me to believe I need to use the following:
-- cron job
-- python mail parser
-- cURL or libcurl
-- something that updates my database
How all these parts will work together is still where I need clarification. I know the cron will run a script that parses the email (sounds simple when reading), but how to get started with all these things is daunting. Any help in pointing me in the right direction, tutorials, or an answer would be greatly appreciated.
| [
"Read messages from maildir. It's not optimized but show how You can parse emails. Of course you should store information about files and users to database. Import models into this code and make right inserts.\nimport mailbox\nimport sys\nimport email\nimport os\nimport errno\nimport mimetypes\n\n\nmdir = mailbox.M... | [
3,
0
] | [] | [] | [
"cron",
"django",
"email",
"postfix_mta",
"python"
] | stackoverflow_0003923915_cron_django_email_postfix_mta_python.txt |
Q:
Convert string to a tuple
I have a string like this:
'|Action and Adventure|Drama|Science-Fiction|Fantasy|'
How can I convert it to a tuple or a list?
Thanks.
A:
>>> s = '|Action and Adventure|Drama|Science-Fiction|Fantasy|'
>>>
>>> [item for item in s.split('|') if item.strip()]
['Action and Adventure', 'Drama', 'Science-Fiction', 'Fantasy']
>>>
If you'd rather have a tuple then:
>>> tuple(item for item in s.split('|') if item.strip())
('Action and Adventure', 'Drama', 'Science-Fiction', 'Fantasy')
>>>
A:
You want str.split():
>>> s = '|Action and Adventure|Drama|Science-Fiction|Fantasy|'
>>> s.split('|')
['', 'Action and Adventure', 'Drama', 'Science-Fiction', 'Fantasy', '']
A:
If you want to just split your string at the | character you use:
myStr.split('|')
If you also want all zero-length element removed (like the ones from the ends) you:
def myFilter(el): return len(el) > 0
filter(myFilter, myStr.split('|'))
A:
Strip
'string'.strip('|')
>>> heading = '|Action and Adventure|Drama|Science-Fiction|Fantasy|'
>>> tuple(heading.strip('|').split('|'))
('Action and Adventure', 'Drama', 'Science-Fiction', 'Fantasy')
Slice
'string'[1:-1]
>>> heading = '|Action and Adventure|Drama|Science-Fiction|Fantasy|'
>>> tuple(heading[1:-1].split('|'))
('Action and Adventure', 'Drama', 'Science-Fiction', 'Fantasy')
For List remove the tuple() call.
A:
strip() gets rid of the leading and trailing chars, split() divvies up the remainder:
>>> s.strip('|').split('|')
['Action and Adventure', 'Drama', 'Science-Fiction', 'Fantasy']
A:
List
seq = '|Action and Adventure|Drama|Science-Fiction|Fantasy|'.split('|')
Tuple
seq = tuple(seq)
If you want to strip empty items, pass the output through filter(None, seq). If you assume outer | always, just slice with seq[1:-1].
| Convert string to a tuple | I have a string like this:
'|Action and Adventure|Drama|Science-Fiction|Fantasy|'
How can I convert it to a tuple or a list?
Thanks.
| [
">>> s = '|Action and Adventure|Drama|Science-Fiction|Fantasy|'\n>>> \n>>> [item for item in s.split('|') if item.strip()]\n['Action and Adventure', 'Drama', 'Science-Fiction', 'Fantasy']\n>>> \n\nIf you'd rather have a tuple then:\n>>> tuple(item for item in s.split('|') if item.strip())\n('Action and Adventure', ... | [
8,
1,
1,
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0003920751_python.txt |
Q:
Subprocess in Python Add Variables
Subprocess in Python Add Variables
import subprocess
subprocess.call('Schtasks /create /sc ONCE /tn Work /tr C:\work.exe /st 15:42 /sd 13/10/2010')
I want to be able to set the variables on the above command. the variables are the time '15:42' separated in 15 and 42 and the date '13/10/2010' separated in day , month and year any ideas??
Thanx in advance
George
A:
Use % formatting to build the command string.
>>> hour,minute = '15','42'
>>> day,month,year = '13','10','2010'
>>> command = 'Schtasks /create /sc ONCE /tn Work /tr C:\work.exe /st %s:%s /sd %s/%s/%s'
>>> command % (hour,minute, day,month,year)
'Schtasks /create /sc ONCE /tn Work /tr C:\\work.exe /st 15:42 /sd 13/10/2010'
>>> subprocess.call( command % (hour,minute, day,month,year) )
>>>
A:
import subprocess
time = "15:42"
date = "13/10/2010"
# you can use these variables anyhow take input from user using raw_iput()
subprocess.call('Schtasks /create /sc ONCE /tn Work /tr C:\work.exe /st '+time+' /sd '+date)
A:
Python has advanced string formatting capabilities, using the format method on strings. For instance:
>>> template = "Hello, {name}. How are you today, {date}?"
>>> name = "World"
>>> date = "the fourteenth of October"
>>> template.format(name=name, date=date)
'Hello, World. How are you today, the fourteenth of October?'
You can get the time and date using strftime in the datetime module:
>>> import datetime
>>> now = datetime.datetime.now()
>>> now.strftime("%A %B %Y, %I:%M:%S")
'Wednesday October 2010, 02:54:30'
A:
import time
subprocess.call(time.strftime("Schtasks /create /sc ONCE /tn Work /tr C:\work.exe /st %H:%M /sd %d/%m/%Y"))
If you would like to change the time you can set it into time object and use it.
| Subprocess in Python Add Variables | Subprocess in Python Add Variables
import subprocess
subprocess.call('Schtasks /create /sc ONCE /tn Work /tr C:\work.exe /st 15:42 /sd 13/10/2010')
I want to be able to set the variables on the above command. the variables are the time '15:42' separated in 15 and 42 and the date '13/10/2010' separated in day , month and year any ideas??
Thanx in advance
George
| [
"Use % formatting to build the command string.\n>>> hour,minute = '15','42'\n>>> day,month,year = '13','10','2010'\n>>> command = 'Schtasks /create /sc ONCE /tn Work /tr C:\\work.exe /st %s:%s /sd %s/%s/%s'\n>>> command % (hour,minute, day,month,year)\n'Schtasks /create /sc ONCE /tn Work /tr C:\\\\work.exe ... | [
1,
0,
0,
0
] | [] | [] | [
"python",
"string"
] | stackoverflow_0003924122_python_string.txt |
Q:
Problem displaying xfbml with pyfacebook
I'm using pyfacebook on my app but I'm having problems displaying xfbml
For example I have to use iframes to display like buttons or like boxes.
What's strange:
1) On the login page the appears correctly, I just have problems on other pages (once logged in)
2) The FB.init part I use is
<script src="http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php/en_US" type="text/javascript"></script>
<script type="text/javascript">FB.init("{{ apikey }}", '/static/xd_receiver.html');
Whereas on the facebook docs the arguments are:
FB.init({
appId : 'YOUR APP ID',
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
3) When I change the FB.init to the official fb one, application doesn't work anymore.
(eg I can't logout using this
<a href="#" onclick="javascript:FB.Connect.logoutAndRedirect('/')">Logout</a>
I'm relatively new to FB stuff, so I'm probably mixing things up, but I just want to display correct fbml on my app without modifying too much the server side.
A:
I think you are confusing Facebook's old javascript API with their new javascript API.
As mentioned on the new API page, use this to do the init:
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({appId: 'your app id', status: true, cookie: true,
xfbml: true});
};
(function() {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol +
'//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
}());
</script>
For the logout, you would want something like this:
<a href="#" onclick="javascript:FB.logout(function(response) {window.location.href = '/';})">Logout</a>
| Problem displaying xfbml with pyfacebook | I'm using pyfacebook on my app but I'm having problems displaying xfbml
For example I have to use iframes to display like buttons or like boxes.
What's strange:
1) On the login page the appears correctly, I just have problems on other pages (once logged in)
2) The FB.init part I use is
<script src="http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php/en_US" type="text/javascript"></script>
<script type="text/javascript">FB.init("{{ apikey }}", '/static/xd_receiver.html');
Whereas on the facebook docs the arguments are:
FB.init({
appId : 'YOUR APP ID',
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
3) When I change the FB.init to the official fb one, application doesn't work anymore.
(eg I can't logout using this
<a href="#" onclick="javascript:FB.Connect.logoutAndRedirect('/')">Logout</a>
I'm relatively new to FB stuff, so I'm probably mixing things up, but I just want to display correct fbml on my app without modifying too much the server side.
| [
"I think you are confusing Facebook's old javascript API with their new javascript API.\nAs mentioned on the new API page, use this to do the init:\n<div id=\"fb-root\"></div>\n<script>\n window.fbAsyncInit = function() {\n FB.init({appId: 'your app id', status: true, cookie: true,\n xfbml: true});\... | [
1
] | [] | [] | [
"facebook",
"google_app_engine",
"javascript",
"pyfacebook",
"python"
] | stackoverflow_0003924414_facebook_google_app_engine_javascript_pyfacebook_python.txt |
Q:
Python Queue - Threads bound to only one core
I wrote a python script that:
1. submits search queries
2. waits for the results
3. parses the returned results(XML)
I used the threading and Queue modules to perform this in parallel (5 workers).
It works great for the querying portion because i can submit multiple search jobs and deal with the results as they come in.
However, it appears that all my threads get bound to the same core. This is apparent when it gets to the part where it processes the XML(cpu intensive).
Has anyone else encountered this problem? Am i missing something conceptually?
Also, i was pondering the idea of having two separate work queues, one for making the queries and one for parsing the XML. As it is now, one worker will do both in serial. I'm not sure what that will buy me, if anything. Any help is greatly appreciated.
Here is the code: (proprietary data removed)
def addWork(source_list):
for item in source_list:
#print "adding: '%s'"%(item)
work_queue.put(item)
def doWork(thread_id):
while 1:
try:
gw = work_queue.get(block=False)
except Queue.Empty:
#print "thread '%d' is terminating..."%(thread_id)
sys.exit() # no more work in the queue for this thread, die quietly
##Here is where i make the call to the REST API
##Here is were i wait for the results
##Here is where i parse the XML results and dump the data into a "global" dict
#MAIN
producer_thread = Thread(target=addWork, args=(sources,))
producer_thread.start() # start the thread (ie call the target/function)
producer_thread.join() # wait for thread/target function to terminate(block)
#start the consumers
for i in range(5):
consumer_thread = Thread(target=doWork, args=(i,))
consumer_thread.start()
thread_list.append(consumer_thread)
for thread in thread_list:
thread.join()
A:
This is a byproduct of how CPython handles threads. There are endless discussions around the internet (search for GIL) but the solution is to use the multiprocessing module instead of threading. Multiprocessing is built with pretty much the same interface (and synchronization structures, so you can still use queues) as threading. It just gives every thread its own entire process, thus avoiding the GIL and forced serialization of parallel workloads.
A:
Using CPython, your threads will never actually run in parallel in two different cores. Look up information on the Global Interpreter Lock (GIL).
Basically, there's a mutual exclusion lock protecting the actual execution part of the interpreter, so no two threads can compute in parallel. Threading for I/O tasks will work just fine, because of blocking.
edit: If you want to fully take advantage of multiple cores, you need to use multiple processes. There's a lot of articles about this topic, I'm trying to look one up for you I remember was great, but can't find it =/.
As Nathon suggested, you can use the multiprocessing module. There are tools to help you share objects between processes (take a look at POSH, Python Object Sharing).
| Python Queue - Threads bound to only one core | I wrote a python script that:
1. submits search queries
2. waits for the results
3. parses the returned results(XML)
I used the threading and Queue modules to perform this in parallel (5 workers).
It works great for the querying portion because i can submit multiple search jobs and deal with the results as they come in.
However, it appears that all my threads get bound to the same core. This is apparent when it gets to the part where it processes the XML(cpu intensive).
Has anyone else encountered this problem? Am i missing something conceptually?
Also, i was pondering the idea of having two separate work queues, one for making the queries and one for parsing the XML. As it is now, one worker will do both in serial. I'm not sure what that will buy me, if anything. Any help is greatly appreciated.
Here is the code: (proprietary data removed)
def addWork(source_list):
for item in source_list:
#print "adding: '%s'"%(item)
work_queue.put(item)
def doWork(thread_id):
while 1:
try:
gw = work_queue.get(block=False)
except Queue.Empty:
#print "thread '%d' is terminating..."%(thread_id)
sys.exit() # no more work in the queue for this thread, die quietly
##Here is where i make the call to the REST API
##Here is were i wait for the results
##Here is where i parse the XML results and dump the data into a "global" dict
#MAIN
producer_thread = Thread(target=addWork, args=(sources,))
producer_thread.start() # start the thread (ie call the target/function)
producer_thread.join() # wait for thread/target function to terminate(block)
#start the consumers
for i in range(5):
consumer_thread = Thread(target=doWork, args=(i,))
consumer_thread.start()
thread_list.append(consumer_thread)
for thread in thread_list:
thread.join()
| [
"This is a byproduct of how CPython handles threads. There are endless discussions around the internet (search for GIL) but the solution is to use the multiprocessing module instead of threading. Multiprocessing is built with pretty much the same interface (and synchronization structures, so you can still use queue... | [
4,
2
] | [] | [] | [
"multithreading",
"python",
"queue"
] | stackoverflow_0003924637_multithreading_python_queue.txt |
Q:
What is the easiest way to search through a list of dicts in Python?
My database currently returns a list of dicts:
id_list = ({'id': '0c871320cf5111df87da000c29196d3d'},
{'id': '2eeeb9f4cf5111df87da000c29196d3d'},
{'id': '3b982384cf5111df87da000c29196d3d'},
{'id': '3f6f3fcecf5111df87da000c29196d3d'},
{'id': '44762370cf5111df87da000c29196d3d'},
{'id': '4ba0d294cf5111df87da000c29196d3d'})
How can I easily check if a given id is in this list or not?
Thanks.
A:
Here's a one-liner:
if some_id in [d.get('id') for d in id_list]:
pass
Not very efficient though.
edit -- A better approach might be:
if some_id in (d.get('id') for d in id_list):
pass
This way, the list isn't generated in full length beforehand.
A:
How can I easily check if a given id is in this list or not?
Make a set
keys = set( d['id'] for d in id_list )
if some_value in keys
Don't ask if this is "efficient" or "best". It involves the standard tradeoff.
Building the set takes time. But the lookup is then instant.
If you do a lot of lookups, the cost of building the set is amortized over each lookup.
If you do few lookups, the cost of building the set may be higher than something ilike
{'id':some_value} in id_list.
A:
if you make a dictionary of your search id,
search_dic = {'id': '0c871320cf5111df87da000c29196d3d'}
id_list = ({'id': '0c871320cf5111df87da000c29196d3d'},
{'id': '2eeeb9f4cf5111df87da000c29196d3d'},
{'id': '3b982384cf5111df87da000c29196d3d'},
{'id': '3f6f3fcecf5111df87da000c29196d3d'},
{'id': '44762370cf5111df87da000c29196d3d'},
{'id': '4ba0d294cf5111df87da000c29196d3d'})
if search_dic in id_list:
print 'yes'
A:
any(x.get('id')==given_id for x in id_list)
. . . returns boolean. Efficiency? See S.Lott's answer
A:
You can flatten it with a list comprehension and use in:
id in [d['id'] for d in id_list]
You can also use generator expressions, which have different performance characteristics (and will use less memory if your list is huge):
id in (d['id'] for d in id_list)
| What is the easiest way to search through a list of dicts in Python? | My database currently returns a list of dicts:
id_list = ({'id': '0c871320cf5111df87da000c29196d3d'},
{'id': '2eeeb9f4cf5111df87da000c29196d3d'},
{'id': '3b982384cf5111df87da000c29196d3d'},
{'id': '3f6f3fcecf5111df87da000c29196d3d'},
{'id': '44762370cf5111df87da000c29196d3d'},
{'id': '4ba0d294cf5111df87da000c29196d3d'})
How can I easily check if a given id is in this list or not?
Thanks.
| [
"Here's a one-liner:\nif some_id in [d.get('id') for d in id_list]:\n pass\n\nNot very efficient though.\nedit -- A better approach might be:\nif some_id in (d.get('id') for d in id_list):\n pass\n\nThis way, the list isn't generated in full length beforehand.\n",
"\nHow can I easily check if a given id is ... | [
7,
7,
5,
3,
2
] | [] | [] | [
"python",
"python_datamodel"
] | stackoverflow_0003924397_python_python_datamodel.txt |
Q:
how to use paramiko to execute remote commands
I wanted to compress a folder on a remote namchine.For that i am using paramiko.
But i don't know how to do that using paramiko.
Any suggestions??
This is my code:
dpath = '/var/mysql/5.1/mysql.zip'
port = 22
host = '10.88.36.7'
transport = paramiko.Transport((host, port))
transport.connect(username=suser, password=spass)
channel = transport.open_channel(kind="session")
channel.exec_command('zip -r /var/db/mysql /var/db/mysql')
transport.close()
whats wrong in this??
A:
After
channel.exec_command(...)
You have to wait the termination of the command with:
while not channel.exit_status_ready()
... wait ... ( you can read the output with channel.recv, or sleep a bit)
Furthermore, you're zip command is weird... don't you want to say
zip -r /var/db/mysql.zip /var/db/mysql
| how to use paramiko to execute remote commands | I wanted to compress a folder on a remote namchine.For that i am using paramiko.
But i don't know how to do that using paramiko.
Any suggestions??
This is my code:
dpath = '/var/mysql/5.1/mysql.zip'
port = 22
host = '10.88.36.7'
transport = paramiko.Transport((host, port))
transport.connect(username=suser, password=spass)
channel = transport.open_channel(kind="session")
channel.exec_command('zip -r /var/db/mysql /var/db/mysql')
transport.close()
whats wrong in this??
| [
"After \nchannel.exec_command(...)\n\nYou have to wait the termination of the command with:\nwhile not channel.exit_status_ready()\n ... wait ... ( you can read the output with channel.recv, or sleep a bit)\n\nFurthermore, you're zip command is weird... don't you want to say\nzip -r /var/db/mysql.zip /var/db/mys... | [
3
] | [] | [] | [
"python"
] | stackoverflow_0003924411_python.txt |
Q:
FormEncode validate: words divided by a comma
How to validate words divided by a comma by FormEncode ?
Something like this:
"foo1, foo2, foo3" -> ["foo1", "foo2", "foo3"]
A:
You'll probably need a custom validator. Here's a quick example:
import formencode
class CommaSepList(formencode.validators.FancyValidator):
def _to_python(self, value, state):
return value.split(",")
def validate_python(self, value, state):
for elem in value:
if elem == "":
raise formencode.Invalid("an element of the list is empty", value, state)
>>> CommaSepList.to_python("1,2,3")
['1', '2', '3']
>>> CommaSepList.to_python("1,,")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib64/python2.5/site-packages/FormEncode-1.2.3dev-py2.5.egg/formencode/api.py", line 416, in to_python
vp(value, state)
File "myValidator.py", line 17, in validate_python
raise formencode.Invalid("an element of the list is empty", value, state)
Of course, you'll want to add validation specific to your use case.
A:
Assuming each word is separated by a comma and a space (', '):
>>> x = "foo1, bar2, foo3"
>>> x.split(', ')
['foo1', 'bar2', 'foo3']
And then pass that list on to FormEncode and have it do whatever you need it to do.
| FormEncode validate: words divided by a comma | How to validate words divided by a comma by FormEncode ?
Something like this:
"foo1, foo2, foo3" -> ["foo1", "foo2", "foo3"]
| [
"You'll probably need a custom validator. Here's a quick example:\nimport formencode\n\nclass CommaSepList(formencode.validators.FancyValidator):\n\n def _to_python(self, value, state):\n return value.split(\",\")\n\n def validate_python(self, value, state):\n for elem in value:\n if... | [
1,
0
] | [] | [] | [
"formencode",
"pylons",
"python"
] | stackoverflow_0003924355_formencode_pylons_python.txt |
Q:
Django and Haystack search issue
I am running Python 2.6, the lastest haystack, django 1.2 beta and I have tried both Woosh and Xapian backends.
The problem is that I cannot do a __lt or __gt filter on an integer field - when such is used,there are always none results found...
My model:
# -*- coding: utf-8 -*-
from django.db import models
from django.utils.translation import ugettext as _
from django.forms import ModelForm
from django.contrib.auth.models import User
# Create your models here.
class District(models.Model):
name = models.CharField(_('STRING_DISTRICT'),max_length=100)
def __unicode__(self):
return u'%s' % self.name
class City(models.Model):
district = models.ForeignKey(District)
name = models.CharField(_('STRING_CITY'),max_length=100)
def __unicode__(self):
return u'%s -> %s' % (self.district.name,self.name)
class Status(models.Model):
name = models.CharField(_('STATUS_NAME'),max_length=50)
def __unicode__(self):
return u'%s' % self.name
class Source(models.Model):
name = models.CharField(_('SOURCE_NAME'),max_length=50)
def __unicode__(self):
return u'%s' % self.name
class SpaceUnit(models.Model):
name = models.CharField(_('SPACE_UNIT_NAME'),max_length=50)
def __unicode__(self):
return u'%s' % self.name
class Currency(models.Model):
name = models.CharField(_('CURRENCY_NAME'),max_length=50)
def __unicode__(self):
return u'%s' % self.name
class EstateType(models.Model):
name = models.CharField(_('ESTATE_TYPE'),max_length=50)
def __unicode__(self):
return u'%s' % self.name
class Client(models.Model):
owner = models.ForeignKey(User)
name = models.CharField(_('STRING_NAME'),max_length=50)
surname = models.CharField(_('STRING_SURNAME'),max_length=50)
code = models.CharField(_('STRING_PID_REG_NR'),max_length=50,blank=True)
status = models.ForeignKey(Status,blank=True)
source = models.ForeignKey(Source,blank=True)
district = models.ForeignKey(District)
city = models.ForeignKey(City)
mobile_phone = models.CharField(_('STRING_MOBILE_PHONE_PERSONAL'),max_length=15,blank=True)
home_phone = models.CharField(_('STRING_HOME_PHONE'),max_length=15,blank=True)
work_phone = models.CharField(_('STRING_WORK_PHONE'),max_length=15,blank=True)
work_mobile_phone = models.CharField(_('STRING_WORK_MOBILE_PHONE'),max_length=15,blank=True)
agreement_nr = models.CharField(_('STRING_AGREEMENT_NR'),max_length=50,blank=True)
email_private = models.CharField(_('STRING_EMAIL_PRIVATE'),max_length=100,blank=True)
estate_type = models.ForeignKey(EstateType)
wants_to_rent = models.BooleanField(_('STRING_WANTS_TO_RENT'),blank=True)
rental_space_from = models.IntegerField(_('STRING_SPACE_FROM'),max_length=5)
rental_space_until = models.IntegerField(_('STRING_SPACE_UNTIL'),max_length=5)
rental_space_units = models.ForeignKey(SpaceUnit,related_name="rental_space_units")
rental_price_from = models.IntegerField(_('STRING_PRICE_FROM'),max_length=5)
rental_price_until = models.IntegerField(_('STRING_PRICE_UNTIL'),max_length=5)
rental_price_units = models.ForeignKey(Currency,related_name="rental_currency_units")
wants_to_buy = models.BooleanField(_('STRING_WANTS_TO_BUY'),blank=True)
buying_space_from = models.IntegerField(_('STRING_SPACE_FROM'),max_length=5)
buying_space_until = models.IntegerField(_('STRING_SPACE_UNTIL'),max_length=5)
buying_space_units = models.ForeignKey(SpaceUnit,related_name="buying_space_units")
buying_price_from = models.IntegerField(_('STRING_PRICE_FROM'),max_length=5)
buying_price_until = models.IntegerField(_('STRING_PRICE_UNTIL'),max_length=5)
buying_price_units = models.ForeignKey(Currency,related_name="buying_currency_units")
def __unicode__(self):
return u'%s %s' % (self.name,self.surname)
class ClientForm(ModelForm):
class Meta:
model = Client
search_indexes.py
from haystack.indexes import *
from haystack import site
from clients.models import Client
class ClientIndex(RealTimeSearchIndex):
text = CharField(document=True, use_template=True)
wants_to_rent = BooleanField(model_attr='wants_to_rent')
rental_space_from = CharField(model_attr='rental_space_from')
rental_space_until = CharField(model_attr='rental_space_until')
rental_price_from = CharField(model_attr='rental_space_from')
rental_price_until = CharField(model_attr='rental_space_until')
wants_to_buy = BooleanField(model_attr='wants_to_buy')
buying_space_from = CharField(model_attr='buying_space_from')
buying_space_until = CharField(model_attr='buying_space_until')
def prepare_rental_space_from(self, obj):
return '%08d' % obj.rental_space_from
def prepare_rental_space_until(self, obj):
return '%08d' % obj.rental_space_until
def prepare_rental_price_from(self, obj):
return '%08d' % obj.rental_price_from
def prepare_rental_price_until(self, obj):
return '%08d' % obj.rental_price_until
site.register(Client, ClientIndex)
and search_form.py
from django import forms
from haystack.forms import SearchForm
from haystack.query import SearchQuerySet
from django.utils.translation import ugettext as _
class ClientSearchForm(SearchForm):
"""start_date = forms.DateField(required=False)
end_date = forms.DateField(required=False)"""
wants_to_rent = forms.BooleanField(required=False)
rental_space_from = forms.IntegerField(label=_('STRING_SPACE_FROM'),required=False)
rental_space_until = forms.IntegerField(label=_('STRING_SPACE_UNTIL'),required=False)
rental_price_from = forms.IntegerField(label=_('STRING_PRICE_FROM'),required=False)
rental_price_until = forms.IntegerField(label=_('STRING_PRICE_UNTIL'),required=False)
wants_to_buy = forms.BooleanField(label=_('STRING_WANTS_TO_BUY'),required=False)
buying_space_from = forms.IntegerField(label=_('STRING_SPACE_FROM'),required=False)
buying_space_until = forms.IntegerField(label=_('STRING_SPACE_UNTIL'),required=False)
buying_price_from = forms.IntegerField(label=_('STRING_PRICE_FROM'),required=False)
buying_price_until = forms.IntegerField(label=_('STRING_PRICE_UNTIL'),required=False)
def search(self):
# First, store the SearchQuerySet received from other processing.
sqs = super(ClientSearchForm, self).search()
# Check to see if a start_date was chosen.
"""
if self.cleaned_data['start_date']:
sqs = sqs.filter(pub_date__gte=self.cleaned_data['start_date'])
# Check to see if an end_date was chosen.
if self.cleaned_data['end_date']:
sqs = sqs.filter(pub_date__lte=self.cleaned_data['end_date'])
"""
if self.cleaned_data['wants_to_rent']:
sqs = sqs.filter(wants_to_rent=True)
if self.cleaned_data['rental_space_from']:
sqs = sqs.filter(rental_space_from__gte=self.cleaned_data['rental_space_from'])
if self.cleaned_data['rental_space_until']:
sqs = sqs.filter(rental_space_until__lt=self.cleaned_data['rental_space_until'])
if self.cleaned_data['rental_price_from']:
sqs = sqs.filter(rental_price_from__gte=self.cleaned_data['rental_price_from'])
if self.cleaned_data['rental_price_until']:
sqs = sqs.filter(rental_price_until__lte=self.cleaned_data['rental_price_until'])
if self.cleaned_data['wants_to_buy']:
sqs = sqs.filter(wants_to_buy=True)
if self.cleaned_data['buying_space_from']:
sqs = sqs.filter(buying_space_from__gt=1)
if self.cleaned_data['buying_space_until']:
sqs = sqs.filter(buying_space_until__lt=6)
if self.cleaned_data['buying_price_from']:
sqs = sqs.filter(buying_price_from__gte=self.cleaned_data['buying_price_from'])
if self.cleaned_data['buying_price_until']:
sqs = sqs.filter(buying_price_until__lte=self.cleaned_data['buying_price_until'])
return sqs
I have tried everything - zero padding the integers, reseting my app a gazillion times and I still cannot get any luck! The fields ignored are buying_place_from/until buying_space_from/until and the same goes for rental fields - NOTHING seems to affect them, if any filter is used - there are 0 results... thank you in advice!
A:
I don't have a real answer, but here's how I would look for it:
Try logging/printing the query you're actually building here (sqs just before the end of the search method). it might give you clues as to what is wrong.
Try running the same kind of query (same set of filters) in the shell. what results do you get?
A:
Why are you using CharField for the ClientIndex when you can use IntegerField there?
Also if you zero-pad the integers saved in the CharField, make sure that you zero-pad the searched value too.
| Django and Haystack search issue | I am running Python 2.6, the lastest haystack, django 1.2 beta and I have tried both Woosh and Xapian backends.
The problem is that I cannot do a __lt or __gt filter on an integer field - when such is used,there are always none results found...
My model:
# -*- coding: utf-8 -*-
from django.db import models
from django.utils.translation import ugettext as _
from django.forms import ModelForm
from django.contrib.auth.models import User
# Create your models here.
class District(models.Model):
name = models.CharField(_('STRING_DISTRICT'),max_length=100)
def __unicode__(self):
return u'%s' % self.name
class City(models.Model):
district = models.ForeignKey(District)
name = models.CharField(_('STRING_CITY'),max_length=100)
def __unicode__(self):
return u'%s -> %s' % (self.district.name,self.name)
class Status(models.Model):
name = models.CharField(_('STATUS_NAME'),max_length=50)
def __unicode__(self):
return u'%s' % self.name
class Source(models.Model):
name = models.CharField(_('SOURCE_NAME'),max_length=50)
def __unicode__(self):
return u'%s' % self.name
class SpaceUnit(models.Model):
name = models.CharField(_('SPACE_UNIT_NAME'),max_length=50)
def __unicode__(self):
return u'%s' % self.name
class Currency(models.Model):
name = models.CharField(_('CURRENCY_NAME'),max_length=50)
def __unicode__(self):
return u'%s' % self.name
class EstateType(models.Model):
name = models.CharField(_('ESTATE_TYPE'),max_length=50)
def __unicode__(self):
return u'%s' % self.name
class Client(models.Model):
owner = models.ForeignKey(User)
name = models.CharField(_('STRING_NAME'),max_length=50)
surname = models.CharField(_('STRING_SURNAME'),max_length=50)
code = models.CharField(_('STRING_PID_REG_NR'),max_length=50,blank=True)
status = models.ForeignKey(Status,blank=True)
source = models.ForeignKey(Source,blank=True)
district = models.ForeignKey(District)
city = models.ForeignKey(City)
mobile_phone = models.CharField(_('STRING_MOBILE_PHONE_PERSONAL'),max_length=15,blank=True)
home_phone = models.CharField(_('STRING_HOME_PHONE'),max_length=15,blank=True)
work_phone = models.CharField(_('STRING_WORK_PHONE'),max_length=15,blank=True)
work_mobile_phone = models.CharField(_('STRING_WORK_MOBILE_PHONE'),max_length=15,blank=True)
agreement_nr = models.CharField(_('STRING_AGREEMENT_NR'),max_length=50,blank=True)
email_private = models.CharField(_('STRING_EMAIL_PRIVATE'),max_length=100,blank=True)
estate_type = models.ForeignKey(EstateType)
wants_to_rent = models.BooleanField(_('STRING_WANTS_TO_RENT'),blank=True)
rental_space_from = models.IntegerField(_('STRING_SPACE_FROM'),max_length=5)
rental_space_until = models.IntegerField(_('STRING_SPACE_UNTIL'),max_length=5)
rental_space_units = models.ForeignKey(SpaceUnit,related_name="rental_space_units")
rental_price_from = models.IntegerField(_('STRING_PRICE_FROM'),max_length=5)
rental_price_until = models.IntegerField(_('STRING_PRICE_UNTIL'),max_length=5)
rental_price_units = models.ForeignKey(Currency,related_name="rental_currency_units")
wants_to_buy = models.BooleanField(_('STRING_WANTS_TO_BUY'),blank=True)
buying_space_from = models.IntegerField(_('STRING_SPACE_FROM'),max_length=5)
buying_space_until = models.IntegerField(_('STRING_SPACE_UNTIL'),max_length=5)
buying_space_units = models.ForeignKey(SpaceUnit,related_name="buying_space_units")
buying_price_from = models.IntegerField(_('STRING_PRICE_FROM'),max_length=5)
buying_price_until = models.IntegerField(_('STRING_PRICE_UNTIL'),max_length=5)
buying_price_units = models.ForeignKey(Currency,related_name="buying_currency_units")
def __unicode__(self):
return u'%s %s' % (self.name,self.surname)
class ClientForm(ModelForm):
class Meta:
model = Client
search_indexes.py
from haystack.indexes import *
from haystack import site
from clients.models import Client
class ClientIndex(RealTimeSearchIndex):
text = CharField(document=True, use_template=True)
wants_to_rent = BooleanField(model_attr='wants_to_rent')
rental_space_from = CharField(model_attr='rental_space_from')
rental_space_until = CharField(model_attr='rental_space_until')
rental_price_from = CharField(model_attr='rental_space_from')
rental_price_until = CharField(model_attr='rental_space_until')
wants_to_buy = BooleanField(model_attr='wants_to_buy')
buying_space_from = CharField(model_attr='buying_space_from')
buying_space_until = CharField(model_attr='buying_space_until')
def prepare_rental_space_from(self, obj):
return '%08d' % obj.rental_space_from
def prepare_rental_space_until(self, obj):
return '%08d' % obj.rental_space_until
def prepare_rental_price_from(self, obj):
return '%08d' % obj.rental_price_from
def prepare_rental_price_until(self, obj):
return '%08d' % obj.rental_price_until
site.register(Client, ClientIndex)
and search_form.py
from django import forms
from haystack.forms import SearchForm
from haystack.query import SearchQuerySet
from django.utils.translation import ugettext as _
class ClientSearchForm(SearchForm):
"""start_date = forms.DateField(required=False)
end_date = forms.DateField(required=False)"""
wants_to_rent = forms.BooleanField(required=False)
rental_space_from = forms.IntegerField(label=_('STRING_SPACE_FROM'),required=False)
rental_space_until = forms.IntegerField(label=_('STRING_SPACE_UNTIL'),required=False)
rental_price_from = forms.IntegerField(label=_('STRING_PRICE_FROM'),required=False)
rental_price_until = forms.IntegerField(label=_('STRING_PRICE_UNTIL'),required=False)
wants_to_buy = forms.BooleanField(label=_('STRING_WANTS_TO_BUY'),required=False)
buying_space_from = forms.IntegerField(label=_('STRING_SPACE_FROM'),required=False)
buying_space_until = forms.IntegerField(label=_('STRING_SPACE_UNTIL'),required=False)
buying_price_from = forms.IntegerField(label=_('STRING_PRICE_FROM'),required=False)
buying_price_until = forms.IntegerField(label=_('STRING_PRICE_UNTIL'),required=False)
def search(self):
# First, store the SearchQuerySet received from other processing.
sqs = super(ClientSearchForm, self).search()
# Check to see if a start_date was chosen.
"""
if self.cleaned_data['start_date']:
sqs = sqs.filter(pub_date__gte=self.cleaned_data['start_date'])
# Check to see if an end_date was chosen.
if self.cleaned_data['end_date']:
sqs = sqs.filter(pub_date__lte=self.cleaned_data['end_date'])
"""
if self.cleaned_data['wants_to_rent']:
sqs = sqs.filter(wants_to_rent=True)
if self.cleaned_data['rental_space_from']:
sqs = sqs.filter(rental_space_from__gte=self.cleaned_data['rental_space_from'])
if self.cleaned_data['rental_space_until']:
sqs = sqs.filter(rental_space_until__lt=self.cleaned_data['rental_space_until'])
if self.cleaned_data['rental_price_from']:
sqs = sqs.filter(rental_price_from__gte=self.cleaned_data['rental_price_from'])
if self.cleaned_data['rental_price_until']:
sqs = sqs.filter(rental_price_until__lte=self.cleaned_data['rental_price_until'])
if self.cleaned_data['wants_to_buy']:
sqs = sqs.filter(wants_to_buy=True)
if self.cleaned_data['buying_space_from']:
sqs = sqs.filter(buying_space_from__gt=1)
if self.cleaned_data['buying_space_until']:
sqs = sqs.filter(buying_space_until__lt=6)
if self.cleaned_data['buying_price_from']:
sqs = sqs.filter(buying_price_from__gte=self.cleaned_data['buying_price_from'])
if self.cleaned_data['buying_price_until']:
sqs = sqs.filter(buying_price_until__lte=self.cleaned_data['buying_price_until'])
return sqs
I have tried everything - zero padding the integers, reseting my app a gazillion times and I still cannot get any luck! The fields ignored are buying_place_from/until buying_space_from/until and the same goes for rental fields - NOTHING seems to affect them, if any filter is used - there are 0 results... thank you in advice!
| [
"I don't have a real answer, but here's how I would look for it:\nTry logging/printing the query you're actually building here (sqs just before the end of the search method). it might give you clues as to what is wrong.\nTry running the same kind of query (same set of filters) in the shell. what results do you get?... | [
0,
0
] | [] | [] | [
"django_haystack",
"python"
] | stackoverflow_0002892466_django_haystack_python.txt |
Q:
Which is the most recommended Python Twitter library for programmatically updating my own Twitter stream?
After Twitter discontinuing the Basic Auth, my program which updates my own Twitter stream (not others' Twitter streams.) has broken. I understand that OAuth is the way to go. I have set up a Twitter App for the same and have acquired the consumer tokens. Now I don't want to implement the OAuth for Twitter all by myself if someone has done it already. I see this library http://code.google.com/p/oauth-python-twitter2/ being recommended by Twitter, but I'm not sure if it is being actively maintained. Could someone please let me know if there is any good library available for interfacing with Twitter?
A:
you might want to try tweepy for that...
A:
I suggest tweepy as well, it's pretty simple, has oAuth/xAuth support, covers all features of Twitter API, actively under development and has a quick documentation to get you started. The author also claims python 3 support but it was discontinued a few months ago.
A:
Looking at the last update in the link provided by you, the lib was last updated on 16th September 2010 which is good I think ;-)
I just posted the above link in another website.
| Which is the most recommended Python Twitter library for programmatically updating my own Twitter stream? | After Twitter discontinuing the Basic Auth, my program which updates my own Twitter stream (not others' Twitter streams.) has broken. I understand that OAuth is the way to go. I have set up a Twitter App for the same and have acquired the consumer tokens. Now I don't want to implement the OAuth for Twitter all by myself if someone has done it already. I see this library http://code.google.com/p/oauth-python-twitter2/ being recommended by Twitter, but I'm not sure if it is being actively maintained. Could someone please let me know if there is any good library available for interfacing with Twitter?
| [
"you might want to try tweepy for that...\n",
"I suggest tweepy as well, it's pretty simple, has oAuth/xAuth support, covers all features of Twitter API, actively under development and has a quick documentation to get you started. The author also claims python 3 support but it was discontinued a few months ago.\n... | [
4,
1,
0
] | [] | [] | [
"oauth",
"python",
"twitter"
] | stackoverflow_0003923292_oauth_python_twitter.txt |
Q:
Changing the encoding of a table with django+south migrations using --auto
Django newbie here
I know that I can change the encoding of a table by writing my own south migration.
My question is, is there a way doing it by changing my model and using
./manage.py schemamigration my_app --auto
?
A:
AFAIK, there is no such thing as charset modification migration, as charset depends on deployment and thus is settings option.
Thus, You must crate the migration manually (so probably without --auto and using raw SQL).
| Changing the encoding of a table with django+south migrations using --auto | Django newbie here
I know that I can change the encoding of a table by writing my own south migration.
My question is, is there a way doing it by changing my model and using
./manage.py schemamigration my_app --auto
?
| [
"AFAIK, there is no such thing as charset modification migration, as charset depends on deployment and thus is settings option.\nThus, You must crate the migration manually (so probably without --auto and using raw SQL). \n"
] | [
1
] | [] | [] | [
"django",
"django_south",
"python"
] | stackoverflow_0003448806_django_django_south_python.txt |
Q:
How to understand this code of flask?
Could anyone explain this line?
g = LocalProxy(lambda: _request_ctx_stack.top.g)
code from flask
from werkzeug import LocalStack, LocalProxy
# context locals
_request_ctx_stack = LocalStack()
current_app = LocalProxy(lambda: _request_ctx_stack.top.app)
request = LocalProxy(lambda: _request_ctx_stack.top.request)
session = LocalProxy(lambda: _request_ctx_stack.top.session)
g = LocalProxy(lambda: _request_ctx_stack.top.g)
code of Local is here: http://pastebin.com/U3e1bEi0
A:
The Werkzeug documentation for LocalStack and LocalProxy might help, as well as some basic understanding of WSGI.
It appears what is going on is that a global (but empty) stack _request_ctx_stack is created. This is available to all threads. Some WSGI-style objects (current_app, request, session, and g) are set to use the top item in the global stack.
At some point, one or more WSGI applications are pushed onto the global stack. Then, when, for example, current_app is used at runtime, the current top application is used. If the stack is never initialized, then top will return None and you'll get an exception like AttributeError: 'NoneType' object has no attribute 'app'.
| How to understand this code of flask? | Could anyone explain this line?
g = LocalProxy(lambda: _request_ctx_stack.top.g)
code from flask
from werkzeug import LocalStack, LocalProxy
# context locals
_request_ctx_stack = LocalStack()
current_app = LocalProxy(lambda: _request_ctx_stack.top.app)
request = LocalProxy(lambda: _request_ctx_stack.top.request)
session = LocalProxy(lambda: _request_ctx_stack.top.session)
g = LocalProxy(lambda: _request_ctx_stack.top.g)
code of Local is here: http://pastebin.com/U3e1bEi0
| [
"The Werkzeug documentation for LocalStack and LocalProxy might help, as well as some basic understanding of WSGI.\nIt appears what is going on is that a global (but empty) stack _request_ctx_stack is created. This is available to all threads. Some WSGI-style objects (current_app, request, session, and g) are set... | [
5
] | [] | [] | [
"flask",
"python",
"werkzeug"
] | stackoverflow_0003800530_flask_python_werkzeug.txt |
Q:
Why it's needed to "source" some Vim plugins?
From autotag.vim:
install details
Simply source the file
autoTag.vim from your .vimrc file.
This utility will (obviously) only
work when using vim that's been
compiled with python support.
Is this needed because this is a Python plugin in vim, instead of a vimscript? Aren't plugins in .vim/plugin loaded automatically?
This plugin only works when I source it. Is this behavior expected because I'm using pathogen?
A:
There is no difference: if you place it in .vim/plugin, you don't need to source it from somewhere else.
Addendum
As Randy Morris explains in the comments, with pathogen.vim's magic, the equivalent plugin path to put the script in would actually be .vim/bundle/autotag/plugin.
| Why it's needed to "source" some Vim plugins? | From autotag.vim:
install details
Simply source the file
autoTag.vim from your .vimrc file.
This utility will (obviously) only
work when using vim that's been
compiled with python support.
Is this needed because this is a Python plugin in vim, instead of a vimscript? Aren't plugins in .vim/plugin loaded automatically?
This plugin only works when I source it. Is this behavior expected because I'm using pathogen?
| [
"There is no difference: if you place it in .vim/plugin, you don't need to source it from somewhere else.\nAddendum\nAs Randy Morris explains in the comments, with pathogen.vim's magic, the equivalent plugin path to put the script in would actually be .vim/bundle/autotag/plugin.\n"
] | [
1
] | [] | [] | [
"ctags",
"plugins",
"python",
"tags",
"vim"
] | stackoverflow_0003925562_ctags_plugins_python_tags_vim.txt |
Q:
Compare strings with newlines in them?
I'm trying to develop a script which compares a runtime generated string against one which is input by the user. Unfortunately, since user inputs his code using a textbox, I get ^M in the string input by user.
Example, If I print these strings to file I get this:
User Input:
1^M
2^M
3
Output of script:
1
2
3
Obviously, when I try to compare these two strings, I get a false. What would be the most efficient way to sort this problem? Just in case you haven't noticed, all lines entered by user "donot" end with "^M". The last line in this user string has no ^M, while output of code has a "\n" at the end.
A:
You should use str.splitlines() to split the text coming from the textbox, instead of whatever it is you're using now. That method handles \r\n properly.
A:
mystring.rstrip('\r') will return a new string with any ^M removed from the end of the string.
| Compare strings with newlines in them? | I'm trying to develop a script which compares a runtime generated string against one which is input by the user. Unfortunately, since user inputs his code using a textbox, I get ^M in the string input by user.
Example, If I print these strings to file I get this:
User Input:
1^M
2^M
3
Output of script:
1
2
3
Obviously, when I try to compare these two strings, I get a false. What would be the most efficient way to sort this problem? Just in case you haven't noticed, all lines entered by user "donot" end with "^M". The last line in this user string has no ^M, while output of code has a "\n" at the end.
| [
"You should use str.splitlines() to split the text coming from the textbox, instead of whatever it is you're using now. That method handles \\r\\n properly.\n",
"mystring.rstrip('\\r') will return a new string with any ^M removed from the end of the string.\n"
] | [
10,
1
] | [] | [] | [
"python",
"string"
] | stackoverflow_0003925641_python_string.txt |
Q:
Markdown with custom syntax?
I'm using python and using markdown. Is there a simple way to add a custom syntax? I want something like [ABC] expands to a certain tag or something.
or do I use regex?
A:
It appears that you can write extensions for Python-Markdown, which is probably the best approach.
If you are using some other Markdown implementation (or, you know, just for the heck of it) you could pre-process the text to implement your own tags (converting them to HTML) before handing it off to Markdown. This could be done using a regex or by any method you like. Within reasonable limits, Markdown should leave your HTML alone.
| Markdown with custom syntax? | I'm using python and using markdown. Is there a simple way to add a custom syntax? I want something like [ABC] expands to a certain tag or something.
or do I use regex?
| [
"It appears that you can write extensions for Python-Markdown, which is probably the best approach.\nIf you are using some other Markdown implementation (or, you know, just for the heck of it) you could pre-process the text to implement your own tags (converting them to HTML) before handing it off to Markdown. This... | [
4
] | [] | [] | [
"markdown",
"python"
] | stackoverflow_0003925867_markdown_python.txt |
Q:
OSX Port Python Library Path? Cant find ctypes
I am trying to use an application that has a dependency of ctypes, but am getting this error:
$ python peach.py -t ~/Desktop/fuzz/wav/template.xml
] Peach 2.3.6 Runtime
] Copyright (c) Michael Eddington
Traceback (most recent call last):
File "peach.py", line 335, in <module>
from Peach.Engine import *
File "/opt/Peach-2.3.6/Peach/__init__.py", line 40, in <module>
import Publishers, Transformers
File "/opt/Peach-2.3.6/Peach/Publishers/__init__.py", line 37, in <module>
import file, sql, stdout, tcp, udp, com, process, http, icmp, raw, remote, dll, smtp
File "/opt/Peach-2.3.6/Peach/Publishers/file.py", line 37, in <module>
from Peach.Engine.engine import Engine
File "/opt/Peach-2.3.6/Peach/Engine/engine.py", line 835, in <module>
from Peach.Engine.state import StateEngine
File "/opt/Peach-2.3.6/Peach/Engine/state.py", line 38, in <module>
import sys, re, types, time, struct, ctypes
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/ctypes/__init__.py", line 10, in <module>
from _ctypes import Union, Structure, Array
ImportError: No module named _ctypes
I have installed py-ctypes from ports, but it seems to only be a Python 2.4 version:
$ port contents py-ctypes
Port py-ctypes contains:
/opt/local/lib/python2.4/site-packages/_ctypes.so
/opt/local/lib/python2.4/site-packages/_ctypes_test.so
/opt/local/lib/python2.4/site-packages/ctypes/__init__.py
/opt/local/lib/python2.4/site-packages/ctypes/__init__.pyc
/opt/local/lib/python2.4/site-packages/ctypes/_endian.py
/opt/local/lib/python2.4/site-packages/ctypes/_endian.pyc
/opt/local/lib/python2.4/site-packages/ctypes/macholib/__init__.py
/opt/local/lib/python2.4/site-packages/ctypes/macholib/__init__.pyc
/opt/local/lib/python2.4/site-packages/ctypes/macholib/dyld.py
/opt/local/lib/python2.4/site-packages/ctypes/macholib/dyld.pyc
/opt/local/lib/python2.4/site-packages/ctypes/macholib/dylib.py
/opt/local/lib/python2.4/site-packages/ctypes/macholib/dylib.pyc
I then tried to run the application via python2.4, but it seems the application uses syntax that is only available in 2.5:
$ python2.4 peach.py -t ~/Desktop/fuzz/wav/template.xml
File "peach.py", line 498
finally:
^
SyntaxError: invalid syntax
My python install is also from OSX ports, and I noticed in the Peach application, it defines python as:
#!/usr/bin/python
Will that mess with anything if my default python executable points to my port installation (and I am running 'python peach.py')?
$ which python
/opt/local/bin/python
Is there any work around for this?
ctypes for python2.5?
Ability to add 2.4 libraries to 2.5 path?
A:
A simple solution would be to use the native Python build that is included with Mac OS. This definitely works with the latest release of Mac OS X 10.6.4, which has Python 2.6.
Here is an example showing that '_ctypes' is being imported successfully:
mariah:~ joet3ch$ /usr/bin/python
Python 2.6.1 (r261:67515, Feb 11 2010, 00:51:29)
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from _ctypes import Union, Structure, Array
>>>
If you have issues after this, try looking at the sys.path attribute to see which modules and versions are in your path.
Here is an example of viewing the contents of sys.path on a fresh Mac OS 10.6.4 build:
mariah:~ joet3ch$ /usr/bin/python
Python 2.6.1 (r261:67515, Feb 11 2010, 00:51:29)
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.path
['', '/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python26.zip', '/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6', '/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/plat-darwin', '/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/plat-mac', '/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/plat-mac/lib-scriptpackages', '/System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python', '/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-tk', '/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-old', '/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-dynload', '/Library/Python/2.6/site-packages', '/System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/PyObjC', '/System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/wx-2.8-mac-unicode']
>>>
A:
ctypes is a standard Python library since version 2.5, so py-ctypes is not needed. The line at which you get an ImportError still exists in my 2.6.5 installation.
I do not own OSX, so my question is: does /opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5 belong to the standard installation of Python 2.5, or may this belong to a possibly broken installation of some framework?
In a running python shell, you could inspect the value of sys.path. Maybe there is some broken library that precedes the standard library.
The shebang line #!/usr/bin/python is interpreted by the OS if it is the first line of an executable script that is invoked directly like an ordinary program. In all other cases, this is just a comment. In particular, the line is ignored if you invoke the script as in python myscript.py or if it is imported by other Python code.
| OSX Port Python Library Path? Cant find ctypes | I am trying to use an application that has a dependency of ctypes, but am getting this error:
$ python peach.py -t ~/Desktop/fuzz/wav/template.xml
] Peach 2.3.6 Runtime
] Copyright (c) Michael Eddington
Traceback (most recent call last):
File "peach.py", line 335, in <module>
from Peach.Engine import *
File "/opt/Peach-2.3.6/Peach/__init__.py", line 40, in <module>
import Publishers, Transformers
File "/opt/Peach-2.3.6/Peach/Publishers/__init__.py", line 37, in <module>
import file, sql, stdout, tcp, udp, com, process, http, icmp, raw, remote, dll, smtp
File "/opt/Peach-2.3.6/Peach/Publishers/file.py", line 37, in <module>
from Peach.Engine.engine import Engine
File "/opt/Peach-2.3.6/Peach/Engine/engine.py", line 835, in <module>
from Peach.Engine.state import StateEngine
File "/opt/Peach-2.3.6/Peach/Engine/state.py", line 38, in <module>
import sys, re, types, time, struct, ctypes
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/ctypes/__init__.py", line 10, in <module>
from _ctypes import Union, Structure, Array
ImportError: No module named _ctypes
I have installed py-ctypes from ports, but it seems to only be a Python 2.4 version:
$ port contents py-ctypes
Port py-ctypes contains:
/opt/local/lib/python2.4/site-packages/_ctypes.so
/opt/local/lib/python2.4/site-packages/_ctypes_test.so
/opt/local/lib/python2.4/site-packages/ctypes/__init__.py
/opt/local/lib/python2.4/site-packages/ctypes/__init__.pyc
/opt/local/lib/python2.4/site-packages/ctypes/_endian.py
/opt/local/lib/python2.4/site-packages/ctypes/_endian.pyc
/opt/local/lib/python2.4/site-packages/ctypes/macholib/__init__.py
/opt/local/lib/python2.4/site-packages/ctypes/macholib/__init__.pyc
/opt/local/lib/python2.4/site-packages/ctypes/macholib/dyld.py
/opt/local/lib/python2.4/site-packages/ctypes/macholib/dyld.pyc
/opt/local/lib/python2.4/site-packages/ctypes/macholib/dylib.py
/opt/local/lib/python2.4/site-packages/ctypes/macholib/dylib.pyc
I then tried to run the application via python2.4, but it seems the application uses syntax that is only available in 2.5:
$ python2.4 peach.py -t ~/Desktop/fuzz/wav/template.xml
File "peach.py", line 498
finally:
^
SyntaxError: invalid syntax
My python install is also from OSX ports, and I noticed in the Peach application, it defines python as:
#!/usr/bin/python
Will that mess with anything if my default python executable points to my port installation (and I am running 'python peach.py')?
$ which python
/opt/local/bin/python
Is there any work around for this?
ctypes for python2.5?
Ability to add 2.4 libraries to 2.5 path?
| [
"A simple solution would be to use the native Python build that is included with Mac OS. This definitely works with the latest release of Mac OS X 10.6.4, which has Python 2.6.\nHere is an example showing that '_ctypes' is being imported successfully:\nmariah:~ joet3ch$ /usr/bin/python\nPython 2.6.1 (r261:67515, F... | [
2,
1
] | [] | [] | [
"macos",
"path",
"python"
] | stackoverflow_0003917391_macos_path_python.txt |
Q:
How to keep a python window on top of all others (python 3.1)
I'm writing a little program that basically has a bunch of buttons that when you click one, it inputs a certain line of text into an online game I play. It would be a lot easier to use if the GUI would stay on top of the active game window so the user could be playing and then press a button on the panel without having to bring it to the front first.
Any help on how to do this would be great. Thanks
EDIT: Using tkinter
A:
You will need to provide the information on which GUI framework you are using for detailed answer at SO.
On windows you could do something like this with the handle of your window.
import win32gui
import win32con
win32gui.SetWindowPos(hWnd, win32con.HWND_TOPMOST, 0,0,0,0,
win32con.SWP_NOMOVE | win32con.SWP_NOSIZE)
Also with Tkinter, you might want to try. I have not tried it though.
root = Tk()
root.wm_attributes("-topmost", 1)
| How to keep a python window on top of all others (python 3.1) | I'm writing a little program that basically has a bunch of buttons that when you click one, it inputs a certain line of text into an online game I play. It would be a lot easier to use if the GUI would stay on top of the active game window so the user could be playing and then press a button on the panel without having to bring it to the front first.
Any help on how to do this would be great. Thanks
EDIT: Using tkinter
| [
"You will need to provide the information on which GUI framework you are using for detailed answer at SO.\nOn windows you could do something like this with the handle of your window.\nimport win32gui\nimport win32con\nwin32gui.SetWindowPos(hWnd, win32con.HWND_TOPMOST, 0,0,0,0,\nwin32con.SWP_NOMOVE | win32con.SWP_NO... | [
14
] | [] | [] | [
"button",
"python"
] | stackoverflow_0003926655_button_python.txt |
Q:
Can You Embed an TCL Script in Bash Script or Python Script That's Callable by External Programs?
I'm writing a script to extract some useful data about a series of chemical simulations I've been running.
To get this data I need (1) a C-program that calculates the density from a file type called *.pdb. I already have (1). And (2) I need to use a program called vmd to get that pdb. In order to accomplish (2) from the command line, I can submit a tcl script, as vmd has a build in tcl interpreter.
These functions -- calling the vmd to run the tcl script, then running the compiled c-program -- will be the key activities of my wrapper data extraction script.
I would like to eliminate the superfluous TCL script, reducing my count from 2 scripts (wrapper script + tcl script for vmd) down to 1. But I'm not sure quite how to do this. One potentially solution seems to be to embed my TCL script within my wrapper script, if there's a way to make such an embedded script callable from external programs.
Most of my data collection scripts so far have been in BASH, so ideally I would like to stick to a BASH script as I'm very familiar with bash scripting versus having only beginning knowledge of Python/Perl.
Here are my questions:
1. Can you embed a TCL script inside a Bash script?
2. Can you make this script callable by an external program?
e.g. in pseudocode:
#!/bin/bash
....
tclembed extract {
#tcl script
...
}
...
vmd -dispdev text -e extract.tcl >& extract_results.log #where vmd is
#an external program
3. If the answer to #2 is no, can you do this in Python, perhaps with the Minotaur library? I would consider the switch to python, if so...
http://markmail.org/message/6kogjphzqtn4ilch
4. If not, how would you suggest trying to merge these two scripts (a tcl routine and a bash script that calls it) into a single file?
5. If anybody HAS gotten external calls of this nature to work using Minotaur, can you post some explanatory code?
I've thought of one non-embedding solution which to #4, which would be to write a function in my Bash script that writes a file with the entire tcl script. That way I would have a single script, but could dump the subscript for use with external programs, later deleting it. I have a feeling this solution is kinda kludgy though I know for sure that it works, vs. embedded solutions.
A:
There have been several Tcl-Python alloys. As Rafe Kettler's comment above sketches, the place to start is with a standard Python installation. This includes Tkinter, which builds in a full Tcl interpreter, accessible as described in the Wiki page mentioned. So, yes, it is feasible to "do this in Python".
I really don't get what this has to do with vmd, though. vmd builds in a Tcl interpreter already. While I entirely support the aim of "reduction of moving parts", so that you have, for example, one script, rather than two, coding something in Python, when vmd already exposes Tcl, doesn't seem like a step in the direction Jason R. Mick wants to go.
SOMEWHAT LATER: after an exchange of comments with Jason R. Mick, it occurred to me he might find
#!/bin/bash
echo "Here's a bit of bash-iness."
MYSCRIPT='
puts "Here I am, inside Tcl."
puts "See? I can do calculations: [expr 3 + 5]."
exit 0
'
tclsh << HERE
$MYSCRIPT
HERE
suggestive. Its output, of course, is
Here's a bit of bash-iness.
Here I am, inside Tcl.
See? I can do calculations: 8.
I wrote this in terms of tclsh, but, if I'm keeping up, Jason R. Mick will actually want to use vmd. The appropriate homologue for *vmd is something like
...
vmd -dispdev text -eofexit << HERE > output.log
$MYSCRIPT
HERE
While I can think of several other ways to meld bash and Tcl, I believe this one is most in the spirit of the original question.
I want to note, too, that, from the little I know of vmd, it would be entirely appropriate to do the same with Python in place of Tcl: vmd is equally adept with either.
Finally, both Python and Tcl are general-purpose languages, with approximately the same power as bash, so yet another direction to take this project would be to write it entirely in Tcl (or Python), rather than bash. Embedding scripts in the way illustrated above is at least as easy in Tcl (or Python) as in bash.
A:
1. Can you embed a TCL script inside a Bash script?
Not easily. The best way is to write the script to a temporary file and pass the name of that file to tclsh (or wish if it is a Tcl/Tk program). That should be a "simple matter of programming", i.e., some awkward coding but not fundamentally hard.
2. Can you make this script callable by an external program?
I don't quite understand what you want to do here. You can put a #! line at the start of a Tcl script and mark the file executable. That works well. The best way of all to do that is this:
#!/usr/bin/env tclsh8.5
your tcl script here...
3. If the answer to #2 is no, can you do this in Python?
This wiki page mentions something called Typcl, which is reported to allow doing Tcl from inside Python. I have never tried it.
(I think questions 4 and 5 are largely irrelevant based on my answers above.)
| Can You Embed an TCL Script in Bash Script or Python Script That's Callable by External Programs? | I'm writing a script to extract some useful data about a series of chemical simulations I've been running.
To get this data I need (1) a C-program that calculates the density from a file type called *.pdb. I already have (1). And (2) I need to use a program called vmd to get that pdb. In order to accomplish (2) from the command line, I can submit a tcl script, as vmd has a build in tcl interpreter.
These functions -- calling the vmd to run the tcl script, then running the compiled c-program -- will be the key activities of my wrapper data extraction script.
I would like to eliminate the superfluous TCL script, reducing my count from 2 scripts (wrapper script + tcl script for vmd) down to 1. But I'm not sure quite how to do this. One potentially solution seems to be to embed my TCL script within my wrapper script, if there's a way to make such an embedded script callable from external programs.
Most of my data collection scripts so far have been in BASH, so ideally I would like to stick to a BASH script as I'm very familiar with bash scripting versus having only beginning knowledge of Python/Perl.
Here are my questions:
1. Can you embed a TCL script inside a Bash script?
2. Can you make this script callable by an external program?
e.g. in pseudocode:
#!/bin/bash
....
tclembed extract {
#tcl script
...
}
...
vmd -dispdev text -e extract.tcl >& extract_results.log #where vmd is
#an external program
3. If the answer to #2 is no, can you do this in Python, perhaps with the Minotaur library? I would consider the switch to python, if so...
http://markmail.org/message/6kogjphzqtn4ilch
4. If not, how would you suggest trying to merge these two scripts (a tcl routine and a bash script that calls it) into a single file?
5. If anybody HAS gotten external calls of this nature to work using Minotaur, can you post some explanatory code?
I've thought of one non-embedding solution which to #4, which would be to write a function in my Bash script that writes a file with the entire tcl script. That way I would have a single script, but could dump the subscript for use with external programs, later deleting it. I have a feeling this solution is kinda kludgy though I know for sure that it works, vs. embedded solutions.
| [
"There have been several Tcl-Python alloys. As Rafe Kettler's comment above sketches, the place to start is with a standard Python installation. This includes Tkinter, which builds in a full Tcl interpreter, accessible as described in the Wiki page mentioned. So, yes, it is feasible to \"do this in Python\".\nI ... | [
5,
1
] | [] | [] | [
"bash",
"embedding",
"python",
"scripting",
"tcl"
] | stackoverflow_0003926273_bash_embedding_python_scripting_tcl.txt |
Q:
compatibility between CPython and IronPython cPickle
I was wondering whether objects serialized using CPython's cPickle are readable by using IronPython's cPickle; the objects in question do not require any modules outside of the built-ins that both Cpython and IronPython include. Thank you!
A:
If you use the default protocol (0) which is text based, then things should work. I'm not sure what will happen if you use a higher protocol. It's very easy to test this ...
A:
It will work because when you unpickle objects during load() it will use the current definitions of whatever classes you have defined now, not back when the objects were pickled.
IronPython is simply Python with the standard library implemented in C# so that everything emits IL. Both the CPython and the IronPython pickle modules have the same functionality, except one is implemented in C and the other in C#.
| compatibility between CPython and IronPython cPickle | I was wondering whether objects serialized using CPython's cPickle are readable by using IronPython's cPickle; the objects in question do not require any modules outside of the built-ins that both Cpython and IronPython include. Thank you!
| [
"If you use the default protocol (0) which is text based, then things should work. I'm not sure what will happen if you use a higher protocol. It's very easy to test this ...\n",
"It will work because when you unpickle objects during load() it will use the current definitions of whatever classes you have defined ... | [
2,
0
] | [] | [] | [
"ironpython",
"pickle",
"python"
] | stackoverflow_0003882750_ironpython_pickle_python.txt |
Q:
print a string in an external application (python 3.1)
Suppose I have a game and a python script running. In this game, to speak you just type whatever you want and hit enter. This python script has a button on it that I want to output a predefined string into the game, and hit enter automatically (essentially, the button causes the character to speak the string). What would be the easiest way to implement this?
(just the actual 'send string to game and hit enter' thing, not the buttons and stuff)
A:
Assuming your game is not running in the console (in that case you could use stdin), sendkeys might be an option on Windows. It allows you to send keystrokes to a certain window - in this case, the game window.
If the game is scriptable, you should of course use the game's own scripting options if available.
A:
It depends on what hooks the game provides. If it doesn't provide any hooks, you may want to look into whatever your windowing system uses for automation. I've only done this sort of thing in Linux where I could use X's XTest extension (xte).
| print a string in an external application (python 3.1) | Suppose I have a game and a python script running. In this game, to speak you just type whatever you want and hit enter. This python script has a button on it that I want to output a predefined string into the game, and hit enter automatically (essentially, the button causes the character to speak the string). What would be the easiest way to implement this?
(just the actual 'send string to game and hit enter' thing, not the buttons and stuff)
| [
"Assuming your game is not running in the console (in that case you could use stdin), sendkeys might be an option on Windows. It allows you to send keystrokes to a certain window - in this case, the game window.\nIf the game is scriptable, you should of course use the game's own scripting options if available.\n",
... | [
1,
0
] | [] | [] | [
"python",
"string"
] | stackoverflow_0003927368_python_string.txt |
Q:
Capturing Console output that is not written to stdout,stderr?
I have an windows application called pregeocode (we lack source), this program basically writes geocoding to an input file. This program doesn't actually write anything to console unless there is an error. This program is generally called from a small Python program (it handles the arguments etc, and does all the fun preprocessing).
We check if it fails by seeing if the output file was actually created (it always returns 0, no matter what). However when it fails subprocess shows that nothing was printed to stderr or stdout. (It processes around a hundred or so successfully, with ussally only a single one being bad, but i would love to be able to see what causes the error)
The small python script calls the application via subprocess.Popen:
argslist = [r'C:\workspace\apps\pregeocode.exe', '-in', inputfilename, '-out', outputfilename, '-gcp', gcp_file]
p = subprocess.Popen(argslist, stderr=subprocess.PIPE, stdout=subprocess.PIPE)
print str(p.communicate())
Gives the output of:
('', '')
However if i run the program manually using the same arguments via cmd, i get the output of:
45 IMAGE_EXTENT_TOO_SMALL
(There is around 60 odd different error messages, 45 indicates the error number)
Using the shell=True argument does not change anything, nor can i find anything online about this problem. The actual exe is something that was made in house a long time ago, and we lack the source code for it so i can't see how it prints out the messages.
So why can't subprocess actually capture the stdout or stderr of this?
EDIT
os.system(" ".join(argslist))
properly prints the error message:
45 IMAGE_EXTENT_TOO_SMALL
EDIT 2
Turns out the application uses ERDAS's toolkit. Their toolkit redirects all stdout/stderr into their logging subsystem. The logging subsystem then rewrites it via "CON".
A:
Since the error message really isn't coming in on either stdout nor stderr, my best guess is that the program is using Windows' equivalent of opening /dev/tty, whatever that is. In Unix you could intercept that with careful use of pty.openpty but, as far as I know, there is no support for similar Windows-specific tricks in Python. You might try Expect for Windows instead.
A:
Are you using python 2.5 or the early version of 2.6 ?
Can you try this subprocess.check_output with stderr redirecting to stdout:
out_err = subprocess.check_output(argslist, stderr=subprocess.STDOUT)
If out_err gets both the output and error, you'll probably need to redirect stdout and stderr to file objects and later read from those file objects (because windows do not have unix-like pipes):
fout = open('fout', 'w')
ferr = open('ferr', 'w')
p = subprocess.Popen(argslist, stdout=fout, stderr=ferr)
p.wait()
fout.close()
ferr.close()
| Capturing Console output that is not written to stdout,stderr? | I have an windows application called pregeocode (we lack source), this program basically writes geocoding to an input file. This program doesn't actually write anything to console unless there is an error. This program is generally called from a small Python program (it handles the arguments etc, and does all the fun preprocessing).
We check if it fails by seeing if the output file was actually created (it always returns 0, no matter what). However when it fails subprocess shows that nothing was printed to stderr or stdout. (It processes around a hundred or so successfully, with ussally only a single one being bad, but i would love to be able to see what causes the error)
The small python script calls the application via subprocess.Popen:
argslist = [r'C:\workspace\apps\pregeocode.exe', '-in', inputfilename, '-out', outputfilename, '-gcp', gcp_file]
p = subprocess.Popen(argslist, stderr=subprocess.PIPE, stdout=subprocess.PIPE)
print str(p.communicate())
Gives the output of:
('', '')
However if i run the program manually using the same arguments via cmd, i get the output of:
45 IMAGE_EXTENT_TOO_SMALL
(There is around 60 odd different error messages, 45 indicates the error number)
Using the shell=True argument does not change anything, nor can i find anything online about this problem. The actual exe is something that was made in house a long time ago, and we lack the source code for it so i can't see how it prints out the messages.
So why can't subprocess actually capture the stdout or stderr of this?
EDIT
os.system(" ".join(argslist))
properly prints the error message:
45 IMAGE_EXTENT_TOO_SMALL
EDIT 2
Turns out the application uses ERDAS's toolkit. Their toolkit redirects all stdout/stderr into their logging subsystem. The logging subsystem then rewrites it via "CON".
| [
"Since the error message really isn't coming in on either stdout nor stderr, my best guess is that the program is using Windows' equivalent of opening /dev/tty, whatever that is. In Unix you could intercept that with careful use of pty.openpty but, as far as I know, there is no support for similar Windows-specific... | [
5,
0
] | [] | [] | [
"python",
"subprocess"
] | stackoverflow_0003926952_python_subprocess.txt |
Q:
How do you get the exact path to "My Documents"?
In C++ it's not too hard to get the full pathname to the folder that the shell calls "My Documents" in Windows XP and Windows 7 and "Documents" in Vista; see Get path to My Documents
Is there a simple way to do this in Python?
A:
You could use the ctypes module to get the "My Documents" directory:
import ctypes
from ctypes.wintypes import MAX_PATH
dll = ctypes.windll.shell32
buf = ctypes.create_unicode_buffer(MAX_PATH + 1)
if dll.SHGetSpecialFolderPathW(None, buf, 0x0005, False):
print(buf.value)
else:
print("Failure!")
Source: http://bugs.python.org/issue1763#msg62242
| How do you get the exact path to "My Documents"? | In C++ it's not too hard to get the full pathname to the folder that the shell calls "My Documents" in Windows XP and Windows 7 and "Documents" in Vista; see Get path to My Documents
Is there a simple way to do this in Python?
| [
"You could use the ctypes module to get the \"My Documents\" directory:\nimport ctypes\nfrom ctypes.wintypes import MAX_PATH\n\ndll = ctypes.windll.shell32\nbuf = ctypes.create_unicode_buffer(MAX_PATH + 1)\nif dll.SHGetSpecialFolderPathW(None, buf, 0x0005, False):\n print(buf.value)\nelse:\n print(\"Failure!\... | [
15
] | [] | [] | [
"python",
"windows"
] | stackoverflow_0003927259_python_windows.txt |
Q:
Add unit to yaxis labels in MatPlotLib
I am trying to add mi or km (miles, kilometers) after the value on the yaxis of a matplotlib bar chart.
Right now I am just supplying matplotlib the values and it is making the yaxis labels automatically. I can't figure out how to append mi to the end of a value.
24 > 24 mi
There is an option for ax.set_7ticklabels(), but then I would need to set them statically.
A:
Are you wanting something like this?
import matplotlib.pyplot as plt
from matplotlib.ticker import FormatStrFormatter
x = range(10)
plt.plot(x)
plt.gca().xaxis.set_major_formatter(FormatStrFormatter('%d km'))
plt.show()
| Add unit to yaxis labels in MatPlotLib | I am trying to add mi or km (miles, kilometers) after the value on the yaxis of a matplotlib bar chart.
Right now I am just supplying matplotlib the values and it is making the yaxis labels automatically. I can't figure out how to append mi to the end of a value.
24 > 24 mi
There is an option for ax.set_7ticklabels(), but then I would need to set them statically.
| [
"Are you wanting something like this?\nimport matplotlib.pyplot as plt\nfrom matplotlib.ticker import FormatStrFormatter\n\nx = range(10)\nplt.plot(x)\n\nplt.gca().xaxis.set_major_formatter(FormatStrFormatter('%d km'))\n\nplt.show()\n\n\n"
] | [
23
] | [] | [] | [
"charts",
"django",
"graph",
"matplotlib",
"python"
] | stackoverflow_0003927389_charts_django_graph_matplotlib_python.txt |
Q:
Need help with comparing two pictures in Python
Hey guys, Im working on an assignment for my comp sci class, I dont know where Im going wrong here. The function is supposed to take two pictures, pic1 and pic2, and return how different they are.
Heres what I have
def smart_difference(pic1, pic2):
'''Given two Pictures, pic1 and pic2 of any size and colour, return the
difference'''
red = red_average(pic2)
blue = blue_average(pic2)
green = green_average(pic2)
pic1_height, pic1_width = media.get_height(pic1), media.get_width(pic1)
pic2_height, pic2_width = media.get_height(pic2), media.get_width(pic2)
if (pic1_height > pic2_height) and (pic1_width > pic2_width):
new_pic1 = media.create_picture(pic2_width, pic2_height)
new_pic2 = pic2
elif (pic1_height > pic2_height) and (pic2_width > pic1_width):
new_pic1 = media.create_picture(pic2_width, pic1_height)
new_pic2 = media.create_picture(pic2_width, pic1_height)
elif (pic2_height > pic1_height) and (pic2_width > pic1_width):
new_pic1 = pic1
new_pic2 = media.create_picture(pic1_width, pic1_height)
elif (pic2_height > pic1_height) and (pic1_width > pic2_width):
new_pic1 = media.create_picture(pic2_width, pic1_height)
new_pic2 = media.create_picture(pic2_width, pic1_height)
scale_red(new_pic1, red)
scale_blue(new_pic1, blue)
scale_green(new_pic1, green)
scale_red(new_pic2, red)
scale_blue(new_pic2, blue)
scale_green(new_pic2, green)
return simple_difference(new_pic1, new_pic2)
I run a self_test file (which was given to us for our assignment), but I keep getting an error here, can anyone help?
*Notes:Simple_difference is another function I wrote beforehand that finds the distance between pixels in the two pictures and scales accordingly
A:
Kay, the error is: "AssertError: result after smart_difference should be between 0 and 1200, not 35000"
Heres what I did for simple difference:
def simple_difference(pic1, pic2):
'''Given two Pictures of the same dimensions, pic1 and pic2, return the
sum of the distances in color of the two pictures.'''
sum_distance = 0
for pix1, pix2 in zip(pic1, pic2):
sum_distance += distance(pix1, pix2)
return sum_distance
Im using a media library that we have to use for our class, running python 2.5... which is kind of ridiculous, but that's what we have to use
| Need help with comparing two pictures in Python | Hey guys, Im working on an assignment for my comp sci class, I dont know where Im going wrong here. The function is supposed to take two pictures, pic1 and pic2, and return how different they are.
Heres what I have
def smart_difference(pic1, pic2):
'''Given two Pictures, pic1 and pic2 of any size and colour, return the
difference'''
red = red_average(pic2)
blue = blue_average(pic2)
green = green_average(pic2)
pic1_height, pic1_width = media.get_height(pic1), media.get_width(pic1)
pic2_height, pic2_width = media.get_height(pic2), media.get_width(pic2)
if (pic1_height > pic2_height) and (pic1_width > pic2_width):
new_pic1 = media.create_picture(pic2_width, pic2_height)
new_pic2 = pic2
elif (pic1_height > pic2_height) and (pic2_width > pic1_width):
new_pic1 = media.create_picture(pic2_width, pic1_height)
new_pic2 = media.create_picture(pic2_width, pic1_height)
elif (pic2_height > pic1_height) and (pic2_width > pic1_width):
new_pic1 = pic1
new_pic2 = media.create_picture(pic1_width, pic1_height)
elif (pic2_height > pic1_height) and (pic1_width > pic2_width):
new_pic1 = media.create_picture(pic2_width, pic1_height)
new_pic2 = media.create_picture(pic2_width, pic1_height)
scale_red(new_pic1, red)
scale_blue(new_pic1, blue)
scale_green(new_pic1, green)
scale_red(new_pic2, red)
scale_blue(new_pic2, blue)
scale_green(new_pic2, green)
return simple_difference(new_pic1, new_pic2)
I run a self_test file (which was given to us for our assignment), but I keep getting an error here, can anyone help?
*Notes:Simple_difference is another function I wrote beforehand that finds the distance between pixels in the two pictures and scales accordingly
| [
"Kay, the error is: \"AssertError: result after smart_difference should be between 0 and 1200, not 35000\"\nHeres what I did for simple difference:\ndef simple_difference(pic1, pic2):\n '''Given two Pictures of the same dimensions, pic1 and pic2, return the\n sum of the distances in color of the two pictures.... | [
0
] | [] | [] | [
"image_processing",
"python"
] | stackoverflow_0003927497_image_processing_python.txt |
Q:
Read static content from within the code of an application
Is there a way to read the contents of a static data directory or interact with that data in any way from within the code of an application?
Edit: Please excuse me if it wasn't clear at first, I mean getting a list of the files in that directory, not reading the data in them.
A:
No. Files marked as static in app.yaml are not available to your application; they're served from separate servers.
If you just need to list them, you could build a list as part of your deploy process. If you need to actually read them, you'll need to include a second copy in your application directory (although the "copy" can be just a symlink; appcfg.py will follow symlinks and upload them.)
A:
You can just open them (only read only).
| Read static content from within the code of an application | Is there a way to read the contents of a static data directory or interact with that data in any way from within the code of an application?
Edit: Please excuse me if it wasn't clear at first, I mean getting a list of the files in that directory, not reading the data in them.
| [
"No. Files marked as static in app.yaml are not available to your application; they're served from separate servers.\nIf you just need to list them, you could build a list as part of your deploy process. If you need to actually read them, you'll need to include a second copy in your application directory (althoug... | [
3,
1
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0003926712_google_app_engine_python.txt |
Q:
Best way to submit data to a form using Python?
I have not worked with web programming or web forms before so I am lost here. There is a simple perl/cgi
<form method="post" action="/gestalt/cgi-pub/Kaviar.pl" enctype="multipart/form-data">
Now I tried looking at questions here, did a google search and read some about urllib2 etc. I guess I don't know enough about this to pick up from where all those left or integrate and use their examples in a meaningful way to solve my problem.
Here is the page
http://db.systemsbiology.net/gestalt/cgi-pub/Kaviar.pl
and I want to use this page through python , submitting data and retrieving it and parse it in my script.
Sample data is like this
chr1:4793
chr1:53534
chr1:53560
So the question is , can you help me how to submit data and get results back into a python script ,step by step or can you please guide me to a simple, step by step guide that teaches how to do this?
Thanks
A:
This should be a good start:
import urllib, urllib2
url = 'http://db.systemsbiology.net/gestalt/cgi-pub/Kaviar.pl'
form_data = {'chr':'chr1', 'pos':'46743'} # the form takes 2 parameters: 'chr', and 'pos'
# the values given in the dict are
# just examples.
# the next line POSTs the form to url, and reads the resulting response (HTML
# in this case) into the variable response
response = urllib2.urlopen(url,urllib.urlencode(form_data)).read()
# now you can happily parse response.
| Best way to submit data to a form using Python? | I have not worked with web programming or web forms before so I am lost here. There is a simple perl/cgi
<form method="post" action="/gestalt/cgi-pub/Kaviar.pl" enctype="multipart/form-data">
Now I tried looking at questions here, did a google search and read some about urllib2 etc. I guess I don't know enough about this to pick up from where all those left or integrate and use their examples in a meaningful way to solve my problem.
Here is the page
http://db.systemsbiology.net/gestalt/cgi-pub/Kaviar.pl
and I want to use this page through python , submitting data and retrieving it and parse it in my script.
Sample data is like this
chr1:4793
chr1:53534
chr1:53560
So the question is , can you help me how to submit data and get results back into a python script ,step by step or can you please guide me to a simple, step by step guide that teaches how to do this?
Thanks
| [
"This should be a good start:\nimport urllib, urllib2\nurl = 'http://db.systemsbiology.net/gestalt/cgi-pub/Kaviar.pl'\nform_data = {'chr':'chr1', 'pos':'46743'} # the form takes 2 parameters: 'chr', and 'pos'\n # the values given in the dict are\n ... | [
5
] | [] | [] | [
"forms",
"python"
] | stackoverflow_0003927599_forms_python.txt |
Q:
List Comprehension in Nested Lists
I have a list like [["foo", ["a", "b", "c"]], ["bar", ["a", "b", "f"]]]
and I'm wanting to split it out so I can get a count of the total number of As, Bs, etc. but I'm new to Python and having a bit of a time of it.
I'm using [lx for lx in [li[1] for li in fieldlist if li[1]]] to try and get a list with all of the items in the sub-sublists, but that returns a list with the first sublists ([["a", "b", "c"], ["a", "b", "f"]] instead of a list with the contents of those sublists. I'm pretty sure I'm just thinking about this wrong, since I'm new to list comprehensions and Python.
Anyone have a good way to do this? (and yes, I know the names I chose (lx, li) are horrible)
Thanks.
A:
This will give you the list you want:
[lx for li in fieldlist for lx in li[1] if li[1]]
A:
List comprehension:
>>> s = [["foo", ["a", "b", "c"]], ["bar", ["a", "b", "f"]]]
>>> [x for y, z in s for x in z]
['a', 'b', 'c', 'a', 'b', 'f']
>>>
What is the purpose of your if li[1]? If li[1] is an empty list or other container, the test is redundant. Otherwise you should edit your question to explain what else it could be.
A:
A Pythonic solution would be something like:
>>> from collections import Counter
>>> Counter(v for (field, values) in fieldlist
... for v in values)
Counter({'a': 2, 'b': 2, 'c': 1, 'f': 1})
| List Comprehension in Nested Lists | I have a list like [["foo", ["a", "b", "c"]], ["bar", ["a", "b", "f"]]]
and I'm wanting to split it out so I can get a count of the total number of As, Bs, etc. but I'm new to Python and having a bit of a time of it.
I'm using [lx for lx in [li[1] for li in fieldlist if li[1]]] to try and get a list with all of the items in the sub-sublists, but that returns a list with the first sublists ([["a", "b", "c"], ["a", "b", "f"]] instead of a list with the contents of those sublists. I'm pretty sure I'm just thinking about this wrong, since I'm new to list comprehensions and Python.
Anyone have a good way to do this? (and yes, I know the names I chose (lx, li) are horrible)
Thanks.
| [
"This will give you the list you want:\n[lx for li in fieldlist for lx in li[1] if li[1]]\n\n",
"List comprehension:\n>>> s = [[\"foo\", [\"a\", \"b\", \"c\"]], [\"bar\", [\"a\", \"b\", \"f\"]]]\n>>> [x for y, z in s for x in z]\n['a', 'b', 'c', 'a', 'b', 'f']\n>>>\n\nWhat is the purpose of your if li[1]? If li[1... | [
5,
0,
0
] | [] | [] | [
"list_comprehension",
"nested_lists",
"python"
] | stackoverflow_0003927553_list_comprehension_nested_lists_python.txt |
Q:
How do I properly format a StringIO object(python and django) to be inserted into an database?
I have a requeriment to store images in the database using django, and for that I created a custom field :
from django.db import models
class BlobField(models.Field):
__metaclass__ = models.SubfieldBase
def db_type(self, connection):
#TODO handle other db engines
backend = connection.settings_dict['ENGINE']
if backend == 'django.db.backends.postgresql':
return 'bytea'
elif backend == 'django.db.backends.sqlite3':
return 'blob'
else:
raise Exception('unsuported db')
def to_python(self, value):
#TODO
return value
def get_db_prep_value(self, value, connection, prepared=False):
#TODO
return value
I have already implemented a custom storage system to handle the storage/retrieval of images using a custom Model(that contains the above BlobField). The 'value' parameter in the 'get_db_prep_value' method is a 'StringIO' object that contains the image binary data. The catch is that I don't know what to return in the 'get_db_prep_value' method since the 'StringIO' object will surely contain non-printable characters.
I have some questions about the problem:
What should I return in the 'get_db_prep_value' method?
If the expected value is an ASCII string, can I represent the blob(hexadecimal escapes) in a database independent way?
If not, are there built in libraries that handle this kind of conversion for me?
What can I expect to receive as input for the 'to_python' method, and how can I convert it to a StringIO object?
A:
There is no constraint requiring get_db_prep_value to return "printable" characters, or ASCII ones, or otherwise-constrained sets of characters: return any byte string that catches your fancy. You'll get a string in to_python and can make a file-like StringIO instance reading its data with the_instance = StringIO.StringIO(value) (of course you'll need to import StringIO at the top of your module).
| How do I properly format a StringIO object(python and django) to be inserted into an database? | I have a requeriment to store images in the database using django, and for that I created a custom field :
from django.db import models
class BlobField(models.Field):
__metaclass__ = models.SubfieldBase
def db_type(self, connection):
#TODO handle other db engines
backend = connection.settings_dict['ENGINE']
if backend == 'django.db.backends.postgresql':
return 'bytea'
elif backend == 'django.db.backends.sqlite3':
return 'blob'
else:
raise Exception('unsuported db')
def to_python(self, value):
#TODO
return value
def get_db_prep_value(self, value, connection, prepared=False):
#TODO
return value
I have already implemented a custom storage system to handle the storage/retrieval of images using a custom Model(that contains the above BlobField). The 'value' parameter in the 'get_db_prep_value' method is a 'StringIO' object that contains the image binary data. The catch is that I don't know what to return in the 'get_db_prep_value' method since the 'StringIO' object will surely contain non-printable characters.
I have some questions about the problem:
What should I return in the 'get_db_prep_value' method?
If the expected value is an ASCII string, can I represent the blob(hexadecimal escapes) in a database independent way?
If not, are there built in libraries that handle this kind of conversion for me?
What can I expect to receive as input for the 'to_python' method, and how can I convert it to a StringIO object?
| [
"There is no constraint requiring get_db_prep_value to return \"printable\" characters, or ASCII ones, or otherwise-constrained sets of characters: return any byte string that catches your fancy. You'll get a string in to_python and can make a file-like StringIO instance reading its data with the_instance = StringI... | [
13
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0003915888_django_django_models_python.txt |
Q:
Jython: subprocess.Popen runs out of file descriptors
I'm using the Jython 2.51 implementation of Python to write a script that repeatedly invokes another process via subprocess.Popen and uses PIPE to pipe stdout and stderr to the parent process and stdin to the child process. After several hundred loop iterations, I seem to run out of file descriptors.
The Python subprocess documentation mentions very little about freeing file descriptors, other than the close_fds option, which isn't described very clearly (Why should there be any file descriptors besides 0, 1 and 2 open in the first place?). I'm assuming that in CPython, reference counting takes care of the resource freeing issue. What's the proper way to make sure all descriptors get freed when one is done with a Popen object in Jython?
Edit: Just in case it makes a difference, this is a multithreaded program, so there are several Popen processes running simultaneously.
A:
This only answers part of your question, but my understanding is that, when you spawn a new process, it normally inherits all the handles of the parent process. That includes such things as open files and sockets that you're listening on.
On UNIX, that's a side-effect of using 'fork', which duplicates the current process and all of its handles before loading the new executable. On Windows it's more explicit, but Python does it anyway, to try to match the behavior across platforms as much as possible.
The close_fds option, when True, closes all these inherited handles after spawning the subprocess, so the new executable starts with a clean slate. But if your subprocesses are run one at a time, and terminating when they're done, then this shouldn't be the problem.
| Jython: subprocess.Popen runs out of file descriptors | I'm using the Jython 2.51 implementation of Python to write a script that repeatedly invokes another process via subprocess.Popen and uses PIPE to pipe stdout and stderr to the parent process and stdin to the child process. After several hundred loop iterations, I seem to run out of file descriptors.
The Python subprocess documentation mentions very little about freeing file descriptors, other than the close_fds option, which isn't described very clearly (Why should there be any file descriptors besides 0, 1 and 2 open in the first place?). I'm assuming that in CPython, reference counting takes care of the resource freeing issue. What's the proper way to make sure all descriptors get freed when one is done with a Popen object in Jython?
Edit: Just in case it makes a difference, this is a multithreaded program, so there are several Popen processes running simultaneously.
| [
"This only answers part of your question, but my understanding is that, when you spawn a new process, it normally inherits all the handles of the parent process. That includes such things as open files and sockets that you're listening on.\nOn UNIX, that's a side-effect of using 'fork', which duplicates the curren... | [
3
] | [] | [] | [
"file_io",
"jython",
"popen",
"python",
"resources"
] | stackoverflow_0003927595_file_io_jython_popen_python_resources.txt |
Q:
Is it possible to overload from/import in Python?
Is it possible to overload the from/import statement in Python?
For example, assuming jvm_object is an instance of class JVM, is it possible to write this code:
class JVM(object):
def import_func(self, cls):
return something...
jvm = JVM()
# would invoke JVM.import_func
from jvm import Foo
A:
This post demonstrates how to use functionality introduced in PEP-302 to import modules over the web. I post it as an example of how to customize the import statement rather than as suggested usage ;)
A:
It's hard to find something which isn't possible in a dynamic language like Python, but do we really need to abuse everything? Anyway, here it is:
from types import ModuleType
import sys
class JVM(ModuleType):
Foo = 3
sys.modules['JVM'] = JVM
from JVM import Foo
print Foo
But one pattern I've seen in several libraries/projects is some kind of a _make_module() function, which creates a ModuleType dynamically and initializes everything in it. After that, the current Module is replaced by the new module (using the assignment to sys.modules) and the _make_module() function gets deleted. The advantage of that, is that you can loop over the module and even add objects to the module inside that loop, which is quite useful sometimes (but use it with caution!).
| Is it possible to overload from/import in Python? | Is it possible to overload the from/import statement in Python?
For example, assuming jvm_object is an instance of class JVM, is it possible to write this code:
class JVM(object):
def import_func(self, cls):
return something...
jvm = JVM()
# would invoke JVM.import_func
from jvm import Foo
| [
"This post demonstrates how to use functionality introduced in PEP-302 to import modules over the web. I post it as an example of how to customize the import statement rather than as suggested usage ;) \n",
"It's hard to find something which isn't possible in a dynamic language like Python, but do we really need ... | [
7,
3
] | [] | [] | [
"import",
"operator_overloading",
"python"
] | stackoverflow_0003928023_import_operator_overloading_python.txt |
Q:
I'm trying to pick a framework for a product I'm about to build, and so far I'm leaning toward Nagare... Any thoughts?
http://www.nagare.org/
As far as the type of product and framework usage, think something like Facebook (it's not exactly a social network, but close enough for evaluation in this context).
Basically, I'm just looking for something robust, scalable, easy to work with (small learning curve is a plus), compatible with older browsers, and well integrated with other technologies (e.g. Postgres, unless there's a compelling case to be made for Cassandra?).
Other frameworks/tools I've looked a bit at or been recommended:
Google Web Toolkit + Server-side Java
Django
Ruby on Rails
ASP.NET + Mono? (I know...)
PHP/Perl/BBQ
I don't have a whole lot of experience with Web frameworks, so no matter what we end up choosing (whether I've mentioned it or not) I'll be learning something new. Any thoughts or recommendations? Anyone have any experience with Nagare (or Pyjamas)?
A:
I would suggest Django + Pinax. Both are robust and have less learning curve (if you have familiarity with Python).
This should have you a social network up & running within a day or two.
For the front-end use the usual suspects. javascript, css, html. I believe there are some terrific libraries for javascript.
A:
As the lead developer of Nagare, I really encourage you to try it in real on your product, which is the best way to see how Nagare is truely different than the others frameworks like Django, Pylons or Flask. Nagare is components oriented (it shares the same components model than Seaside) and its set of advance features like direct callbacks registration, stateful components, Ajax without to write any Javascript code or the use of continuations makes a Web application looks like a desktop one. In fact we have often found that developers like you, without prior Web experiences, can be quicker to get Nagare because they have nothing to "unlearn".
Talking about reliability, scabability and compatibility, you can check some of our important projects in production today.
For more info, don't hesitate to ask and share your experiences with us.
| I'm trying to pick a framework for a product I'm about to build, and so far I'm leaning toward Nagare... Any thoughts? | http://www.nagare.org/
As far as the type of product and framework usage, think something like Facebook (it's not exactly a social network, but close enough for evaluation in this context).
Basically, I'm just looking for something robust, scalable, easy to work with (small learning curve is a plus), compatible with older browsers, and well integrated with other technologies (e.g. Postgres, unless there's a compelling case to be made for Cassandra?).
Other frameworks/tools I've looked a bit at or been recommended:
Google Web Toolkit + Server-side Java
Django
Ruby on Rails
ASP.NET + Mono? (I know...)
PHP/Perl/BBQ
I don't have a whole lot of experience with Web frameworks, so no matter what we end up choosing (whether I've mentioned it or not) I'll be learning something new. Any thoughts or recommendations? Anyone have any experience with Nagare (or Pyjamas)?
| [
"I would suggest Django + Pinax. Both are robust and have less learning curve (if you have familiarity with Python). \nThis should have you a social network up & running within a day or two.\nFor the front-end use the usual suspects. javascript, css, html. I believe there are some terrific libraries for javascript.... | [
5,
4
] | [] | [] | [
"frameworks",
"java",
"javascript",
"python"
] | stackoverflow_0003921312_frameworks_java_javascript_python.txt |
Q:
Send files from form directly to remote server
In my application I'm dealing with upload of really big image files. They will be stored on a remote server, so from what I was able to learn I need to write some custom Storage system (probably with the use of python's poster module). Because of the size I would like to send the files directly to media server without storing them in memory (which 'poster' enables). But all uploaded files are handled by UploadHandler class, which forces files to be stored locally in some way (file, temp or in memory). So how can I get around this ?
A:
According to the docs, the UploadedFile class should have a method chunks() which returns a generator. The chunk size is configurable (2.5 MB by default). So you can do something like that (copied from the docs):
destination = open('some/file/name.txt', 'wb+')
for chunk in f.chunks():
destination.write(chunk)
destination.close()
This will read one chunk after another into the memory and write it to a file. (So there is only one chunk at the time in the memory). You might want to change the path of open() to a NFS volume, then every call to write() would only send the current chunk to the NFS. (NFS exports all file operations like open/write/read/seek/close as RPC). Samba works similar.
Alternatively, you can also implement such a mechanism on your own, by running another service at the media server which offers a method of appending a chunk to a file. (Anyway, using NFS or Samba would be the better choice in my opinion).
A:
You might find xsendfile(snippet) or similar extensions of web servers usefull. But you have to initiate the connection from the requesting machine then.
| Send files from form directly to remote server | In my application I'm dealing with upload of really big image files. They will be stored on a remote server, so from what I was able to learn I need to write some custom Storage system (probably with the use of python's poster module). Because of the size I would like to send the files directly to media server without storing them in memory (which 'poster' enables). But all uploaded files are handled by UploadHandler class, which forces files to be stored locally in some way (file, temp or in memory). So how can I get around this ?
| [
"According to the docs, the UploadedFile class should have a method chunks() which returns a generator. The chunk size is configurable (2.5 MB by default). So you can do something like that (copied from the docs):\ndestination = open('some/file/name.txt', 'wb+')\nfor chunk in f.chunks():\n destination.write(chun... | [
0,
0
] | [] | [] | [
"django",
"file_upload",
"python"
] | stackoverflow_0003928300_django_file_upload_python.txt |
Q:
Automatically expiring variable
How to implement an automatically expiring variable in python? For example, Let the program running For one hour. I want implement an array of 6 variables, each variable in array will be automatically deleted themselves after 10 mins. And after 1 hour, there will be no variable in the array.
A:
I actually had to do this for dictionaries. Maybe you'll find the code useful:
"""Cache which has data that expires after a given period of time."""
from datetime import datetime, timedelta
class KeyExpiredError(KeyError): pass
def __hax():
class NoArg: pass
return NoArg()
NoArg = __hax()
class DataCache(object):
def __init__(self, defaultExpireTime=timedelta(1, 0, 0), dbg=True):
self.defaultExpireTime = defaultExpireTime
self.cache = {}
self.dbg = dbg
self.processExpires = True
def setProcessExpires(self, b):
self.processExpires = b
def __getitem__(self, key):
c = self.cache[key]
n = datetime.now()
if (n - c['timestamp']) < c['expireTime'] or not self.processExpires:
return c['data']
del self.cache[key]
if self.dbg:
print "DataCache: Key %s expired" % repr(key)
raise KeyExpiredError(key)
def __contains__(self, key):
try:
self[key]
return True
except KeyError:
return False
def __setitem__(self, key, val):
self.cache[key] = {
'data': val,
'timestamp': datetime.now(),
'expireTime': self.defaultExpireTime,
}
def items(self):
keys = list(self.cache)
for k in keys:
try:
val = self[k]
yield (k, val)
except:
pass
def get(self, key, default=NoArg, expired=NoArg):
try:
return self[key]
except KeyExpiredError:
if expired is NoArg and default is not NoArg:
return default
if expired is NoArg: return None
return expired
except KeyError:
if default is NoArg: return None
return default
def set(self, key, val, expireTime=None):
if expireTime is None:
expireTime = self.defaultExpireTime
self.cache[key] = {
'data': val,
'timestamp': datetime.now(),
'expireTime': expireTime,
}
def tryremove(self, key):
if key in self.cache:
del self.cache[key]
return True
return False
#the following you can call without triggering any expirations
def getTotalExpireTime(self, key):
"""Get the total amount of time the key will be in the cache for"""
c = self.cache[key]
return c['expireTime']
def getExpirationTime(self, key):
"""Return the datetime when the given key will expire"""
c = self.cache[key]
return c['timestamp'] + c['expireTime']
def getTimeRemaining(self, key):
"""Get the time left until the item will expire"""
return self.getExpirationTime(key) - datetime.now()
def getTimestamp(self, key):
return self.cache[key]['timestamp']
def __len__(self):
return len(self.cache)
Usage:
>>> dc = DataCache(timedelta(0, 5, 0)) #expire in 5 seconds
>>> dc[4] = 3
>>> dc[4]
3
>>> import time
>>> time.sleep(5)
>>> dc[4]
DataCache: Key 4 expired
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
dc[4]
File "datacache.py", line 35, in __getitem__
raise KeyExpiredError(key)
KeyExpiredError: 4
>>>
A:
Hmmm, seems weird, but possible.
Sounds like you need a class which records the time when __init__ is called. Then, implement __getitem__ to check the time when it is called, and only return the item if it's not too late. (It's probably easier to do this than to have a process "running in the background" which actively deletes items even when you don't ask for them.)
A:
you can create a background process that check how much time it's passed, and del the right item... or if you want to create a subclass of list wich deletes it's contens after a certain time you can do the same thing, just calling it in init
def __init__(self, time):
#run subprocess to chek_espired elements
edit:
i wrote an example, but it can be done much better!
class MyList(list):
def __init__(self,elems, expires_time):
list.__init__(self, elems)
self.created = time.time()
self.expires_time = expires_time
def __getitem__(self, index):
t = time.time()
print t - self.created
if t - self.created > self.expires_time:
self.created += self.expires_time
self.pop(index)
self.__getitem__(index)
return list.__getitem__(self, index)
ps of course you can easily raise a personal error if the program try to get the index from an empty list
A:
It sounds like the items in your array know about each other, because otherwise they'll all expire at the same time.
I think you want to create a subclass of list which deletes its contents after a certain time.
A:
import sched
import time
import threading
a = [1, 2, 3, 4, 5, 6]
scheduler = sched.scheduler(time.time, time.sleep)
def delete(_list):
del _list[0]
for i in range(len(a)):
scheduler.enter(60*10*i, 1, delete, (a,))
t = threading.Thread(target=scheduler.run)
t.start()
A:
You can use the time module to clear the "array" every 10 minutes, by checking the time interval from when the script starts.
The last example on http://effbot.org/librarybook/time.htm point you in the right direction.
| Automatically expiring variable | How to implement an automatically expiring variable in python? For example, Let the program running For one hour. I want implement an array of 6 variables, each variable in array will be automatically deleted themselves after 10 mins. And after 1 hour, there will be no variable in the array.
| [
"I actually had to do this for dictionaries. Maybe you'll find the code useful:\n\"\"\"Cache which has data that expires after a given period of time.\"\"\"\nfrom datetime import datetime, timedelta\n\nclass KeyExpiredError(KeyError): pass \n\ndef __hax():\n class NoArg: pass\n return NoArg()\nNoArg = __hax()... | [
9,
8,
3,
1,
1,
0
] | [] | [] | [
"arrays",
"python",
"variables"
] | stackoverflow_0003927166_arrays_python_variables.txt |
Q:
How to setup springpython with Jython and Eclipse/PyDev?
I'm having trouble setting up SpringPython with PyDev and Jython
I've installed Spring python by:
jython setup.py install
and the setup installed the library to my jython installation successfully.
See!:
In my PyDev project i've selected the jython interpreter and have c:\jython2.5.1\Lib\site-packages in my Library paths:
My eclipse environment fails to resolve the new classes:
What else do I need to do to install this baby?
Perhaps I should just be using the Java version of spring...
Thanks SO!
A:
The python interpreter that is used to compile your Python files is specified by PyDev on the project level. I suspect that while you do have Jython installed, your Eclipse project (katas) still uses CPython.
Perform the following steps to fix this:
Open your project properties: right-click your project folder ("katas") and select properties
Select tab "PyDev - Interpreter/Grammar"
Switch Python to "Jython"
Your files should now be compiled correctly using Jython.
As noted by the asker himself, you may need to restart your editor (or the Eclipse itself).
A:
Turns out that I just needed to restart eclipse, there you go.
| How to setup springpython with Jython and Eclipse/PyDev? | I'm having trouble setting up SpringPython with PyDev and Jython
I've installed Spring python by:
jython setup.py install
and the setup installed the library to my jython installation successfully.
See!:
In my PyDev project i've selected the jython interpreter and have c:\jython2.5.1\Lib\site-packages in my Library paths:
My eclipse environment fails to resolve the new classes:
What else do I need to do to install this baby?
Perhaps I should just be using the Java version of spring...
Thanks SO!
| [
"The python interpreter that is used to compile your Python files is specified by PyDev on the project level. I suspect that while you do have Jython installed, your Eclipse project (katas) still uses CPython.\nPerform the following steps to fix this:\n\nOpen your project properties: right-click your project folder... | [
1,
1
] | [] | [] | [
"jython",
"pydev",
"python",
"spring"
] | stackoverflow_0003921191_jython_pydev_python_spring.txt |
Q:
How to list an image sequence in an efficient way? Numercial sequence comparison in Python
I have a directory of 9 images:
image_0001, image_0002, image_0003
image_0010, image_0011
image_0011-1, image_0011-2, image_0011-3
image_9999
I would like to be able to list them in an efficient way, like this (4 entries for 9 images):
(image_000[1-3], image_00[10-11], image_0011-[1-3], image_9999)
Is there a way in python, to return a directory of images, in a short/clear way (without listing every file)?
So, possibly something like this:
list all images, sort numerically, create a list (counting each image in sequence from start).
When an image is missing (create a new list), continue until original file list is finished.
Now I should just have some lists that contain non broken sequences.
I'm trying to make it easy to read/describe a list of numbers. If I had a sequence of 1000 consecutive files It could be clearly listed as file[0001-1000] rather than file['0001','0002','0003' etc...]
Edit1(based on suggestion): Given a flattened list, how would you derive the glob patterns?
Edit2 I'm trying to break the problem down into smaller pieces. Here is an example of part of the solution:
data1 works, data2 returns 0010 as 64, data3 (the realworld data) doesn't work:
# Find runs of consecutive numbers using groupby. The key to the solution
# is differencing with a range so that consecutive numbers all appear in
# same group.
from operator import itemgetter
from itertools import *
data1=[01,02,03,10,11,100,9999]
data2=[0001,0002,0003,0010,0011,0100,9999]
data3=['image_0001','image_0002','image_0003','image_0010','image_0011','image_0011-2','image_0011-3','image_0100','image_9999']
list1 = []
for k, g in groupby(enumerate(data1), lambda (i,x):i-x):
list1.append(map(itemgetter(1), g))
print 'data1'
print list1
list2 = []
for k, g in groupby(enumerate(data2), lambda (i,x):i-x):
list2.append(map(itemgetter(1), g))
print '\ndata2'
print list2
returns:
data1
[[1, 2, 3], [10, 11], [100], [9999]]
data2
[[1, 2, 3], [8, 9], [64], [9999]]
A:
Here is a working implementation of what you want to achieve, using the code you added as a starting point:
#!/usr/bin/env python
import itertools
import re
# This algorithm only works if DATA is sorted.
DATA = ["image_0001", "image_0002", "image_0003",
"image_0010", "image_0011",
"image_0011-1", "image_0011-2", "image_0011-3",
"image_0100", "image_9999"]
def extract_number(name):
# Match the last number in the name and return it as a string,
# including leading zeroes (that's important for formatting below).
return re.findall(r"\d+$", name)[0]
def collapse_group(group):
if len(group) == 1:
return group[0][1] # Unique names collapse to themselves.
first = extract_number(group[0][1]) # Fetch range
last = extract_number(group[-1][1]) # of this group.
# Cheap way to compute the string length of the upper bound,
# discarding leading zeroes.
length = len(str(int(last)))
# Now we have the length of the variable part of the names,
# the rest is only formatting.
return "%s[%s-%s]" % (group[0][1][:-length],
first[-length:], last[-length:])
groups = [collapse_group(tuple(group)) \
for key, group in itertools.groupby(enumerate(DATA),
lambda(index, name): index - int(extract_number(name)))]
print groups
This prints ['image_000[1-3]', 'image_00[10-11]', 'image_0011-[1-3]', 'image_0100', 'image_9999'], which is what you want.
HISTORY: I initially answered the question backwards, as @Mark Ransom pointed out below. For the sake of history, my original answer was:
You're looking for glob. Try:
import glob
images = glob.glob("image_[0-9]*")
Or, using your example:
images = [glob.glob(pattern) for pattern in ("image_000[1-3]*",
"image_00[10-11]*", "image_0011-[1-3]*", "image_9999*")]
images = [image for seq in images for image in seq] # flatten the list
A:
Okay, so I found your question to be a fascinating puzzle. I've left how to
"compress" the numeric ranges up to you (marked as a TODO), as there are
different ways to accomplish that depending on how you like it formatted and if
you want the minimum number of elements or the minimum string description
length.
This solution uses a simple regular expression (digit strings) to classify each string into two groups: static and variable. After the data is classified, I use groupby to collect the
static data into longest matching groups to achieve the summary effect. I mix integer index sentinals into the result (in matchGrouper) so I can re-select the varying parts from all elements (in unpack).
import re
import glob
from itertools import groupby
from operator import itemgetter
def classifyGroups(iterable, reObj=re.compile('\d+')):
"""Yields successive match lists, where each item in the list is either
static text content, or a list of matching values.
* `iterable` is a list of strings, such as glob('images/*')
* `reObj` is a compiled regular expression that describes the
variable section of the iterable you want to match and classify
"""
def classify(text, pos=0):
"""Use a regular expression object to split the text into match and non-match sections"""
r = []
for m in reObj.finditer(text, pos):
m0 = m.start()
r.append((False, text[pos:m0]))
pos = m.end()
r.append((True, text[m0:pos]))
r.append((False, text[pos:]))
return r
def matchGrouper(each):
"""Returns index of matches or origional text for non-matches"""
return [(i if t else v) for i,(t,v) in enumerate(each)]
def unpack(k,matches):
"""If the key is an integer, unpack the value array from matches"""
if isinstance(k, int):
k = [m[k][1] for m in matches]
return k
# classify each item into matches
matchLists = (classify(t) for t in iterable)
# group the matches by their static content
for key, matches in groupby(matchLists, matchGrouper):
matches = list(matches)
# Yield a list of content matches. Each entry is either text
# from static content, or a list of matches
yield [unpack(k, matches) for k in key]
Finally, we add enough logic to perform pretty printing of the output, and run an example.
def makeResultPretty(res):
"""Formats data somewhat like the question"""
r = []
for e in res:
if isinstance(e, list):
# TODO: collapse and simplify ranges as desired here
if len(set(e))<=1:
# it's a list of the same element
e = e[0]
else:
# prettify the list
e = '['+' '.join(e)+']'
r.append(e)
return ''.join(r)
fnList = sorted(glob.glob('images/*'))
re_digits = re.compile(r'\d+')
for res in classifyGroups(fnList, re_digits):
print makeResultPretty(res)
My directory of images was created from your example. You can replace fnList with the following list for testing:
fnList = [
'images/image_0001.jpg',
'images/image_0002.jpg',
'images/image_0003.jpg',
'images/image_0010.jpg',
'images/image_0011-1.jpg',
'images/image_0011-2.jpg',
'images/image_0011-3.jpg',
'images/image_0011.jpg',
'images/image_9999.jpg']
And when I run against this directory, my output looks like:
StackOverflow/3926936% python classify.py
images/image_[0001 0002 0003 0010].jpg
images/image_0011-[1 2 3].jpg
images/image_[0011 9999].jpg
A:
def ranges(sorted_list):
first = None
for x in sorted_list:
if first is None:
first = last = x
elif x == increment(last):
last = x
else:
yield first, last
first = last = x
if first is not None:
yield first, last
The increment function is left as an exercise for the reader.
Edit: here's an example of how it would be used with integers instead of strings as input.
def increment(x): return x+1
list(ranges([1,2,3,4,6,7,8,10]))
[(1, 4), (6, 8), (10, 10)]
For each contiguous range in the input you get a pair indicating the start and end of the range. If an element isn't part of a range, the start and end values are identical.
| How to list an image sequence in an efficient way? Numercial sequence comparison in Python | I have a directory of 9 images:
image_0001, image_0002, image_0003
image_0010, image_0011
image_0011-1, image_0011-2, image_0011-3
image_9999
I would like to be able to list them in an efficient way, like this (4 entries for 9 images):
(image_000[1-3], image_00[10-11], image_0011-[1-3], image_9999)
Is there a way in python, to return a directory of images, in a short/clear way (without listing every file)?
So, possibly something like this:
list all images, sort numerically, create a list (counting each image in sequence from start).
When an image is missing (create a new list), continue until original file list is finished.
Now I should just have some lists that contain non broken sequences.
I'm trying to make it easy to read/describe a list of numbers. If I had a sequence of 1000 consecutive files It could be clearly listed as file[0001-1000] rather than file['0001','0002','0003' etc...]
Edit1(based on suggestion): Given a flattened list, how would you derive the glob patterns?
Edit2 I'm trying to break the problem down into smaller pieces. Here is an example of part of the solution:
data1 works, data2 returns 0010 as 64, data3 (the realworld data) doesn't work:
# Find runs of consecutive numbers using groupby. The key to the solution
# is differencing with a range so that consecutive numbers all appear in
# same group.
from operator import itemgetter
from itertools import *
data1=[01,02,03,10,11,100,9999]
data2=[0001,0002,0003,0010,0011,0100,9999]
data3=['image_0001','image_0002','image_0003','image_0010','image_0011','image_0011-2','image_0011-3','image_0100','image_9999']
list1 = []
for k, g in groupby(enumerate(data1), lambda (i,x):i-x):
list1.append(map(itemgetter(1), g))
print 'data1'
print list1
list2 = []
for k, g in groupby(enumerate(data2), lambda (i,x):i-x):
list2.append(map(itemgetter(1), g))
print '\ndata2'
print list2
returns:
data1
[[1, 2, 3], [10, 11], [100], [9999]]
data2
[[1, 2, 3], [8, 9], [64], [9999]]
| [
"Here is a working implementation of what you want to achieve, using the code you added as a starting point:\n#!/usr/bin/env python\n\nimport itertools\nimport re\n\n# This algorithm only works if DATA is sorted.\nDATA = [\"image_0001\", \"image_0002\", \"image_0003\",\n \"image_0010\", \"image_0011\",\n ... | [
6,
3,
2
] | [] | [] | [
"glob",
"python",
"regex"
] | stackoverflow_0003926936_glob_python_regex.txt |
Q:
Compare Python Web Frameworks and their respective HTML5 APIs Implementations
If you are familiar with a specific python web framework that has implementations for HTML5 API(s) ie.WebSockets, Forms, WebWorkers, WebStorage, Communication, Geolocation, Canvas, etc.
Then please list the name of the framework and its HTML5 capabilities.
A:
If you prefer writing your client code in Python, check out Pyjamas.
I'm sorry, I haven't looked into its HTML5 capabilities.
| Compare Python Web Frameworks and their respective HTML5 APIs Implementations | If you are familiar with a specific python web framework that has implementations for HTML5 API(s) ie.WebSockets, Forms, WebWorkers, WebStorage, Communication, Geolocation, Canvas, etc.
Then please list the name of the framework and its HTML5 capabilities.
| [
"If you prefer writing your client code in Python, check out Pyjamas.\nI'm sorry, I haven't looked into its HTML5 capabilities.\n"
] | [
0
] | [] | [] | [
"django",
"html",
"python",
"tornado",
"web_applications"
] | stackoverflow_0003841983_django_html_python_tornado_web_applications.txt |
Q:
Documenting Python scripts for non-programmers
We are currently looking for ways to help the non-programming members of the sysadmin group familiarize themselves with Python scripts used for day-to-day sysadmin tasks.
Does anyone have any suggested documentation tools or best practices that we might find useful for this purpose?
Edit to address S.Lott's comment:
First, my apologies for being too brief on my initial question. My primary goal is to make sure that someone, even a non-programmer, is easily able to troubleshoot my scripts if I'm not in that day or if I leave the organization.
What I'm looking for is practices used by other people who have the "script coder" role in a technical group such as a sysadmin team. For example, before I begin the process of scripting a task, I've gotten into the habit of first writing an article in our shared wiki explaining each step in detail. I then base my Python scripts on the article--using it as pseudo code.
Other examples of the sorts of things I'm looking for:
Using tools such as Sphinx to provide easily available doc
Having group discussions to go over code before putting in production
Allowing group members to first go over the process manually (we usually go this route but perhaps we should make it a more common practice)
Or, just as valuable if not more so, negatives such as:
Found that heavy commenting is a waste of time because the logic flow is still foreign to non-programmers
Lean toward using pexpect because of the verbosity lost when using high level modules
The above are just examples of things I thought of. Hope this clarifies the question! As always, thanks SO'ers.
A:
There is a book on this subject - "Python for Unix and Linux System Administration".
http://oreilly.com/catalog/9780596515829
And an article on developer works which might provide you the flavor that you may want to follow.
http://www.ibm.com/developerworks/aix/library/au-python/
And almost any one, irrespective of how, he is going to apply it, would want to work on the basics of the language itself. There is a good starter on web apart from tutorial that is distributed along with standard python distribution.
http://diveintopython3.ep.io/
A:
I find that using argparse as the basis for script invocation parsing/routing tends to produce a decent first line of documentation. If used as intended, your sysadmins can run some_script --help to get a description of the script's purpose and a summary of its options.
It can be fairly trivial to link the documentation sources used by the parser building code to the actual docstrings of functions and classes in your code and that of the script itself. It depends on the complexity of the script, but this can often be a low-effort way to get sufficient documentation.
| Documenting Python scripts for non-programmers | We are currently looking for ways to help the non-programming members of the sysadmin group familiarize themselves with Python scripts used for day-to-day sysadmin tasks.
Does anyone have any suggested documentation tools or best practices that we might find useful for this purpose?
Edit to address S.Lott's comment:
First, my apologies for being too brief on my initial question. My primary goal is to make sure that someone, even a non-programmer, is easily able to troubleshoot my scripts if I'm not in that day or if I leave the organization.
What I'm looking for is practices used by other people who have the "script coder" role in a technical group such as a sysadmin team. For example, before I begin the process of scripting a task, I've gotten into the habit of first writing an article in our shared wiki explaining each step in detail. I then base my Python scripts on the article--using it as pseudo code.
Other examples of the sorts of things I'm looking for:
Using tools such as Sphinx to provide easily available doc
Having group discussions to go over code before putting in production
Allowing group members to first go over the process manually (we usually go this route but perhaps we should make it a more common practice)
Or, just as valuable if not more so, negatives such as:
Found that heavy commenting is a waste of time because the logic flow is still foreign to non-programmers
Lean toward using pexpect because of the verbosity lost when using high level modules
The above are just examples of things I thought of. Hope this clarifies the question! As always, thanks SO'ers.
| [
"There is a book on this subject - \"Python for Unix and Linux System Administration\".\n\nhttp://oreilly.com/catalog/9780596515829\n\nAnd an article on developer works which might provide you the flavor that you may want to follow.\n\nhttp://www.ibm.com/developerworks/aix/library/au-python/\n\nAnd almost any one, ... | [
2,
2
] | [] | [] | [
"documentation_generation",
"python"
] | stackoverflow_0003928021_documentation_generation_python.txt |
Q:
lxml cleaner with a custom tag?
I want to use lxml cleaner to get rid of all html, but then a regex to autolink something:
[ABC] -> <a href="bah bah bah">ABC</a>
what is the right way to handle this without xss and such?
A:
Maybe using markdown with inline HTML disabled would be suitable? The python markdown module is quite mature.
Check out the "safe mode" section in the docs for more info on stripping out inline HTML.
Depending on what you want, something like py-wikimarkup may be more appropriate.
Using a custom regexp is probably not a great idea, because
you'll have to explain the rules to people who might already be familiar with markdown/WikiText
you'll have to provide a way to escape text, e.g. for people who really want to write [ABC]
you'll have to fix any bugs, including security issues
| lxml cleaner with a custom tag? | I want to use lxml cleaner to get rid of all html, but then a regex to autolink something:
[ABC] -> <a href="bah bah bah">ABC</a>
what is the right way to handle this without xss and such?
| [
"Maybe using markdown with inline HTML disabled would be suitable? The python markdown module is quite mature.\nCheck out the \"safe mode\" section in the docs for more info on stripping out inline HTML.\nDepending on what you want, something like py-wikimarkup may be more appropriate.\nUsing a custom regexp is pr... | [
1
] | [] | [] | [
"lxml",
"python",
"xss"
] | stackoverflow_0003928060_lxml_python_xss.txt |
Q:
String Comparison with a Format - Python
I wanted to check if user has entered the input in particular order or not. Basically i wanted user to input date in format like this
%d/%m/%y %H:%M
Is there any way i can compare string input with the above format in python?
A:
import time
time.strptime("01/01/09 12:23", "%d/%m/%y %H:%M")
This will raise ValueError if the string doesn't match:
time.strptime("01/01/09 12:234", "%d/%m/%y %H:%M")
time.strptime("01-01-09 12:23", "%d/%m/%y %H:%M")
By the way, please don't bring back two-digit years--use %Y if at all possible.
A:
This sounds like a job for... Regular Expressions! Have a look at the re module. What you want is simple enough that it would be fairly trivial to just hand you the regex for it, but you should learn to use them yourself.
OK, for this job, the strptime answer is better. But for the general case of making sure a string matches up with a format, regular expressions are generally the way to go.
| String Comparison with a Format - Python | I wanted to check if user has entered the input in particular order or not. Basically i wanted user to input date in format like this
%d/%m/%y %H:%M
Is there any way i can compare string input with the above format in python?
| [
"import time\ntime.strptime(\"01/01/09 12:23\", \"%d/%m/%y %H:%M\")\n\nThis will raise ValueError if the string doesn't match:\ntime.strptime(\"01/01/09 12:234\", \"%d/%m/%y %H:%M\")\ntime.strptime(\"01-01-09 12:23\", \"%d/%m/%y %H:%M\")\n\nBy the way, please don't bring back two-digit years--use %Y if at all possi... | [
8,
2
] | [] | [] | [
"comparison",
"python",
"string"
] | stackoverflow_0003928999_comparison_python_string.txt |
Q:
AES encryption library compatible with Python 2.7 for Windows
Any recommendations on an AES encryption library that's compatible with Python 2.7 for Windows?
In the past we've used m2crypto with Python 2.6, but there's no version of m2crypto for Python 2.7 and our attempts to build a version from source have failed.
Thank you,
Malcolm
A:
Actually, the M2Crypto package supports Python 2.7 just fine — I have been using it in a cryptography-heavy application with no problem. I suppose the problem here is that Windows does not come with a compiler, so you cannot easily install the .tar.gz off of PyPI? Or are you getting an error when you try to compile it?
I would suggest that the best response to an error would be posting it to Stack Overflow so that we could fix it, instead of asking for alternative to what is — so far as I can tell — the premier cryptography library for Python.
Update: I have now successfully built M2Crypto for Windows under Python 2.7, so I can personally confirm that it works fine with Python 2.7 on all major platforms.
A:
Have you looked at the PyCrypto library?
http://www.dlitz.net/software/pycrypto/
It should be compatible with Python 2.7
You might also take a look at pycryptopp, a wrapper around the Crypto++ library.
http://tahoe-lafs.org/trac/pycryptopp
| AES encryption library compatible with Python 2.7 for Windows | Any recommendations on an AES encryption library that's compatible with Python 2.7 for Windows?
In the past we've used m2crypto with Python 2.6, but there's no version of m2crypto for Python 2.7 and our attempts to build a version from source have failed.
Thank you,
Malcolm
| [
"Actually, the M2Crypto package supports Python 2.7 just fine — I have been using it in a cryptography-heavy application with no problem. I suppose the problem here is that Windows does not come with a compiler, so you cannot easily install the .tar.gz off of PyPI? Or are you getting an error when you try to compil... | [
2,
1
] | [] | [] | [
"cryptography",
"m2crypto",
"python",
"python_2.7"
] | stackoverflow_0003859623_cryptography_m2crypto_python_python_2.7.txt |
Q:
rounding-up numbers within a tuple
Is there anyway I could round-up numbers within a tuple to two decimal points,
from this:
('string 1', 1234.55555, 5.66666, 'string2')
to this:
('string 1', 1234.56, 5.67, 'string2')
Many thanks in advance.
A:
If your tuple has a fixed size of 4 and the position of the floats is always the same, you can do this:
>>> t = ('string 1', 1234.55555, 5.66666, 'string2')
>>> t2 = (t[0], round(t[1], 2), round(t[2], 2), t[3])
>>> t2
('string 1', 1234.56, 5.67, 'string2')
The general solution would be:
>>> t2 = tuple(map(lambda x: isinstance(x, float) and round(x, 2) or x, t))
>>> t2
('string 1', 1234.56, 5.67, 'string2')
A:
List comprehension solution:
t = ('string 1', 1234.55555, 5.66666, 'string2')
solution = tuple([round(x,2) if isinstance(x, float) else x for x in t])
A:
To avoid issues with floating-point rounding errors, you can use decimal.Decimal objects:
"""
>>> rounded_tuple(('string 1', 1234.55555, 5.66666, 'string2'))
('string 1', Decimal('1234.56'), Decimal('5.67'), 'string2')
"""
from decimal import Decimal
def round_if_float(value):
if isinstance(value, float):
return Decimal(str(value)).quantize(Decimal('1.00'))
else:
return value
def rounded_tuple(tup):
return tuple(round_if_float(value) for value in tup)
rounded_tuple uses a generator expression inside a call to tuple.
| rounding-up numbers within a tuple | Is there anyway I could round-up numbers within a tuple to two decimal points,
from this:
('string 1', 1234.55555, 5.66666, 'string2')
to this:
('string 1', 1234.56, 5.67, 'string2')
Many thanks in advance.
| [
"If your tuple has a fixed size of 4 and the position of the floats is always the same, you can do this:\n>>> t = ('string 1', 1234.55555, 5.66666, 'string2')\n>>> t2 = (t[0], round(t[1], 2), round(t[2], 2), t[3])\n>>> t2\n('string 1', 1234.56, 5.67, 'string2')\n\nThe general solution would be:\n>>> t2 = tuple(map(... | [
14,
3,
1
] | [] | [] | [
"python"
] | stackoverflow_0003928523_python.txt |
Q:
How to print the top 10 users by the number of processes?
How could I print the top 10 users on a linux distribution by the number of processes they have running? I have managed to do this using a shell script, but now I'm interested at how I can do this using Python.
A:
Parsing the output of ps aux is not very pleasant, and can be tricky because the format is not guaranteed to be the same on all Linux systems.
Installing a third-party tool like psutil or PSI should make things easy and portable.
If you are looking for a Linux-only solution without installing a third-party module, then the following might help:
On modern Linux systems, all processes are listed in the /procs directory by their pid. The owner of the directory is the owner of the process.
import os
import stat
import pwd
import collections
import operator
os.chdir('/proc')
dirnames=(dirname for dirname in os.listdir('.') if dirname.isdigit())
statinfos=(os.stat(dirname) for dirname in dirnames)
uids=(statinfo[stat.ST_UID] for statinfo in statinfos)
names=(pwd.getpwuid(uid).pw_name for uid in uids)
counter=collections.defaultdict(int)
for name in names:
counter[name]+=1
count=counter.items()
count.sort(key=operator.itemgetter(1),reverse=True)
print('\n'.join(map(str,count[:10])))
yields
('root', 130)
('unutbu', 55)
('www-data', 7)
('avahi', 2)
('haldaemon', 2)
('daemon', 1)
('messagebus', 1)
('syslog', 1)
('Debian-exim', 1)
('mysql', 1)
| How to print the top 10 users by the number of processes? | How could I print the top 10 users on a linux distribution by the number of processes they have running? I have managed to do this using a shell script, but now I'm interested at how I can do this using Python.
| [
"Parsing the output of ps aux is not very pleasant, and can be tricky because the format is not guaranteed to be the same on all Linux systems. \nInstalling a third-party tool like psutil or PSI should make things easy and portable. \nIf you are looking for a Linux-only solution without installing a third-party mo... | [
2
] | [] | [] | [
"linux",
"process",
"python"
] | stackoverflow_0003928959_linux_process_python.txt |
Q:
Importing nested modules in Python
I'm trying to import a few libraries into my program (which is a google AppEngine application).
Basically, I'm supposed to put all libraries in the root folder, but I've just created another folder called lib and placed them within that folder. (I've created the __init__.py)
Imports regularly work fine by using the import lib.module or from lib import module, but what happens is that when I try to import a complete package, for instance a folder named pack1 with various modules in it, by calling from lib.pack1 import *, I get this error in one of the modules who has accessed another module statically, i.e. from pack1.mod2 import sth.
What is the easy and clean way to overcome this? Without modifying the libraries themselves.
Edit: Using Python 2.7.
Edit: Error: when using import lib.pack1, I get ImportError: No module named pack1.mod1.
A:
I think that instead of from pack1.mod2 you actually want to say from lib.pack1.mod2.
Edit: and, specifying what version of Python this is would help, since importation semantics have improved gradually over the years!
Edit: Aha! Thank you for your comment; I now understand. You are trying to rename libraries without going inside of them and fixing the fact that their name is now different. The problem is that what you are doing is, unfortunately, impossible. If all libraries used relative imports inside, then you might have some chance of doing it; but, alas, relative imports are both (a) recent and (b) not widely used.
So, if you want to use library p, then you are going to have to put it in your root directory, not inside of lib/p because that creates a library with a different name: lib.p, which is going to badly surprise the library and break it.
But I have two more thoughts.
First, if you are trying to do this to organize your files, and not because you need the import names to be different, then (a) create lib like you are doing but (b) do not put an __init__.py inside! Instead, add the lib directory to your PYTHONPATH or, inside of your program, to sys.path. (Does the GAE let you do something like this? Does it have a PYTHONPATH?)
Second, I am lying when I say this is not possible. Strictly speaking, you could probably do this by adding an entry to sys.metapath that intercepts all module lookups and tries grabbing them from inside of lib if they exist there. But — yuck.
| Importing nested modules in Python | I'm trying to import a few libraries into my program (which is a google AppEngine application).
Basically, I'm supposed to put all libraries in the root folder, but I've just created another folder called lib and placed them within that folder. (I've created the __init__.py)
Imports regularly work fine by using the import lib.module or from lib import module, but what happens is that when I try to import a complete package, for instance a folder named pack1 with various modules in it, by calling from lib.pack1 import *, I get this error in one of the modules who has accessed another module statically, i.e. from pack1.mod2 import sth.
What is the easy and clean way to overcome this? Without modifying the libraries themselves.
Edit: Using Python 2.7.
Edit: Error: when using import lib.pack1, I get ImportError: No module named pack1.mod1.
| [
"I think that instead of from pack1.mod2 you actually want to say from lib.pack1.mod2.\nEdit: and, specifying what version of Python this is would help, since importation semantics have improved gradually over the years!\nEdit: Aha! Thank you for your comment; I now understand. You are trying to rename libraries wi... | [
6
] | [] | [] | [
"import",
"module",
"python"
] | stackoverflow_0003929228_import_module_python.txt |
Q:
Is it possible to use reflection to examine a function's decorators in Python 2.5?
This is what i want to do:
@MyDecorator
def f():
pass
for d in f.decorators:
print d
A:
This is not generally possible without the cooperation of the decorators. For example,
def my_decorator(f):
def wrapper(*args, **kwargs):
return f(*args, **kwargs)
wrapper.decorators = [wrapper]
if hasattr(f, 'decorators'):
wrapper.decorators.extend[f.decorators]
return wrapper
Essentially, all the decorator does is wrap the function as usual and then put a decorators attribute on the wrapper function. It then checks the wrapped function for a similar list and propagates it upwards.
This is pretty useless though
What I think you want is
def my_decorator(f):
def wrapper(args):
return f(args)
wrapper.decorated = f
return wrapper
This will allow you to do stuff like
@my_other_decorator # another decorator following the same pattern
@my_decorator
def foo(args):
print args
foo.decorated(args) # calls the function with the inner decorated function (my_decorator)
foo.decorated.decorated(args) # original function
You can actually abstract this pattern into a decorator
def reversable(decorator):
def wrapper(func):
ret = decorator(func) # manually apply the decorator
ret.decorated = func # save the original function
return ret
return wrapper
Now when you are writing your decorator:
@reversable
def my_decorator(f):
def wrapper(x):
return f(x + 1)
return wrapper
A:
The @MyDecorator syntax is just shorthand for writing the following Python code:
def f():
pass
f = MyDecorator(f)
Written in this form, you can see that the decorators applied to the function are not kept track of in any way. You could make your decorators remember when they're applied (Aaron's answer has a couple good ideas on how to do this), but you'd have to wrap all third-party decorators with your own.
| Is it possible to use reflection to examine a function's decorators in Python 2.5? | This is what i want to do:
@MyDecorator
def f():
pass
for d in f.decorators:
print d
| [
"This is not generally possible without the cooperation of the decorators. For example,\ndef my_decorator(f):\n def wrapper(*args, **kwargs):\n return f(*args, **kwargs)\n wrapper.decorators = [wrapper]\n if hasattr(f, 'decorators'):\n wrapper.decorators.extend[f.decorators]\n return... | [
3,
1
] | [] | [] | [
"python"
] | stackoverflow_0003929317_python.txt |
Q:
Subprocess module errors with 'export' in python on linux?
I'm setting up a program to connect my computer to our schools proxy and currently have something like this:
import subprocess
import sys
username = 'fergus.barker'
password = '*************'
proxy = 'proxy.det.nsw.edu.au:8080'
options = '%s:%s@%s' % (username, password, proxy)
subprocess.Popen('export http_proxy=' + options)
But upon running I get:
Traceback (most recent call last):
File "school_proxy_settings.py", line 19, in <module>
subprocess.Popen('export http_proxy=' + options)
File "/usr/lib/python2.6/subprocess.py", line 621, in __init__
errread, errwrite)
File "/usr/lib/python2.6/subprocess.py", line 1126, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
Why is this happening please guys?
A:
The problem is that export is not an actual command or file. It is a built-in command to shells like bash and sh, so when you attempt a subprocess.Popen you will get an exception because it can not find the export command. By default Popen does an os.execvp() to spawn a new process, which would not allow you to use shell intrinsics.
You can do something like this, though you have to change your call to Popen.
http://docs.python.org/library/subprocess.html
You can specify shell=True to make it use shell commands.
class subprocess.Popen(args, bufsize=0, executable=None, stdin=None, stdout=None, stderr=None, preexec_fn=None, close_fds=False, shell=False, cwd=None, env=None, universal_newlines=False, startupinfo=None, creationflags=0)
On Unix, with shell=True: If args is a string, it specifies the command string to execute through the shell. This means that the string must be formatted exactly as it would be when typed at the shell prompt. This includes, for example, quoting or backslash escaping filenames with spaces in them. If args is a sequence, the first item specifies the command string, and any additional items will be treated as additional arguments to the shell itself. That is to say, Popen does the equivalent of:
Popen(['/bin/sh', '-c', args[0], args[1], ...])
A:
export is not a separate binary on your system, it is actually just a command within the shell itself. For example, try using which rm on your system. You'll probably see something like:
[21:16:28] ~ $ which rm
/bin/rm
Now try using which export. You'll get something like:
[21:16:37] ~ $ which export
/usr/bin/which: no export in (/usr/lib/qt-3.3/bin:/usr/kerberos/sbin:
/usr/kerberos/bin:/usr/lib/ccache:/usr/local/bin:/usr/bin:/bin:
/usr/local/sbin:/usr/sbin:/sbin:/home/carter/bin)
So you can't actually invoke an export process/subprocess by default. You may want to look at os.putenv() and os.environ() instead.
| Subprocess module errors with 'export' in python on linux? | I'm setting up a program to connect my computer to our schools proxy and currently have something like this:
import subprocess
import sys
username = 'fergus.barker'
password = '*************'
proxy = 'proxy.det.nsw.edu.au:8080'
options = '%s:%s@%s' % (username, password, proxy)
subprocess.Popen('export http_proxy=' + options)
But upon running I get:
Traceback (most recent call last):
File "school_proxy_settings.py", line 19, in <module>
subprocess.Popen('export http_proxy=' + options)
File "/usr/lib/python2.6/subprocess.py", line 621, in __init__
errread, errwrite)
File "/usr/lib/python2.6/subprocess.py", line 1126, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
Why is this happening please guys?
| [
"The problem is that export is not an actual command or file. It is a built-in command to shells like bash and sh, so when you attempt a subprocess.Popen you will get an exception because it can not find the export command. By default Popen does an os.execvp() to spawn a new process, which would not allow you to us... | [
11,
5
] | [] | [] | [
"python",
"subprocess"
] | stackoverflow_0003929319_python_subprocess.txt |
Q:
UTF-8 compatible compression in python
I'd like to include a large compressed string in a json packet, but am having some difficulty.
import json,bz2
myString = "A very large string"
zString = bz2.compress(myString)
json.dumps({ 'compressedData' : zString })
which will result in a
UnicodeDecodeError: 'utf8' codec can't decode bytes in position 10-13: invalid data
An obvious solution is bz2'ing the entire json structure, but let's just assume I'm using a blackbox api that does the json encoding and it wants a dict.
Also, I'm just using bz2 as an example, I don't really care what the actual algorithm is though I noticed the same behavior with zlib.
I can understand why these two compression libraries wouldn't create utf-8 compatible output, but is there any solution that can effectively compress utf-8 strings? This page seemed like a gold mine http://unicode.org/faq/compression.html but I couldn't find any relevant python information.
A:
Do you mean "compress to UTF-8 strings"? I'll assume that, since any generic compressor will compress UTF-8 strings. However, no real-world compressor is going to compress to a UTF-8 string.
You can't store 8-bit data like UTF-8 directly in JSON, because JSON strings are defined as Unicode. You'd have to base64-encode the data before giving it to JSON:
json.dumps({ 'compressedData' : base64.b64encode(zString) })
However, base64 inherently causes a 4/3 encoding overhead. If you're compressing typical string data you'll probably get enough compression for this to still be a win, but it's a significant overhead. You might find an encoding with a little less overhead, but not much.
Note that if you're using this to send data to a browser, you're better off letting HTTP compression do this; it's widely-supported and will be much more robust.
| UTF-8 compatible compression in python | I'd like to include a large compressed string in a json packet, but am having some difficulty.
import json,bz2
myString = "A very large string"
zString = bz2.compress(myString)
json.dumps({ 'compressedData' : zString })
which will result in a
UnicodeDecodeError: 'utf8' codec can't decode bytes in position 10-13: invalid data
An obvious solution is bz2'ing the entire json structure, but let's just assume I'm using a blackbox api that does the json encoding and it wants a dict.
Also, I'm just using bz2 as an example, I don't really care what the actual algorithm is though I noticed the same behavior with zlib.
I can understand why these two compression libraries wouldn't create utf-8 compatible output, but is there any solution that can effectively compress utf-8 strings? This page seemed like a gold mine http://unicode.org/faq/compression.html but I couldn't find any relevant python information.
| [
"Do you mean \"compress to UTF-8 strings\"? I'll assume that, since any generic compressor will compress UTF-8 strings. However, no real-world compressor is going to compress to a UTF-8 string.\nYou can't store 8-bit data like UTF-8 directly in JSON, because JSON strings are defined as Unicode. You'd have to bas... | [
11
] | [] | [] | [
"python",
"utf_8"
] | stackoverflow_0003929301_python_utf_8.txt |
Q:
python for loop, how to find next value(object)?
HI, I'm trying to use for loop to find the difference between every two object by minus each other.
So, how can I find the next value in a for loop?
for entry in entries:
first = entry # Present value
last = ?????? # The last value how to say?
diff = last = first
A:
It should be noted that none of these solutions work for generators. For that see Glenn Maynards superior solution.
use zip for small lists:
for current, last in zip(entries[1:], entries):
diff = current - last
This makes a copy of the list (and a list of tuples from both copies of the list) so it's good to use itertools for handling larger lists
import itertools as it
items = it.izip(it.islice(entries, 1, None), entries)
for current, last in items:
diff = current - last
This will avoid both making a copy of the list and making a list of tuples.
Another way to do it without making a copy is
entry_iter = iter(entries)
entry_iter.next() # Throw away the first version
for i, entry in enumerate(entry_iter):
diff = entry - entries[i]
And yet another way is:
for i in xrange(len(entries) - 1):
diff = entries[i+1] - entries[i]
This creates an iterator that indexes entries and advances it by one. It then uses enumerate to get an indice with the item. The indice starts at 0 and so points to the previous element because we the loop one item in.
Also, as Tyler pointed out in the comment, a loop might be overkill for such a simple problem if you just want to iterate over the differences.
diffs = (current - last for current, last in
it.izip(it.islice(entries, 1, None), entries))
A:
zip works for lists, but for the general case:
def pairs(it):
it = iter(it)
prev = next(it)
for v in it:
yield prev, v
prev = v
a = [1,2,3,4,5]
for prev, cur in pairs(a):
print cur - prev
import itertools as it
for prev, cur in pairs(it.cycle([1,2,3,4])):
print cur - prev
This works efficiently for large containers, and more importantly, it works for iterators:
for prev, cur in pairs(open("/usr/share/dict/words").xreadlines()):
print cur, prev,
Edit: I changed the generator to omit the first value with no previous value, since that fits the original question better ("finding differences between adjacent pairs"), and I added an example case showing that it works for an infinitely-repeating iterator.
A:
i don't know exactly what are you looking but maybe this can help :
first = entries[0]
for entry in entries[1:]:
last = entry
diff = last - first
first = entry
A:
very simply, using enumerate, no fancy stuff
>>> entries=[10,20,30,40]
>>> for n,i in enumerate(entries):
... try:
... print entries[n+1] - i
... except IndexError:
... print entries[-1]
...
10
10
10
40
| python for loop, how to find next value(object)? | HI, I'm trying to use for loop to find the difference between every two object by minus each other.
So, how can I find the next value in a for loop?
for entry in entries:
first = entry # Present value
last = ?????? # The last value how to say?
diff = last = first
| [
"It should be noted that none of these solutions work for generators. For that see Glenn Maynards superior solution.\nuse zip for small lists:\n for current, last in zip(entries[1:], entries):\n diff = current - last\n\nThis makes a copy of the list (and a list of tuples from both copies of the list) so it's go... | [
12,
6,
1,
0
] | [] | [] | [
"for_loop",
"python"
] | stackoverflow_0003929039_for_loop_python.txt |
Q:
Subclassing file class in Python raises NameError
I have to do a very simple project in python where I add error checking to the built in file class. So far, I've got:
class RobustFile(file):
def __init__(self,name,mode):
file.__init__(self,name,mode)
I'm just starting out, but to make sure I hadn't messed anything up, I ran it. Well, right off the bat, I raised a NameError because it didn't recognize file. I tried tweaking it, I looked it up on the internet, I copied examples using the same format, and...all NameError. Can anyone shed some light on how exactly to subclass file?
A:
You're probably using Python 3, which no longer has a file type.
Instead, as noted in the Python 3 documentation's I/O Overview, it has a number of different stream types that are all derived from one of _io.TextIOBase, _io.BufferedIOBase, or _io.RawIOBase, which are themselves derived from _io.IOBase.
A:
Works fine in python 2.6.6:
In [44]: class RobustFile(file):
def __init__(self,name,mode):
file.__init__(self,name,mode)
....:
In [47]: fp = RobustFile('foo','w')
In [48]: fp.writelines('bar')
In [49]: fp.close()
| Subclassing file class in Python raises NameError | I have to do a very simple project in python where I add error checking to the built in file class. So far, I've got:
class RobustFile(file):
def __init__(self,name,mode):
file.__init__(self,name,mode)
I'm just starting out, but to make sure I hadn't messed anything up, I ran it. Well, right off the bat, I raised a NameError because it didn't recognize file. I tried tweaking it, I looked it up on the internet, I copied examples using the same format, and...all NameError. Can anyone shed some light on how exactly to subclass file?
| [
"You're probably using Python 3, which no longer has a file type.\nInstead, as noted in the Python 3 documentation's I/O Overview, it has a number of different stream types that are all derived from one of _io.TextIOBase, _io.BufferedIOBase, or _io.RawIOBase, which are themselves derived from _io.IOBase.\n",
"Wor... | [
7,
1
] | [] | [] | [
"file",
"python",
"subclass"
] | stackoverflow_0003929646_file_python_subclass.txt |
Q:
Insert multiple tab-delimited text files into MySQL with Python?
I am trying to create a program that takes a number of tab delaminated text files, and works through them one at a time entering the data they hold into a MySQL database. There are several text files, like movies.txt which looks like this:
1 Avatar
3 Iron Man
3 Star Trek
and actors.txt that looks the same etc. Each text file has upwards of one hundred entries each with an id and corresponding value as seen above. I have found a number of code examples on this site and others but I can't quite get my head around how to implement them in this situation.
So far my code looks something like this ...
import MySQLdb
database_connection = MySQLdb.connect(host='localhost', user='root', passwd='')
cursor = database_connection.cursor()
cursor.execute('CREATE DATABASE library')
cursor.execute('USE library')
cursor.execute('''CREATE TABLE popularity (
PersonNumber INT,
Category VARCHAR(25),
Value VARCHAR(60),
)
''')
def data_entry(categories):
Everytime i try to get the other code I have found working with this I just get lost completely. Hopeing someone can help me out by either showing me what I need to do or pointing me in the direction of some more information.
Examples of the code I have been trying to adapt to my situation are:
import MySQLdb, csv, sys
conn = MySQLdb.connect (host = "localhost",user = "usr", passwd = "pass",db = "databasename")
c = conn.cursor()
csv_data=csv.reader(file("a.txt"))
for row in csv_data:
print row
c.execute("INSERT INTO a (first, last) VALUES (%s, %s), row")
c.commit()
c.close()
and:
Python File Read + Write
A:
MySQL can read TSV files directly using the mysqlimport utility or by executing the LOAD DATA INFILE SQL command. This will be faster than processing the file in python and inserting it, but you may want to learn how to do both. Good luck!
| Insert multiple tab-delimited text files into MySQL with Python? | I am trying to create a program that takes a number of tab delaminated text files, and works through them one at a time entering the data they hold into a MySQL database. There are several text files, like movies.txt which looks like this:
1 Avatar
3 Iron Man
3 Star Trek
and actors.txt that looks the same etc. Each text file has upwards of one hundred entries each with an id and corresponding value as seen above. I have found a number of code examples on this site and others but I can't quite get my head around how to implement them in this situation.
So far my code looks something like this ...
import MySQLdb
database_connection = MySQLdb.connect(host='localhost', user='root', passwd='')
cursor = database_connection.cursor()
cursor.execute('CREATE DATABASE library')
cursor.execute('USE library')
cursor.execute('''CREATE TABLE popularity (
PersonNumber INT,
Category VARCHAR(25),
Value VARCHAR(60),
)
''')
def data_entry(categories):
Everytime i try to get the other code I have found working with this I just get lost completely. Hopeing someone can help me out by either showing me what I need to do or pointing me in the direction of some more information.
Examples of the code I have been trying to adapt to my situation are:
import MySQLdb, csv, sys
conn = MySQLdb.connect (host = "localhost",user = "usr", passwd = "pass",db = "databasename")
c = conn.cursor()
csv_data=csv.reader(file("a.txt"))
for row in csv_data:
print row
c.execute("INSERT INTO a (first, last) VALUES (%s, %s), row")
c.commit()
c.close()
and:
Python File Read + Write
| [
"MySQL can read TSV files directly using the mysqlimport utility or by executing the LOAD DATA INFILE SQL command. This will be faster than processing the file in python and inserting it, but you may want to learn how to do both. Good luck!\n"
] | [
1
] | [] | [] | [
"mysql",
"python"
] | stackoverflow_0003929297_mysql_python.txt |
Q:
Python Unicode CSV export (using Django)
I'm using a Django app to export a string to a CSV file. The string is a message that was submitted through a front end form. However, I've been getting this error when a unicode single quote is provided in the input.
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2019'
in position 200: ordinal not in range(128)
I've been trying to convert the unicode to ascii using the code below, but still get a similar error.
UnicodeEncodeError: 'ascii' codec can't encode characters in
position 0-9: ordinal not in range(128)
I've sifted through dozens of websites and learned a lot about unicode, however, I'm still not able to convert this unicode to ascii. I don't care if the algorithm removes the unicode characters. The commented lines indicate some various options I've tried, but the error persists.
import csv
import unicodedata
...
#message = unicode( unicodedata.normalize(
# 'NFKD',contact.message).encode('ascii','ignore'))
#dmessage = (contact.message).encode('utf-8','ignore')
#dmessage = contact.message.decode("utf-8")
#dmessage = "%s" % dmessage
dmessage = contact.message
csv_writer.writerow([
dmessage,
])
Does anyone have any advice in removing unicode characters to I can export them to CSV? This seemingly easy problem has kept my head spinning. Any help is much appreciated.
Thanks,
Joe
A:
You can't encode the Unicode character u'\u2019' (U+2019 Right Single Quotation Mark) into ASCII, because ASCII doesn't have that character in it. ASCII is only the basic Latin alphabet, digits and punctuation; you don't get any accented letters or ‘smart quotes’ like this character.
So you will have to choose another encoding. Now normally the sensible thing to do would be to export to UTF-8, which can hold any Unicode character. Unfortunately for you if your target users are using Office (and they probably are), they're not going to be able to read UTF-8-encoded characters in CSV. Instead Excel will read the files using the system default code page for that machine (also misleadingly known as the ‘ANSI’ code page), and end up with mojibake like ’ instead of ’.
So that means you have to guess the user's system default code page if you want the characters to show up correctly. For Western users, that will be code page 1252. Users with non-Western Windows installs will see the wrong characters, but there's nothing you can do about that (other than organise a letter-writing campaign to Microsoft to just drop the stupid nonsense with ANSI already and use UTF-8 like everyone else).
Code page 1252 can contain U+2019 (’), but obviously there are many more characters it can't represent. To avoid getting UnicodeEncodeError for those characters you can use the ignore argument (or replace to replace them with question marks).
dmessage= contact.message.encode('cp1252', 'ignore')
alternatively, to give up and remove all non-ASCII characters, so that everyone gets an equally bad experience regardless of locale:
dmessage= contact.message.encode('ascii', 'ignore')
A:
Encoding is a pain, but if you're working in django have you tried smart_unicode(str) from django.utils.encoding? I find that usually does the trick.
The only other option I've found is to use the built-in python encode() and decode() for strings, but you have to specify the encoding for those and honestly, it's a pain.
A:
[caveat: I'm not a djangoist; django may have a better solution].
General non-django-specific answer:
If you have a smallish number of known non-ASCII characters and there are user-acceptable ASCII equivalents for them, you can set up a translation table and use the unicode.translate method:
smashcii = {
0x2019 : u"'",
# etc
#
smashed = input_string.translate(smashcii)
| Python Unicode CSV export (using Django) | I'm using a Django app to export a string to a CSV file. The string is a message that was submitted through a front end form. However, I've been getting this error when a unicode single quote is provided in the input.
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2019'
in position 200: ordinal not in range(128)
I've been trying to convert the unicode to ascii using the code below, but still get a similar error.
UnicodeEncodeError: 'ascii' codec can't encode characters in
position 0-9: ordinal not in range(128)
I've sifted through dozens of websites and learned a lot about unicode, however, I'm still not able to convert this unicode to ascii. I don't care if the algorithm removes the unicode characters. The commented lines indicate some various options I've tried, but the error persists.
import csv
import unicodedata
...
#message = unicode( unicodedata.normalize(
# 'NFKD',contact.message).encode('ascii','ignore'))
#dmessage = (contact.message).encode('utf-8','ignore')
#dmessage = contact.message.decode("utf-8")
#dmessage = "%s" % dmessage
dmessage = contact.message
csv_writer.writerow([
dmessage,
])
Does anyone have any advice in removing unicode characters to I can export them to CSV? This seemingly easy problem has kept my head spinning. Any help is much appreciated.
Thanks,
Joe
| [
"You can't encode the Unicode character u'\\u2019' (U+2019 Right Single Quotation Mark) into ASCII, because ASCII doesn't have that character in it. ASCII is only the basic Latin alphabet, digits and punctuation; you don't get any accented letters or ‘smart quotes’ like this character.\nSo you will have to choose a... | [
7,
2,
1
] | [] | [] | [
"ascii",
"csv",
"python",
"unicode",
"utf_8"
] | stackoverflow_0003929327_ascii_csv_python_unicode_utf_8.txt |
Q:
password fetch using python
import pwd
import operator
# Load all of the user data, sorted by username
all_user_data = pwd.getpwall()
interesting_users = sorted((u
for u in all_user_data
if not u.pw_name.startswith('_')),
key=operator.attrgetter('pw_name'))
# Find the longest lengths for a few fields
username_length = max(len(u.pw_name) for u in interesting_users) + 1
home_length = max(len(u.pw_dir) for u in interesting_users) + 1
# Print report headers
fmt = '%-*s %4s %-*s %s'
print fmt % (username_length, 'User',
'UID',
home_length, 'Home Dir',
'Description')
print '-' * username_length, '----', '-' * home_length, '-' * 30
# Print the data
for u in interesting_users:
print fmt % (username_length, u.pw_name,
u.pw_uid,
home_length, u.pw_dir,
u.pw_gecos)
the above program fetch password from linux password file,
i want to create the program which shows linux kernel file which maintain logs of user login.
how to get into the kernel please help.......
A:
Look at wtmp and utmp. There are APIs - check man wtmp
| password fetch using python | import pwd
import operator
# Load all of the user data, sorted by username
all_user_data = pwd.getpwall()
interesting_users = sorted((u
for u in all_user_data
if not u.pw_name.startswith('_')),
key=operator.attrgetter('pw_name'))
# Find the longest lengths for a few fields
username_length = max(len(u.pw_name) for u in interesting_users) + 1
home_length = max(len(u.pw_dir) for u in interesting_users) + 1
# Print report headers
fmt = '%-*s %4s %-*s %s'
print fmt % (username_length, 'User',
'UID',
home_length, 'Home Dir',
'Description')
print '-' * username_length, '----', '-' * home_length, '-' * 30
# Print the data
for u in interesting_users:
print fmt % (username_length, u.pw_name,
u.pw_uid,
home_length, u.pw_dir,
u.pw_gecos)
the above program fetch password from linux password file,
i want to create the program which shows linux kernel file which maintain logs of user login.
how to get into the kernel please help.......
| [
"Look at wtmp and utmp. There are APIs - check man wtmp\n"
] | [
1
] | [] | [] | [
"linux",
"passwords",
"python"
] | stackoverflow_0003873128_linux_passwords_python.txt |
Q:
Twitter Authentication Questions
I have two questions (does that violate etiquette?) surrounding Twitter authentication.
The first question is this. I'd like to store the access token that I receive but it is a dictionary object. Do I store the whole dictionary object or just some of the pertinent parts.
Secondly I'd like to know how to log the user out. I found this link that would help log a user out of Facebook - is there anything similar to this for Twitter (or is this logout method a bad idea) http://m.facebook.com/logout.php?confirm=1&next=
A:
What you need to understand is that the OAuth protocol does not define "login" and "logout" concepts, those are inherent to your application. OAuth is a protocol to allow a consumer (your application) to access a resource owner's (one of your users) data stored by a resource provider (in this case, Twitter).
Do I store the whole dictionary object or just some of the pertinent parts.
As far as I know, you only need to store the access token to be able to continue making inquiries to the server for the resources you requested (requesting new resources might require getting another access token). Keep in mind that this token may expire, and may be revoked at any time by the user directly through Twitter, and without your knowledge. This is by design in OAuth.
I'd like to know how to log the user out
There is no "session" in OAuth, that is a concept relevant to your application.
A:
You need the access token key and secret to be able to access the API. It doesn't really matter how you store it as long as you store it somehow. The application you are giving access will have a way of storing the data. Unless you are creating a new OAuth application or adding support to an existing application. In which case you will want to store the key and secret using whatever key/value system that is idiomatic (the right way) for that language (i.e. pickling, or config file for python).
The consumer (application) that is given the key and secret will have access to twitter on the user's behalf.
To revoke a particular access key, you login to twitter as the user and go to http://twitter.com/settings/connections. Each application that has a valid access token is listed on that page and can be revoked. Consumers are not really ever logged in like users are, they authenticate using the access key and secret.
| Twitter Authentication Questions | I have two questions (does that violate etiquette?) surrounding Twitter authentication.
The first question is this. I'd like to store the access token that I receive but it is a dictionary object. Do I store the whole dictionary object or just some of the pertinent parts.
Secondly I'd like to know how to log the user out. I found this link that would help log a user out of Facebook - is there anything similar to this for Twitter (or is this logout method a bad idea) http://m.facebook.com/logout.php?confirm=1&next=
| [
"What you need to understand is that the OAuth protocol does not define \"login\" and \"logout\" concepts, those are inherent to your application. OAuth is a protocol to allow a consumer (your application) to access a resource owner's (one of your users) data stored by a resource provider (in this case, Twitter).\n... | [
2,
1
] | [] | [] | [
"oauth",
"python",
"twitter"
] | stackoverflow_0003929990_oauth_python_twitter.txt |
Q:
PyObjc vs RubyCocoa for Mac development: Which is more mature?
I've been wanting to have a play with either Ruby or Python while at the same time I've been wanting to do a bit of Cocoa programming.
So I thought the best way to achieve both these goals is to develop something using either a Ruby or Python to Objective-C bridge (PyObjc or RubyCocoa).
I know that ideally to get the best learning experience I would learn each techonology independently but I don't have the time. :)
So my question is which is a more mature platform, PyObc or RubyCocoa, main things I am looking for:
Documentation of API
Tutorials
Tools
Supportive Community
Completness of Cocoa API avaialble through the bridge
Regarding point 5 I don't expect that the entire Cocoa API will be availble through either bridge but I need to have enough Cocoa APIs available to develop a functioning application.
A:
While you say you "don't have time" to learn technologies independently the fastest route to learning Cocoa will still be to learn it in its native language: Objective-C. Once you understand Objective-C and have gotten over the initial learning curve of the Cocoa frameworks you'll have a much easier time picking up either PyObjC or RubyCocoa.
A:
I would echo Chris' assesment and will expand a bit on why you should learn Objective-C to learn Cocoa. As Chris says, Objective-C is the foundation and native language of Cocoa and many of its paradigms are inextricably linked with that lineage. In particular, selectors and dynamic message resolution and ability to modify classes at run time are required to implement Cocoa technologies such as Distributed Objects and bindings. Although these features are available in other dynamic languages such as Ruby and Python, there is enough of a mismatch in the language models that you will have to at least understand Objective-C to understand Cocoa. I suggest you take a look at this previous question for further discussion: Do I have to learn Objective-C for professional Mac Development?
Fortunately, Objective-C is very easy to learn. I often tell people it will take them a day to learn Objective-C coming from C/C++/Java or LISP, Scheme, or any of the 'newer' dynamic languages such as Ruby and Python. In addition to expanding your mind a bit, you'll learn to at least read the code that is used in virtually all of the Cocoa documentation and examples.
As for Ruby vs. Python, the bridge capabilities are very similar. In fact, they both use Apple's BridgeSupport (shipped with Leopard) to provide the bridge description. Both are supported by Apple and ship with Leopard. It's a matter of personal taste which language you prefer. If you choose Ruby, I suggest you give MacRuby a look. It's definitely the future of Ruby on OS X, as it reimplements the Ruby runtime on top of the Objective-C run time. This provides some nice performance and conceptual advantages (including integration with the Objective-C garbage collection system, a feature currently lacking in PyObjC which uses the native python gc). MacRuby also includes a custom parser that makes the syntax of bridged objective-c methods a little nicer. The downside of MacRuby is that it's not quite ready for production-level use at the time of this writing (June 2009). Since it sounds like this is a learning project for you, that's probably not an issue.
A:
Both are roughly equal, I'd say. Better in some places, worse in others. But I wouldn't recommend learning Cocoa with either. Like Chris said, Cocoa requires some understanding of Objective-C. I like Ruby better than Objective-C, but I still don't recommend using it to learn Cocoa. Once you have a solid foundation (no pun intended) in Cocoa/Objective-C, then the bridges can be useful to you.
A:
Apple seems to be getting behind Ruby scripting for Cocoa but not RubyCocoa. They are hosting and I believe supporting MacRuby. I often wonder if MacRuby is Apple's answer to a higher level language for OSX prototyping and full on application development.
A:
ObjectiveC is nowhere near as much fun or as productive as either Python or Ruby. That is why people want to pick a python or ruby with good Objective C access. Advising them to learn Objective C first misses the point imo. I have really good things to say about pyobjc. Its ability to interoperate painlessly with Objective C frameworks is superb. I have less experience with Ruby Cocoa and that was partly because when I last looked it didn't seem to have as clean and relatively painless interoperability. I feel hesitant about MacRuby because it seems to go too far. In pyobjc you can write plain python and only subclass/use Foundation and Cocoa objects when you really want/mean to. From what I understand of MacRuby it is a Ruby on top of Cocoa. So a string is always an NSString. I am less happy with that. YMMV.
| PyObjc vs RubyCocoa for Mac development: Which is more mature? | I've been wanting to have a play with either Ruby or Python while at the same time I've been wanting to do a bit of Cocoa programming.
So I thought the best way to achieve both these goals is to develop something using either a Ruby or Python to Objective-C bridge (PyObjc or RubyCocoa).
I know that ideally to get the best learning experience I would learn each techonology independently but I don't have the time. :)
So my question is which is a more mature platform, PyObc or RubyCocoa, main things I am looking for:
Documentation of API
Tutorials
Tools
Supportive Community
Completness of Cocoa API avaialble through the bridge
Regarding point 5 I don't expect that the entire Cocoa API will be availble through either bridge but I need to have enough Cocoa APIs available to develop a functioning application.
| [
"While you say you \"don't have time\" to learn technologies independently the fastest route to learning Cocoa will still be to learn it in its native language: Objective-C. Once you understand Objective-C and have gotten over the initial learning curve of the Cocoa frameworks you'll have a much easier time pickin... | [
12,
7,
3,
1,
1
] | [] | [] | [
"cocoa",
"pyobjc",
"python",
"ruby",
"ruby_cocoa"
] | stackoverflow_0000426607_cocoa_pyobjc_python_ruby_ruby_cocoa.txt |
Q:
500 Error when sending file from python to django
I've found a nice python module for sending data to remote servers via HTTP POST called poster. So I've wrote a simple view on my django app to receive and store data and then tried to send some file. Unfortunately even though I've set everything as it was shown in the instruction I'm getting Internal Server Error. Can anyone maybe see what am I doing wrong ?
Here's the view function :
def upload(request):
for key, file in request.FILES.items():
path = '/site_media/remote/'+ file.name
dest = open(path.encode('utf-8'), 'wb+')
if file.multiple_chunks:
for c in file.chunks():
dest.write(c)
else:
dest.write(file.read())
dest.close()
Here's the module instruction : http://atlee.ca/software/poster/ and some instruction I was basing on http://www.laurentluce.com/?p=20
Here's the traceback:
In [15]: print urllib2.urlopen(request).read()
-------> print(urllib2.urlopen(request).read())
---------------------------------------------------------------------------
HTTPError Traceback (most recent call last)
/home/rails/ntt/<ipython console> in <module>()
/bin/python-2.6.2/lib/python2.6/urllib2.pyc in urlopen(url, data, timeout)
122 if _opener is None:
123 _opener = build_opener()
--> 124 return _opener.open(url, data, timeout)
125
126 def install_opener(opener):
/bin/python-2.6.2/lib/python2.6/urllib2.pyc in open(self, fullurl, data, timeout)
387 for processor in self.process_response.get(protocol, []):
388 meth = getattr(processor, meth_name)
--> 389 response = meth(req, response)
390
391 return response
/bin/python-2.6.2/lib/python2.6/urllib2.pyc in http_response(self, request, response)
500 if not (200 <= code < 300):
501 response = self.parent.error(
--> 502 'http', request, response, code, msg, hdrs)
503
504 return response
/bin/python-2.6.2/lib/python2.6/urllib2.pyc in error(self, proto, *args)
425 if http_err:
426 args = (dict, 'default', 'http_error_default') + orig_args
--> 427 return self._call_chain(*args)
428
429 # XXX probably also want an abstract factory that knows when it makes
/bin/python-2.6.2/lib/python2.6/urllib2.pyc in _call_chain(self, chain, kind, meth_name, *args)
359 func = getattr(handler, meth_name)
360
--> 361 result = func(*args)
362 if result is not None:
363 return result
/bin/python-2.6.2/lib/python2.6/urllib2.pyc in http_error_default(self, req, fp, code, msg, hdrs)
508 class HTTPDefaultErrorHandler(BaseHandler):
509 def http_error_default(self, req, fp, code, msg, hdrs):
--> 510 raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
511
512 class HTTPRedirectHandler(BaseHandler):
HTTPError: HTTP Error 500: Internal Server Error
I get the same error when I'm trying to send my file to a php function (from www.w3schools.com/php/php_file_upload.asp
Also I've checked with wireshark and my POST request is sent without any problems but then something bad happens and I'm getting this 500. May it be that the server is somehow limited ? Uploading files in applications running on it works fluently.
Placing this view function with url on different server, and running :
import httplib
conn = httplib.HTTPConnection("address")
f = open("file, "rb")
conn.request("POST","/upload", f, headers)
response = conn.getresponse()
Raised : BadStatusLine exception.
A:
This is a basic Python question. You need to import a module before you can use it. So just do import urllib at the top of the script and it should work.
| 500 Error when sending file from python to django | I've found a nice python module for sending data to remote servers via HTTP POST called poster. So I've wrote a simple view on my django app to receive and store data and then tried to send some file. Unfortunately even though I've set everything as it was shown in the instruction I'm getting Internal Server Error. Can anyone maybe see what am I doing wrong ?
Here's the view function :
def upload(request):
for key, file in request.FILES.items():
path = '/site_media/remote/'+ file.name
dest = open(path.encode('utf-8'), 'wb+')
if file.multiple_chunks:
for c in file.chunks():
dest.write(c)
else:
dest.write(file.read())
dest.close()
Here's the module instruction : http://atlee.ca/software/poster/ and some instruction I was basing on http://www.laurentluce.com/?p=20
Here's the traceback:
In [15]: print urllib2.urlopen(request).read()
-------> print(urllib2.urlopen(request).read())
---------------------------------------------------------------------------
HTTPError Traceback (most recent call last)
/home/rails/ntt/<ipython console> in <module>()
/bin/python-2.6.2/lib/python2.6/urllib2.pyc in urlopen(url, data, timeout)
122 if _opener is None:
123 _opener = build_opener()
--> 124 return _opener.open(url, data, timeout)
125
126 def install_opener(opener):
/bin/python-2.6.2/lib/python2.6/urllib2.pyc in open(self, fullurl, data, timeout)
387 for processor in self.process_response.get(protocol, []):
388 meth = getattr(processor, meth_name)
--> 389 response = meth(req, response)
390
391 return response
/bin/python-2.6.2/lib/python2.6/urllib2.pyc in http_response(self, request, response)
500 if not (200 <= code < 300):
501 response = self.parent.error(
--> 502 'http', request, response, code, msg, hdrs)
503
504 return response
/bin/python-2.6.2/lib/python2.6/urllib2.pyc in error(self, proto, *args)
425 if http_err:
426 args = (dict, 'default', 'http_error_default') + orig_args
--> 427 return self._call_chain(*args)
428
429 # XXX probably also want an abstract factory that knows when it makes
/bin/python-2.6.2/lib/python2.6/urllib2.pyc in _call_chain(self, chain, kind, meth_name, *args)
359 func = getattr(handler, meth_name)
360
--> 361 result = func(*args)
362 if result is not None:
363 return result
/bin/python-2.6.2/lib/python2.6/urllib2.pyc in http_error_default(self, req, fp, code, msg, hdrs)
508 class HTTPDefaultErrorHandler(BaseHandler):
509 def http_error_default(self, req, fp, code, msg, hdrs):
--> 510 raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
511
512 class HTTPRedirectHandler(BaseHandler):
HTTPError: HTTP Error 500: Internal Server Error
I get the same error when I'm trying to send my file to a php function (from www.w3schools.com/php/php_file_upload.asp
Also I've checked with wireshark and my POST request is sent without any problems but then something bad happens and I'm getting this 500. May it be that the server is somehow limited ? Uploading files in applications running on it works fluently.
Placing this view function with url on different server, and running :
import httplib
conn = httplib.HTTPConnection("address")
f = open("file, "rb")
conn.request("POST","/upload", f, headers)
response = conn.getresponse()
Raised : BadStatusLine exception.
| [
"This is a basic Python question. You need to import a module before you can use it. So just do import urllib at the top of the script and it should work.\n"
] | [
3
] | [] | [] | [
"django",
"file_upload",
"http",
"python"
] | stackoverflow_0003928950_django_file_upload_http_python.txt |
Q:
Localization of Django application only applies to forms.py and not to models.py
I have a problem when trying to localize my application. It is available in two languages: english and german. The problem appears when the browser has the language set english(United States) and in my settings file is set to 'de' and vice-versa. Some fields appear in english, others in german. My model contains CharField, DecimalField and DateField field types.
models.py:
from django.db import models
from django.utils.translation import ugettext as _
class Test(models.Model):
test_number = models.CharField(_('Test number'), max_length=20)
test_date = models.DateField()
test_price = models.DecimalField(_('Test price'), max_digits=16, decimal_places=2, null=True, blank=True)
forms.py:
class TestForm(ModelForm):
test_date = forms.DateField(label=_('Booking date'), widget=AdminDateWidget)
settings.py
USE_L10N = True
USE_I18N = True
TIME_ZONE = 'Europe/Berlin'
LANGUAGE_CODE = 'de'
TEMPLATE_CONTEXT_PROCESSORS = (
"django.core.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.media",
"django.core.context_processors.request",
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.core.files.uploadhandler.MemoryFileUploadHandler',
'django.core.files.uploadhandler.TemporaryFileUploadHandler',
'django.middleware.transaction.TransactionMiddleware',
'pagination.middleware.PaginationMiddleware',
)
English is the language set the browser.The labels of the fields test_number and test_price appear in german and the label of test_date in english. If I remove _('Test number') from models.py and added it as label attribute in forms.py it works. Isn't it another way of doing this?
A:
Changing the declaration "from django.utils.translation import ugettext as _" to "from django.utils.translation import ugettext_lazy as _" seems to solve the problem.
A:
Doublecheck your .po file: it shouldn't have any 'fuzzy' status.
| Localization of Django application only applies to forms.py and not to models.py | I have a problem when trying to localize my application. It is available in two languages: english and german. The problem appears when the browser has the language set english(United States) and in my settings file is set to 'de' and vice-versa. Some fields appear in english, others in german. My model contains CharField, DecimalField and DateField field types.
models.py:
from django.db import models
from django.utils.translation import ugettext as _
class Test(models.Model):
test_number = models.CharField(_('Test number'), max_length=20)
test_date = models.DateField()
test_price = models.DecimalField(_('Test price'), max_digits=16, decimal_places=2, null=True, blank=True)
forms.py:
class TestForm(ModelForm):
test_date = forms.DateField(label=_('Booking date'), widget=AdminDateWidget)
settings.py
USE_L10N = True
USE_I18N = True
TIME_ZONE = 'Europe/Berlin'
LANGUAGE_CODE = 'de'
TEMPLATE_CONTEXT_PROCESSORS = (
"django.core.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.media",
"django.core.context_processors.request",
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.core.files.uploadhandler.MemoryFileUploadHandler',
'django.core.files.uploadhandler.TemporaryFileUploadHandler',
'django.middleware.transaction.TransactionMiddleware',
'pagination.middleware.PaginationMiddleware',
)
English is the language set the browser.The labels of the fields test_number and test_price appear in german and the label of test_date in english. If I remove _('Test number') from models.py and added it as label attribute in forms.py it works. Isn't it another way of doing this?
| [
"Changing the declaration \"from django.utils.translation import ugettext as _\" to \"from django.utils.translation import ugettext_lazy as _\" seems to solve the problem.\n",
"Doublecheck your .po file: it shouldn't have any 'fuzzy' status.\n"
] | [
2,
0
] | [] | [] | [
"django",
"localization",
"modelform",
"models",
"python"
] | stackoverflow_0003905690_django_localization_modelform_models_python.txt |
Q:
Monkey patching a Django form class?
Given a form class (somewhere deep in your giant Django app)..
class ContactForm(forms.Form):
name = ...
surname = ...
And considering you want to add another field to this form without extending or modifying the form class itself, why does not the following approach work?
ContactForm.another_field = forms.CharField(...)
(My first guess is that the metaclass hackery that Django uses applies only the first time the form class is constructed. If so, would there be a way to redeclare the class to overcome this?)
A:
Some pertinent definitions occur in django/forms/forms.py. They are:
class BaseForm
class Form
class DeclarativeFieldsMetaclass
def get_declared_fields
get_declared_fields is called from DeclarativeFieldsMetaclass and constructs a list with the field instances sorted by their creation counter. It then prepends fields from the base classes to this list and returns the result as an OrderedDict instance with the field name serving as the keys. DeclarativeFieldsMetaclass then sticks this value in the attribute base_fields and calls to type to construct the class. It then passes the class to the media_property function in widgets.py and attaches the return value to the media attribute on the new class.
media_property returns a property method that reconstructs the media declarations on every access. My feeling is that it wont be relevant here but I could be wrong.
At any rate, if you are not declaring a Media attribute (and none of the base classes do) then it only returns a fresh Media instance with no arguments to the constructor and I think that monkeypatching a new field on should be as simple as manually inserting the field into base_fields.
ContactForm.another_field = forms.CharField(...)
ContactForm.base_fields['another_field'] = ContactForm.another_field
Each form instance then gets a deepcopy of base_fields that becomes form_instance.fields in the __init__ method of BaseForm. HTH.
| Monkey patching a Django form class? | Given a form class (somewhere deep in your giant Django app)..
class ContactForm(forms.Form):
name = ...
surname = ...
And considering you want to add another field to this form without extending or modifying the form class itself, why does not the following approach work?
ContactForm.another_field = forms.CharField(...)
(My first guess is that the metaclass hackery that Django uses applies only the first time the form class is constructed. If so, would there be a way to redeclare the class to overcome this?)
| [
"Some pertinent definitions occur in django/forms/forms.py. They are:\n\nclass BaseForm\nclass Form\nclass DeclarativeFieldsMetaclass\ndef get_declared_fields\n\nget_declared_fields is called from DeclarativeFieldsMetaclass and constructs a list with the field instances sorted by their creation counter. It then pre... | [
9
] | [] | [] | [
"django",
"django_forms",
"monkeypatching",
"python"
] | stackoverflow_0003930512_django_django_forms_monkeypatching_python.txt |
Q:
In python, any elegant way to refer to class method within the classes declaration scope?
The below code works both under Python 2.6 and 3.1, but the third lambda of SomeObject.columns is a bit silly, serving no real purpose but to prevent the reference to SomeObject.helper_function from being looked at before the class declaration finishes. It seems like a hack. If I remove the lambda, and replace it with just SomeObject.helper_function, I get NameError: name 'SomeObject' is not defined. Am I missing a better non-hacky way?
class SomeObject:
def __init__(self, values):
self.values = values
@staticmethod
def helper_function(row):
# do something fancy here
return str(len(row))
columns = [
(lambda x: x['type'], 'Type'),
(lambda x: 'http://localhost/view?id=%s' % x['id'], 'Link'),
(lambda x: SomeObject.helper_function(x), 'Data'),
]
def render_table_head(self):
print('\t'.join([c[1] for c in self.columns]))
def render_table_body(self):
for row in self.values:
print('\t'.join([col[0](row) for col in self.columns]))
A:
There's no way to refer to the class that's currently being defined. There should really be keywords referring to the current scope, eg. __this_class__ for the innermost class being defined and __this_func__ for the innermost function, so classes and functions can cleanly refer to themselves without having to repeat their name.
You could move the definition of columns out of the class body:
class SomeObject:
def __init__(self, values):
self.values = values
...
SomeObject.columns = [
(lambda x: x['type'], 'Type'),
(lambda x: 'http://localhost/view?id=%s' % x['id'], 'Link'),
(SomeObject.helper_function, 'Data'),
]
By the way, please always use at least 4-space indentation. Anything less is very hard to read.
A:
Why not populate columns in init() and use self?
def __init__(self, values):
self.values = values
self.columns = [
(lambda x: x['type'], 'Type'),
(lambda x: 'http://localhost/view?id=%s' % x['id'], 'Link'),
(self.helper_function, 'Data'),
]
A:
This works. It goes against all of my sensibilities.
class SomeObject:
def __init__(self, values):
self.values = values
def helper_function(row):
# do something fancy here
return str(len(row))
columns = [
(lambda x: x['type'], 'Type'),
(lambda x: 'http://localhost/view?id=%s' % x['id'], 'Link'),
(helper_function, 'Data'),
]
def render_table_head(self):
print('\t'.join([c[1] for c in self.columns]))
def render_table_body(self):
for row in self.values:
print('\t'.join([col[0](row) for col in self.columns]))
if __name__ == '__main__':
print "foo"
o = SomeObject([{'type':'type100', 'id':'myId'}, {'type':'type200', 'id':'myId2'}])
o.render_table_body()
A:
You can directly refer to the static function through
(helper_function.__func__, 'Data'),
without having to change anything else in your code. helper_function is of type staticmethod, and __func__ gives access to the underlying function.
| In python, any elegant way to refer to class method within the classes declaration scope? | The below code works both under Python 2.6 and 3.1, but the third lambda of SomeObject.columns is a bit silly, serving no real purpose but to prevent the reference to SomeObject.helper_function from being looked at before the class declaration finishes. It seems like a hack. If I remove the lambda, and replace it with just SomeObject.helper_function, I get NameError: name 'SomeObject' is not defined. Am I missing a better non-hacky way?
class SomeObject:
def __init__(self, values):
self.values = values
@staticmethod
def helper_function(row):
# do something fancy here
return str(len(row))
columns = [
(lambda x: x['type'], 'Type'),
(lambda x: 'http://localhost/view?id=%s' % x['id'], 'Link'),
(lambda x: SomeObject.helper_function(x), 'Data'),
]
def render_table_head(self):
print('\t'.join([c[1] for c in self.columns]))
def render_table_body(self):
for row in self.values:
print('\t'.join([col[0](row) for col in self.columns]))
| [
"There's no way to refer to the class that's currently being defined. There should really be keywords referring to the current scope, eg. __this_class__ for the innermost class being defined and __this_func__ for the innermost function, so classes and functions can cleanly refer to themselves without having to rep... | [
4,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0003929582_python.txt |
Q:
Python - Applying Two's Complement to a String
I am trying to add the Two's Complement to a Binary number represented with a string.
Assuming the string has already been flipped, how would I go about "adding" 1 to the last character, and replacing the other characters in the string as needed?
Example: 100010 is flipped to 011101, and is represented as a string. How would you apply the Two's Complement to the 011101 string?
One part of this that really has me puzzled is if the user enters a binary number that, when the two's complement is applied, involves a lot of carrying.
A:
I'd just do it as a number, then convert it back.
def tobin(x, count=8):
# robbed from http://code.activestate.com/recipes/219300/
return "".join(map(lambda y:str((x>>y)&1), range(count-1, -1, -1)))
def twoscomp(num_str):
return tobin(-int(num_str,2),len(num_str))
print twoscomp('01001001') # prints 10110111
print twoscomp('1000') # prints 1000 (because two's comp is cool like that)
print twoscomp('001') # prints 111
A:
Just for variety, here's yet another way based on the fact the Two's Complement is defined as the One's Complement plus one. This cheats a little and converts the intermediate one's complement string value into an integer to add one to it, and then converts it back to a binary string using the new built-in bin() function added in Python 2.6.
def onescomp(binstr):
return ''.join('1' if b=='0' else '0' for b in binstr)
def twoscomp(binstr):
return bin(int(onescomp(binstr),2)+1)[2:]
print twoscomp('01001001') # prints 10110111
print twoscomp('011101') # prints 100011
print twoscomp('001') # prints 111
A:
if you want to do it without converting back to a number, start from the right of the string until you find the first 1, then flip all chars to its left.
| Python - Applying Two's Complement to a String | I am trying to add the Two's Complement to a Binary number represented with a string.
Assuming the string has already been flipped, how would I go about "adding" 1 to the last character, and replacing the other characters in the string as needed?
Example: 100010 is flipped to 011101, and is represented as a string. How would you apply the Two's Complement to the 011101 string?
One part of this that really has me puzzled is if the user enters a binary number that, when the two's complement is applied, involves a lot of carrying.
| [
"I'd just do it as a number, then convert it back.\ndef tobin(x, count=8):\n # robbed from http://code.activestate.com/recipes/219300/\n return \"\".join(map(lambda y:str((x>>y)&1), range(count-1, -1, -1)))\n\ndef twoscomp(num_str):\n return tobin(-int(num_str,2),len(num_str))\n\nprint twoscomp('01001001')... | [
2,
2,
1
] | [] | [] | [
"python",
"twos_complement"
] | stackoverflow_0003920873_python_twos_complement.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.