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:
Why is my spawned process still causing IntelliJ to wait?
I'm trying to start a server as part of an Ant artifact.
Here are the relevant lines:
<exec dir="." executable="cmd.exe" spawn="true">
<arg line="/c c:\Java\james-2.3.2\bin\debug.bat" />
</exec>
If I start it with ant from the command line... | Why is my spawned process still causing IntelliJ to wait? | I'm trying to start a server as part of an Ant artifact.
Here are the relevant lines:
<exec dir="." executable="cmd.exe" spawn="true">
<arg line="/c c:\Java\james-2.3.2\bin\debug.bat" />
</exec>
If I start it with ant from the command line, a process is spawned and I get a command prompt and everythin... | [
"I've given up on figuring this out, so instead I set up an XML RPC server that does the starting and stopping, and the startup/shutdown scripts make an XML RPC call.\nCode for the server (simplified):\nfrom __future__ import with_statement\n\nfrom threading import Lock\nfrom SimpleXMLRPCServer import SimpleXMLRPCS... | [
0
] | [] | [] | [
"ant",
"intellij_idea",
"python",
"subprocess"
] | stackoverflow_0002402635_ant_intellij_idea_python_subprocess.txt |
Q:
Memory usage with Django + SQLite3
I've got a very large SQLite table with over 500,000 rows with about 15 columns (mostly floats). I'm wanting to transfer data from the SQLite DB to a Django app (which could be backed by many RDBMs, but Postgres in my case). Everything works OK, but as the iteration continues, me... | Memory usage with Django + SQLite3 | I've got a very large SQLite table with over 500,000 rows with about 15 columns (mostly floats). I'm wanting to transfer data from the SQLite DB to a Django app (which could be backed by many RDBMs, but Postgres in my case). Everything works OK, but as the iteration continues, memory usage jumps by 2-3 meg a second for... | [
"Silly me, this was addressed in the Django FAQ.\nNeeded to clear the DB query cache while in DEBUG mode. \nfrom django import db \ndb.reset_queries()\n\n",
"I think a select * from mapDenormalize and loading the result into memory will always be a bad idea. My advise is - spread script into chunks. Use LIMIT to ... | [
3,
1
] | [] | [] | [
"django",
"python",
"sqlite"
] | stackoverflow_0002417572_django_python_sqlite.txt |
Q:
What's the correct way to extract a regexp match in Python?
I have found two ways to extract matches in Python:
1.
def extract_matches(regexp, text):
matches = re.match(regexp, text)
if matches:
return matches.group(1)
2.
def extract_matches(regexp, text):
try:
return re.findall(regexp, text)[0]
e... | What's the correct way to extract a regexp match in Python? | I have found two ways to extract matches in Python:
1.
def extract_matches(regexp, text):
matches = re.match(regexp, text)
if matches:
return matches.group(1)
2.
def extract_matches(regexp, text):
try:
return re.findall(regexp, text)[0]
except IndexError:
return None
Which one would you suggest me... | [
"I would more often use re.search (which returns any match, not just one constrained to start at the beginning of the string as re.match does!) if I'm looking for just one match, re.finditer if I want to loop over all matches. Never re.findall if I'm going after only one match though, that's wasted effort with no ... | [
6
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0002418312_python_regex.txt |
Q:
How do I emulate keyboard-interactive ssh login with paramiko?
I'm trying to automate a ssh connection and control of a network device, that for some reason, only allows keyboard-interactive authentication. It doesn't appear that paramiko supports this by default or with the standard sshclient() object.
I've spen... | How do I emulate keyboard-interactive ssh login with paramiko? | I'm trying to automate a ssh connection and control of a network device, that for some reason, only allows keyboard-interactive authentication. It doesn't appear that paramiko supports this by default or with the standard sshclient() object.
I've spent the past couple of days going through the paramiko documentation t... | [] | [] | [
"What you want is pxssh from the pxpect project. Look at the sshls.py and ssh_tunnel.py examples.\nhttp://www.noah.org/wiki/Pexpect\n"
] | [
-1
] | [
"authentication",
"paramiko",
"python",
"ssh"
] | stackoverflow_0002254673_authentication_paramiko_python_ssh.txt |
Q:
How to digitally sign a message with M2Crypto using the keys within a DER format certificate
I am working on a project to implement digital signatures of outgoing messages and decided to use M2Crypto for that.
I have a certificate (in DER format) from which I extract the keys to sign the message. For some reason I... | How to digitally sign a message with M2Crypto using the keys within a DER format certificate | I am working on a project to implement digital signatures of outgoing messages and decided to use M2Crypto for that.
I have a certificate (in DER format) from which I extract the keys to sign the message. For some reason I keep getting an ugly segmentation fault error when I call the "sign_update" method.
Given the pre... | [
"One obvious thing jumps at me: you say your certificate is in DER format, but you are passing format=0 to load_cert() which means PEM. See X509 module variables. Maybe not what is causing your issue, though (I would expect you'd get an exception if you mix the cert type).\nUpdate After some more thought, I think y... | [
2,
0
] | [] | [] | [
"digital_certificate",
"digital_signature",
"m2crypto",
"python"
] | stackoverflow_0002401397_digital_certificate_digital_signature_m2crypto_python.txt |
Q:
Problem importing pylab in Ubuntu 8.1
I have installed numpy1.3,scipy 0.7.1,matplotlib 0.99.1.1 and python 2.5
when I import pylab I get the following error. Someone please help.
/var/lib/python-support/python2.5/gtk-2.0/gtk/__init__.py:72: GtkWarning: could not open display
warnings.warn(str(e), _gtk.Warni... | Problem importing pylab in Ubuntu 8.1 | I have installed numpy1.3,scipy 0.7.1,matplotlib 0.99.1.1 and python 2.5
when I import pylab I get the following error. Someone please help.
/var/lib/python-support/python2.5/gtk-2.0/gtk/__init__.py:72: GtkWarning: could not open display
warnings.warn(str(e), _gtk.Warning)
/usr/lib/python2.5/site-packages/ma... | [
"try using a different backend for plotting than Gtk. \nOpen the python console and type:\n>>> import matplotlib\n>>> matplotlib.matplotlib_fname()\n\nThis will print a file name. Edit this file and modify the section 'Backend' and change Gtk or GtkAgg with any other (see the documentation in the same file), until ... | [
8
] | [] | [] | [
"python"
] | stackoverflow_0002418583_python.txt |
Q:
Applying style sheets in pyqt
If i apply a property to a parent widget it is automatically applied for child widgets too.. Is there any way of preventing this?? For example if i set background color as white in a dialog the button,combo boxes and scroll bars looks white as it lacks it native look(have to say it's ... | Applying style sheets in pyqt | If i apply a property to a parent widget it is automatically applied for child widgets too.. Is there any way of preventing this?? For example if i set background color as white in a dialog the button,combo boxes and scroll bars looks white as it lacks it native look(have to say it's unpleasant & ugly).. Is there any w... | [
"Found a solution..\nInstead of using \nself.groupBox.setStyleSheet(\"background-color: rgb(255, 255, 255);\\n\"\n \"border:1px solid rgb(255, 170, 255);\")\n\nuse specifically using selector types..\nself.groupBox.setStyleSheet(\"QGroupBox { background-color: rgb(255, 255,\\\n255... | [
14
] | [] | [] | [
"pyqt",
"pyqt4",
"python",
"qt4",
"stylesheet"
] | stackoverflow_0002404317_pyqt_pyqt4_python_qt4_stylesheet.txt |
Q:
How do I pass a list parameter as multiple link-named elements instead of as an array in SOAPpy?
I am trying to pass multiple instances of an element to a web servile that has the following wsdl
<complexType name="OAMCommand">
<sequence>
<element name="m-strName" type="xsd:string" minOccurs="1" maxOccurs=... | How do I pass a list parameter as multiple link-named elements instead of as an array in SOAPpy? | I am trying to pass multiple instances of an element to a web servile that has the following wsdl
<complexType name="OAMCommand">
<sequence>
<element name="m-strName" type="xsd:string" minOccurs="1" maxOccurs="1"/>
<element name="m-argVector" type="xsd:string" minOccurs="0" maxOccurs="unbounded"/>
</se... | [
"After trying a few different librairies (suds, soaplib), I finally dug into the SOAPpy code.\nIn order to remove the arrays from my SOAP requests, I modified the dump_list() function in the SOAPBuilder class of the SOAPpy library.\n# COMMENT: We dont want arrays in SOAP-XML so I commented out the following lines\n... | [
1
] | [] | [] | [
"python",
"soap",
"soappy",
"wsdl"
] | stackoverflow_0002336961_python_soap_soappy_wsdl.txt |
Q:
stop django from taking out javascript/frames?
Very newbie question, but please be gentle with me. Our site uses Django CMS and we're trying to insert some javascript into particular stories, but it appears Django is stripping out any javascript or iframes we put in there as soon as we save the story. How do we al... | stop django from taking out javascript/frames? | Very newbie question, but please be gentle with me. Our site uses Django CMS and we're trying to insert some javascript into particular stories, but it appears Django is stripping out any javascript or iframes we put in there as soon as we save the story. How do we allow javascript to be used in stories? Is it being de... | [
"Django is probably automatically escaping the content the javascript / html as the template renders the content. It does this for security purposes.\nThe solution depends on which version of django you're running, whether you'll be rendering any content from untrusted sources, how the templates are put together an... | [
2,
0,
0
] | [] | [] | [
"django",
"django_templates",
"python"
] | stackoverflow_0002416677_django_django_templates_python.txt |
Q:
Sending a List through an URL
I have a list that I need to send through a URL to a third party vendor. I don't know what language they are using.
The list prints out like this:
[u'1', u'6', u'5']
I know that the u encodes the string in utf-8 right? So a couple of questions.
Can I send a list through a URL?
Will ... | Sending a List through an URL | I have a list that I need to send through a URL to a third party vendor. I don't know what language they are using.
The list prints out like this:
[u'1', u'6', u'5']
I know that the u encodes the string in utf-8 right? So a couple of questions.
Can I send a list through a URL?
Will the u's show up on the other end wh... | [
"\nCan I send a list through a URL?\n\nNo. A URL is just text. If you want a way to package structured information in it, you'll have to agree that with the provider you're talking to.\nOne standard encoding for structure in URLs, that might or might not be what you need, is the use of multiple parameters with the ... | [
5,
1,
0
] | [] | [] | [
"python",
"string",
"unicode",
"url"
] | stackoverflow_0002417611_python_string_unicode_url.txt |
Q:
Avoiding duplicated data in PostgreSQL database in Python
I am working on PostgreSQL and psycopg2. Trying
to get feed data which is updated every after 10 mins
and keep this feeds contents in PostgreSQL database.My target is to retrieve
and print those data from that table.
But facing problem as duplicate data ... | Avoiding duplicated data in PostgreSQL database in Python | I am working on PostgreSQL and psycopg2. Trying
to get feed data which is updated every after 10 mins
and keep this feeds contents in PostgreSQL database.My target is to retrieve
and print those data from that table.
But facing problem as duplicate data is also stored in the database every time I run that script due... | [
"Your code only has INSERT, so what do you think is going to happen when you fetch the same data for a second time?\nYour update is failing because you're trying to insert a row which has an identical field value to one that already exists in a column with a unique constraint.\nYou either need to match entries in f... | [
2,
2,
1
] | [] | [] | [
"postgresql",
"psycopg2",
"python"
] | stackoverflow_0002415884_postgresql_psycopg2_python.txt |
Q:
Installing mod_python on Snow Leopard
I'd rather not use Macports. Simply cause Macport replaces (installs another Apache in /opt/local/bin) the default installation of Apache. And that would mean having ports install/replace PHP too. I'd rather use the default installation included in Snow Leopard.
Been searching... | Installing mod_python on Snow Leopard | I'd rather not use Macports. Simply cause Macport replaces (installs another Apache in /opt/local/bin) the default installation of Apache. And that would mean having ports install/replace PHP too. I'd rather use the default installation included in Snow Leopard.
Been searching the net, and all I get is old instructions... | [
"First of all, it seems that the mod_python development has somewhat stalled. I've read comments that, for wsgi-capable applications like Trac or Django, mod_wsgi is sufficient. Mod_wsgi compiles without problems on Snow Leopard (of course you need the Developer tools installed).\nOf course, Macports or Fink is alw... | [
2,
0,
0
] | [] | [] | [
"mod_python",
"osx_snow_leopard",
"python"
] | stackoverflow_0001616431_mod_python_osx_snow_leopard_python.txt |
Q:
How to only pay the dependency penalty for the implementation you use in Python?
I have a fairly simple set of functionality for which I have multiple implementations, e.g., a datastore that could be backed by Redis, MongoDB, or PostgreSQL. How should I structure/write my code so that code that wants to use one of... | How to only pay the dependency penalty for the implementation you use in Python? | I have a fairly simple set of functionality for which I have multiple implementations, e.g., a datastore that could be backed by Redis, MongoDB, or PostgreSQL. How should I structure/write my code so that code that wants to use one of these implementations only needs the dependencies for that implementation, e.g., they... | [
"Can't you simply put the import statement in the __init__ method of each class? Then it won't be run until you try to make an instance:\nclass UnsatisfiedExample(object):\n def __init__(self):\n try:\n import flibbertigibbet\n except ImportError:\n raise RuntimeError(\"You ne... | [
5,
4
] | [] | [] | [
"dependencies",
"import",
"python"
] | stackoverflow_0002410580_dependencies_import_python.txt |
Q:
Some doubts on implementing custom error pages in Web2Py
I'm trying to implement a decorator for custom error pages in web2py
as per one of the haiti Todos. Ref -
http://web2py.com/AlterEgo/default/show/75
I'm trying to keep it as a module in /modules directory so that I can
import it into the controllers and plac... | Some doubts on implementing custom error pages in Web2Py | I'm trying to implement a decorator for custom error pages in web2py
as per one of the haiti Todos. Ref -
http://web2py.com/AlterEgo/default/show/75
I'm trying to keep it as a module in /modules directory so that I can
import it into the controllers and place the decorator appropriately.
I have kept error handling deco... | [
"Solved through the web2py users mailing list.\n\nyou can also use: onerror = load_import('onerror').onerror \n\nHTTP object wasn't available in onerror.py so i did a - \n from gluon.http import * \n\npython modules are normal python modules in web2py as well. They only see\n python keywords unless you import ... | [
1
] | [] | [] | [
"python",
"web2py"
] | stackoverflow_0002391297_python_web2py.txt |
Q:
Difference between `is` and `==`?
Possible Duplicate:
Python ‘==’ vs ‘is’ comparing strings, ‘is’ fails sometimes, why?
In Python, what is the difference between these two statements:
if x is "odp":
if x == "odp":
A:
The == operator tests for equality
The is keyword tests for object identity; whether we are ta... | Difference between `is` and `==`? |
Possible Duplicate:
Python ‘==’ vs ‘is’ comparing strings, ‘is’ fails sometimes, why?
In Python, what is the difference between these two statements:
if x is "odp":
if x == "odp":
| [
"The == operator tests for equality \nThe is keyword tests for object identity; whether we are talking about the same object. Note that multiple variables may refer to the same object.\n",
"The is operator compares the identity while the == operator compares the value. Essentially x is y is the same as id(x) == i... | [
3,
2,
1,
0
] | [] | [] | [
"python",
"syntax"
] | stackoverflow_0002419361_python_syntax.txt |
Q:
How do I retrieve a modules path when I have a class from that module
In python, If I have a class foo, I can call foo.__module__ to get a string with the name of the module it is part of.
If I have a module bar, I can call bar.__file__ to get a string with the path where the module was loaded from.
How, when I on... | How do I retrieve a modules path when I have a class from that module | In python, If I have a class foo, I can call foo.__module__ to get a string with the name of the module it is part of.
If I have a module bar, I can call bar.__file__ to get a string with the path where the module was loaded from.
How, when I only have class foo can I get the path of the module it is part of? (foo.__mo... | [
"sys.modules is a mapping from module name to module:\nsys.modules[foo.__module__].__file__\n\n",
"For such introspection tasks, I always recommend using Python standard library's inspect module: it can handle some corner cases &c and makes the whole process much smoother. For your specific task, inspect.getsour... | [
6,
3
] | [] | [] | [
"python"
] | stackoverflow_0002417639_python.txt |
Q:
Decorator class to test for required class variables
First of all I don't know if this is the right approach. I want to write a decorator class that will be used with methods of other class. Before running the method I'd like to check if all required class variables are initialized. The ideal case would be somethi... | Decorator class to test for required class variables | First of all I don't know if this is the right approach. I want to write a decorator class that will be used with methods of other class. Before running the method I'd like to check if all required class variables are initialized. The ideal case would be something similar to this:
class Test(object):
def __init__(s... | [
"I'd say decorators are a bit unfit here for the purpose of checking if a variable exists.\nThink about what you're planning to do if the required variables are not supplied: raise an exception (it's in your comment). \nI'd say (based on the code above):\ndef sum(self):\n return self.a + self.b\n\nAnd let it fai... | [
1,
0
] | [] | [] | [
"decorator",
"python"
] | stackoverflow_0002419196_decorator_python.txt |
Q:
How to get the content of a Html page in Python
I have downloaded the web page into an html file. I am wondering what's the simplest way to get the content of that page. By content, I mean I need the strings that a browser would display.
To be clear:
Input:
<html><head><title>Page title</title></head>
<body... | How to get the content of a Html page in Python | I have downloaded the web page into an html file. I am wondering what's the simplest way to get the content of that page. By content, I mean I need the strings that a browser would display.
To be clear:
Input:
<html><head><title>Page title</title></head>
<body><p id="firstpara" align="center">This is paragraph <... | [
"Parse the HTML with Beautiful Soup.\nTo get all the text, without the tags, try:\n''.join(soup.findAll(text=True))\n\n",
"Personally, I use lxml because it's a swiss-army knife...\n\nfrom lxml import html\n\nprint html.parse('http://someurl.at.domain').xpath('//body')[0].text_content()\n\nThis tells lxml to retr... | [
12,
9,
2,
1
] | [
"If I am getting your question correctly, this can simply be done by using urlopen function of urllib. Just have a look at this function to open an url and read the response which will be the html code of that page.\n",
"The quickest way to get a usable sample of what a browser would display is to remove any tags... | [
-2,
-3
] | [
"html",
"parsing",
"python"
] | stackoverflow_0002416823_html_parsing_python.txt |
Q:
Error installing MySQL-python on MAC Snow Leopard, OS 10.6
I am trying to install the MySQL-python on MAC OS 10.6 (Snow leopard, 64 bit). I followed the steps:
1. Installed MySQL for Mac OS X ver. 10.6 (x86, 64-bit), DMG Archive.
2. Downloaded MySQL-python-1.2.3c1.tar.gz and unzipped it
3. CD to MySQL-python-1.2.3... | Error installing MySQL-python on MAC Snow Leopard, OS 10.6 | I am trying to install the MySQL-python on MAC OS 10.6 (Snow leopard, 64 bit). I followed the steps:
1. Installed MySQL for Mac OS X ver. 10.6 (x86, 64-bit), DMG Archive.
2. Downloaded MySQL-python-1.2.3c1.tar.gz and unzipped it
3. CD to MySQL-python-1.2.3c1 and built it as:
ARCHFLAGS="-arch x86_64" python setup.py ... | [
"The python 2.6.4 you are using is 32-bit only (definitely true if you downloaded the OS X installer from python.org). You can't override the architecture for extension modules; they have to be compatible with the base python. The 10.3 shows up because the python you are using was built with a deployment target o... | [
1
] | [] | [] | [
"macos",
"mysql",
"python"
] | stackoverflow_0002414658_macos_mysql_python.txt |
Q:
Open Windows shared folder through linux machine
I am using python 2.5 on Ubuntu, and there's a machine in the same network called machine1. The folder is shared.
How to to get a file in a specific folder of that machine?
I have tried, with no success:
urllib.urlopen('\\machine1\folder\file.txt')
A:
Linux has a ... | Open Windows shared folder through linux machine | I am using python 2.5 on Ubuntu, and there's a machine in the same network called machine1. The folder is shared.
How to to get a file in a specific folder of that machine?
I have tried, with no success:
urllib.urlopen('\\machine1\folder\file.txt')
| [
"Linux has a utiliy called smbmount, which can be found in package smbutils I believe.\nThis is a command line utility which mounts a Windows share to a directory on the local machine, optionally with username/password.\nsmbmount is I believe a utility which runs as root, so whether it's suitable for you I don't kn... | [
6,
2,
0
] | [
"You should look for the default file browser.\nAnd then you can execute the process and pass in the folder you want as an argument (smb://machine1/folder/).\nFor example on windows you would do:\nexecl(\"explorer.exe\", \"D:\")\n\nTry to look for the path to your file browser (most of the time it's Nautilus).\nSo:... | [
-1
] | [
"python",
"urllib"
] | stackoverflow_0002419953_python_urllib.txt |
Q:
How does OS handle a python dict that's larger than memory?
I have a python program that is going to eat a lot of memory, primarily in a dict. This dict will be responsible for assigning a unique integer value to a very large set of keys. As I am working with large matrices, I need a key-to-index correspondence ... | How does OS handle a python dict that's larger than memory? | I have a python program that is going to eat a lot of memory, primarily in a dict. This dict will be responsible for assigning a unique integer value to a very large set of keys. As I am working with large matrices, I need a key-to-index correspondence that can also be recovered from (i.e., once matrix computations a... | [
"You need a database, if the data will exceed memory. The indexing of dictionaries isn't designed for good performance when a dictionary is bigger than memory.\n",
"Swap space is a kernel feature and transparant to the user (python).\nIf you do have a huge dict and don't need all the data at once, you could look... | [
5,
2,
1,
1
] | [] | [] | [
"data_structures",
"matrix",
"memory",
"python",
"swap"
] | stackoverflow_0002420219_data_structures_matrix_memory_python_swap.txt |
Q:
Python String with HTML /
I'm trying a simple program to send some html down a socket to a client. 2 things are goofing me up.
The code:
c.send( str.encode("<HTML><BODY>Test Page<///BODY><///HTML>") )
My python client receives:
b'<HTML><BODY>Test Page<///BODY><///HTML>'
According to Beginning Python which says ... | Python String with HTML / | I'm trying a simple program to send some html down a socket to a client. 2 things are goofing me up.
The code:
c.send( str.encode("<HTML><BODY>Test Page<///BODY><///HTML>") )
My python client receives:
b'<HTML><BODY>Test Page<///BODY><///HTML>'
According to Beginning Python which says it covers Python 3 (I'm using 3... | [
"You want '...'.encode() and b'...'.decode(). Saying \"str.encode\" is shorthand for saying that all str literals have this method.\n"
] | [
0
] | [
"The extra '/' is wrong. You only need to worry about escaping for '\\'\n"
] | [
-1
] | [
"decode",
"html",
"python",
"string"
] | stackoverflow_0002420246_decode_html_python_string.txt |
Q:
google app engine: new version doesn't appear
I have made an update on Google App Engine with a small fix and I got:
Closing update: new version is ready to start serving.
However, when I open the website, there is still old version. I have changed version to 2 in app.yaml, before running update. What am I missin... | google app engine: new version doesn't appear | I have made an update on Google App Engine with a small fix and I got:
Closing update: new version is ready to start serving.
However, when I open the website, there is still old version. I have changed version to 2 in app.yaml, before running update. What am I missing?
| [
"You have to set the new version to be the active version in the Admin console. Click the 'Versions' link, and make your new version the Default.\n"
] | [
4
] | [] | [] | [
"django",
"google_app_engine",
"python",
"version"
] | stackoverflow_0002420519_django_google_app_engine_python_version.txt |
Q:
get an array variable in python
can I do this in a loop, by producing the file name from the name of the array to store ?
ab = array.array('B', map( operator.xor, a, b ) )
f1 = open('ab', 'wb')
ab.tofile(f1)
f1.close
ac = array.array('B', map( operator.xor, a, c ) )
f1 = open('ac', 'wb')
ac.tofile(f1)
f1.close
ad... | get an array variable in python | can I do this in a loop, by producing the file name from the name of the array to store ?
ab = array.array('B', map( operator.xor, a, b ) )
f1 = open('ab', 'wb')
ab.tofile(f1)
f1.close
ac = array.array('B', map( operator.xor, a, c ) )
f1 = open('ac', 'wb')
ac.tofile(f1)
f1.close
ad = array.array('B', map( operator.xor... | [
"Assuming you are storing all the intermediate arrays for a reason.\nA={}\nfor v,x in zip((b,c,d,e,f),'bcdef'):\n fname = 'a'+x\n A[fname] = (array.array('B', map( operator.xor, a, v ) ))\n f1 = open(fname, 'wb')\n A[fname].tofile(f1)\n f1.close\n\nOr something like this should work too\nA={}\nfor x ... | [
2,
1
] | [] | [] | [
"arrays",
"introspection",
"python",
"variables"
] | stackoverflow_0002420644_arrays_introspection_python_variables.txt |
Q:
Why does my 'hello world' Python C module work correctly in everything but IDLE?
I compiled a simple hello world C module for Python and it works correctly in everything I've tried but IDLE. Here's what I type to test it:
>>> import hello
>>> hello.say_hello('Justin')
I have tried this using Python from the comma... | Why does my 'hello world' Python C module work correctly in everything but IDLE? | I compiled a simple hello world C module for Python and it works correctly in everything I've tried but IDLE. Here's what I type to test it:
>>> import hello
>>> hello.say_hello('Justin')
I have tried this using Python from the command prompt(I'm using Windows), in Eclipse's PyDev, and with PieDream and they all print... | [
"Sounds like the hello is writing directly to stdout. Python's stdout is not necessarily the the same place as C stdout\nNormally you would return a string to Python so Python can print it to it's own stdout\n",
"If you need to write to Python's sys.stdout from a C-coded extension, you can use something like:\nvo... | [
5,
5
] | [] | [] | [
"c",
"mingw",
"module",
"python",
"windows"
] | stackoverflow_0002420317_c_mingw_module_python_windows.txt |
Q:
Django query with related models
For the below models:
class Customer(models.Model):
id = models.IntegerField(primary_key=True)
class OrderA(models.Model):
name = models.CharField(max_length=20)
foo = models.FloatField()
customer = models.ForeignKey(Customer)
type = models.IntegerField()
clas... | Django query with related models | For the below models:
class Customer(models.Model):
id = models.IntegerField(primary_key=True)
class OrderA(models.Model):
name = models.CharField(max_length=20)
foo = models.FloatField()
customer = models.ForeignKey(Customer)
type = models.IntegerField()
class OrderB(models.Model):
name = mod... | [
"select_related() will pre-populate the appropriate attributes:\nCustomer.objects.filter(ordera_set__type=1, orderb_set__type=1).select_related()\n\n",
"You're right in your comment to Ignacio that select_related works in the opposite direction.\nI've written about a technique to do it in this direction on my blo... | [
2,
-3
] | [] | [] | [
"django",
"python"
] | stackoverflow_0002421064_django_python.txt |
Q:
How to filter a query by property of user profile in Django?
I have two models,Design and Profile. Profile is hooked up in settings.py as the profile to be used with the User model. So I can access it via user.get_profile().
And each Design instance has an author property that is a ForeignKey to User.
So, when I'm... | How to filter a query by property of user profile in Django? | I have two models,Design and Profile. Profile is hooked up in settings.py as the profile to be used with the User model. So I can access it via user.get_profile().
And each Design instance has an author property that is a ForeignKey to User.
So, when I'm any view, I can get the screenname (a property of Profile) by:
us... | [
"If your profile class is named Profile, and you haven't customized the User <-> Profile relation using the related_name property of the ForeignKey, then shouldn't you be accessing via:\ndesigns = Design.objects.filter(author__user__profile__screenname__icontains=w)\n\nThe User -> Profile spans a relation so you ne... | [
8
] | [] | [] | [
"django",
"python"
] | stackoverflow_0002421221_django_python.txt |
Q:
Python Unicode strings and the Python interactive interpreter
I'm trying to understand how python 2.5 deals with unicode strings. Although by now I think I have a good grasp of how I'm supposed to handle them in code, I don't fully understand what's going on behind the scenes, particularly when you type strings at... | Python Unicode strings and the Python interactive interpreter | I'm trying to understand how python 2.5 deals with unicode strings. Although by now I think I have a good grasp of how I'm supposed to handle them in code, I don't fully understand what's going on behind the scenes, particularly when you type strings at the interpreter's prompt.
So python pre 3.0 has two types for stri... | [
"Let me expand Ignacio's reply: In both cases there is an extra layer between Python and you: in one case it is Sublime Text and in the other it's cmd.exe. The difference in behaviour you see is not due to Python but by the different encodings used by Sublime Text (utf-8, as it seems) and cmd.exe (cp437).\nSo, when... | [
7,
3,
1
] | [] | [] | [
"python",
"string",
"sublimetext",
"unicode"
] | stackoverflow_0002421145_python_string_sublimetext_unicode.txt |
Q:
How do I modify a generator in Python?
Is there a common interface in Python that I could derive from to modify behavior of a generator?
For example, I want to modify an existing generator to insert some values in the stream and remove some other values.
How do I do that?
Thanks, Boda Cydo
A:
You can use the fun... | How do I modify a generator in Python? | Is there a common interface in Python that I could derive from to modify behavior of a generator?
For example, I want to modify an existing generator to insert some values in the stream and remove some other values.
How do I do that?
Thanks, Boda Cydo
| [
"You can use the functions provided by itertools to take a generator and produce a new generator.\nFor example, you can use takewhile until a predicate is no longer fulfilled, and chain on a new series of values.\nTake a look at the documentation for other examples, including things like ifilter, dropwhile and isli... | [
7,
7
] | [] | [] | [
"generator",
"python"
] | stackoverflow_0002421355_generator_python.txt |
Q:
How to correctly call base class methods (and constructor) from inherited classes in Python?
Suppose I have a Base class and a Child class that inherits from Base. What is the right way to call the constructor of base class from a child class in Python? Do I use super?
Here is an example of what I have so far:
cla... | How to correctly call base class methods (and constructor) from inherited classes in Python? | Suppose I have a Base class and a Child class that inherits from Base. What is the right way to call the constructor of base class from a child class in Python? Do I use super?
Here is an example of what I have so far:
class Base(object):
def __init__(self, value):
self.value = value
...
class Child(Base)... | [
"That is correct. Note that you can also call the __init__ method directly on the Base class, like so:\nclass Child(Base):\n def __init__(self, something_else):\n Base.__init__(self, value = 20)\n self.something_else = something_else\n\nThat's the way I generally do it. But it's discouraged, beca... | [
72,
66,
13
] | [] | [] | [
"python"
] | stackoverflow_0002421307_python.txt |
Q:
Verify RTSP service via URL
I am trying to verify that a video service is provided from an URL in python. I am asking does anyone know of any good libraries to use or a way to do this. I have not found much info for this on the web.
Thanks
A:
Digging around on StackOverflow I came across a previous question ask... | Verify RTSP service via URL | I am trying to verify that a video service is provided from an URL in python. I am asking does anyone know of any good libraries to use or a way to do this. I have not found much info for this on the web.
Thanks
| [
"Digging around on StackOverflow I came across a previous question asking for an RTSP library in Python or C/C++ .\nLinked there is an RTSP library provided by Twisted, and another one called Live555. Have you tried either of these?\nI am just reposting the links for convenience.\n",
"If you do not want to use a... | [
4,
3,
1,
0
] | [] | [] | [
"python",
"rtsp",
"url",
"video_streaming"
] | stackoverflow_0002207110_python_rtsp_url_video_streaming.txt |
Q:
What is the Bash equivalent of Python's pass statement
Is there a Bash equivalent to the Python's pass statement?
A:
You can use : for this.
A:
true is a command that successfully does nothing.
(false would, in a way, be the opposite: it doesn't do anything, but claims that a failure occurred.)
| What is the Bash equivalent of Python's pass statement | Is there a Bash equivalent to the Python's pass statement?
| [
"You can use : for this.\n",
"true is a command that successfully does nothing.\n(false would, in a way, be the opposite: it doesn't do anything, but claims that a failure occurred.)\n"
] | [
184,
47
] | [] | [] | [
"bash",
"language_comparisons",
"python"
] | stackoverflow_0002421586_bash_language_comparisons_python.txt |
Q:
parsing words in string prefaced by 'password' with regex
a="aaaaaa password: GOD hello world password is G0D hello"
match = re.match("^(?:.*(?:password\sis\s|password:\s)([a-zA-Z]*)\s.*)*$",a)
print match.groups()
i want the output to be ('GOD','G0D') but all i get is ('G0D')
i am trying to solve this with Rege... | parsing words in string prefaced by 'password' with regex | a="aaaaaa password: GOD hello world password is G0D hello"
match = re.match("^(?:.*(?:password\sis\s|password:\s)([a-zA-Z]*)\s.*)*$",a)
print match.groups()
i want the output to be ('GOD','G0D') but all i get is ('G0D')
i am trying to solve this with Regex only. the amount of times "password" can appear in the text c... | [
"I'd use re.findall, and simplify the regex a bit.\n>>> re.findall(r\"(?:password\\sis\\s+|password\\:\\s+)(\\S+)\", a)\n['GOD', 'G0D']\n\nEdit: Changed from \\w to \\S in order to also capture punctuation, and remove list expression.\n",
"The ([a-zA-Z]*) regular subexpression does not accept digits, you might ha... | [
1,
0,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0002421529_python_regex.txt |
Q:
RegExp in Python
This is an example that searches PDF files in the current directory.
import os, os.path
import re
def print_pdf (arg, dir, files):
for file in files:
path = os.path.join(dir, file)
path = os.path.normcase(path)
if re.search(r".*\.pdf", path):
print path
os.path.walk('.', print_pdf, 0)
... | RegExp in Python | This is an example that searches PDF files in the current directory.
import os, os.path
import re
def print_pdf (arg, dir, files):
for file in files:
path = os.path.join(dir, file)
path = os.path.normcase(path)
if re.search(r".*\.pdf", path):
print path
os.path.walk('.', print_pdf, 0)
Could anyone explain ... | [
"it means any character zero or more times, followed by the literal dot and letters pdf (due to the greedy nature of the asterisk, it's basically guaranteed that the '.pdf' are going to be at the end of the subject string).\nThere is glob module to do this the right way:\n>>> glob.glob(os.path.join(dirname, '*.pdf'... | [
8,
3,
2,
1,
0,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0002419147_python_regex.txt |
Q:
Cannot fetch a web site with python urllib.urlopen() or any web browser other than Shiretoko
Here is the URL of the site I want to fetch
https://salami.parc.com/spartag/GetRepository?friend=jmankoff&keywords=antibiotic&option=jmankoff%27s+tags
When I fetch the web site with the following code and display the conte... | Cannot fetch a web site with python urllib.urlopen() or any web browser other than Shiretoko | Here is the URL of the site I want to fetch
https://salami.parc.com/spartag/GetRepository?friend=jmankoff&keywords=antibiotic&option=jmankoff%27s+tags
When I fetch the web site with the following code and display the contents with the following code:
sock = urllib.urlopen("https://salami.parc.com/spartag/GetRepository?... | [
"If you see the urllib2 doc, it says\nurllib2.build_opener([handler, ...])¶\n\n .....\n If the Python installation has SSL support (i.e., if the ssl module can be imported), HTTPSHandler will also be added. \n\n .....\n\nyou can try using urllib2 together with ssl module. alternatively, you can use httplib... | [
2,
0
] | [] | [] | [
"beautifulsoup",
"python",
"urllib"
] | stackoverflow_0002421857_beautifulsoup_python_urllib.txt |
Q:
PyGTK StatusIcon with transparency
I'm trying to create a PyGTK StatusIcon with transparent background. I need to draw the contents of the StatusIcon at runtime.
StatusIcon wants a Pixbuf object (which can have transparency). No problem with that:
pixbuf = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, True, 8, width, hei... | PyGTK StatusIcon with transparency | I'm trying to create a PyGTK StatusIcon with transparent background. I need to draw the contents of the StatusIcon at runtime.
StatusIcon wants a Pixbuf object (which can have transparency). No problem with that:
pixbuf = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, True, 8, width, height)
pixbuf.fill(0xffffffff)
The proble... | [
"You can add transparency to Pixbuf objects with the add_alpha() method. The following line will set zero opacity for the color #ffffff:\npixbuf = pixbuf.add_alpha(True, 0xFF, 0xFF, 0xFF)\n\nToo easy... :-|\n"
] | [
4
] | [] | [] | [
"alpha_transparency",
"pygtk",
"python"
] | stackoverflow_0002412346_alpha_transparency_pygtk_python.txt |
Q:
How to Check if request.GET var is None?
I'm getting into django and this is getting me a headache. I'm trying to get a simple GET variable. URL is site.com/search/?q=search-term
My view is:
def search(request):
if request.method == 'GET' and 'q' in request.GET:
q = request.GET.get('q', None)
i... | How to Check if request.GET var is None? | I'm getting into django and this is getting me a headache. I'm trying to get a simple GET variable. URL is site.com/search/?q=search-term
My view is:
def search(request):
if request.method == 'GET' and 'q' in request.GET:
q = request.GET.get('q', None)
if q is not None:
results = Task.ob... | [
"First, check if the request.GET dict contains a parameter named q. You're doing this properly already:\nif request.method == 'GET' and 'q' in request.GET:\n\nNext, check if the value of q is either None or the empty string. To do that, you can write this:\nq = request.GET['q']\nif q is not None and q != '':\n #... | [
55,
2
] | [] | [] | [
"django",
"python"
] | stackoverflow_0002422055_django_python.txt |
Q:
Apache2: mod_wsgi or mod_python, which one is better?
I am planning to write web service in python. But, I found wsgi also does the similar thing. Which one can be preferred?
Thank you
Bala
Update
I am still confused. Please help.
Better in my sense means:
1. Bug will be fixed periodically.
2. Chosen by most dev... | Apache2: mod_wsgi or mod_python, which one is better? | I am planning to write web service in python. But, I found wsgi also does the similar thing. Which one can be preferred?
Thank you
Bala
Update
I am still confused. Please help.
Better in my sense means:
1. Bug will be fixed periodically.
2. Chosen by most developers.
3. Additional features like authentication tokens ... | [
"mod_wsgi is more actively maintained and (I hear -- haven't benchmarked them myself!) better performing than mod_python. So unless you need exclusive features of mod_python, just to use a web app framework (or non-framework, like werkzeug;-), you're probably better off with mod_wsgi! (Just about every Python web... | [
14,
5,
4,
3,
1,
0
] | [] | [] | [
"apache2",
"python",
"rest",
"web_services"
] | stackoverflow_0002421007_apache2_python_rest_web_services.txt |
Q:
Quickly implement a sortable table of objects in Django
Hey all. I have a question on how to implement the following with Django. I'd like to display a tabular view of my objects with each column corresponding to a particular model field. I'd like to be able to have the user sort the columns or search through all ... | Quickly implement a sortable table of objects in Django | Hey all. I have a question on how to implement the following with Django. I'd like to display a tabular view of my objects with each column corresponding to a particular model field. I'd like to be able to have the user sort the columns or search through all of them. Basically just like the admin, but client facing and... | [
"Alex Gaynor's django-filter may be what you want.\n",
"Depending on how much you wanted to work with it, Yahoo YUI's DataTable control is pretty easy to get working with a JSON data source. See http://developer.yahoo.com/yui/datatable/\n"
] | [
1,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0002421006_django_python.txt |
Q:
How do I create a list with 256 elements?
I've started teaching myself Python, and as an exercise I've set myself the task of generating lookup tables I need for another project.
I need to generate a list of 256 elements in which each element is the value of math.sin(2*i*pi/256). The problem is, I don't know how ... | How do I create a list with 256 elements? | I've started teaching myself Python, and as an exercise I've set myself the task of generating lookup tables I need for another project.
I need to generate a list of 256 elements in which each element is the value of math.sin(2*i*pi/256). The problem is, I don't know how to generate a list initialized to "dummy" value... | [
"Two answers have already shown you how to build your list at a single stroke, using the \"list comprehension\" (AKA \"listcomp\") construct.\nTo answer your specific question, though,\nmylist = [None] * 256\n\nis the simplest way to make a list with 256 items, all None, in case you want to fill it in later.\nIf yo... | [
10,
5,
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0002422461_python.txt |
Q:
Are PyArg_ParseTuple() "s" format specifiers useful in Python 3.x C API?
I'm trying to write a Python C extension that processes byte strings, and I have something basically working for Python 2.x and Python 3.x.
For the Python 2.x code, near the start of my function, I currently have a line:
if (!PyArg_ParseT... | Are PyArg_ParseTuple() "s" format specifiers useful in Python 3.x C API? | I'm trying to write a Python C extension that processes byte strings, and I have something basically working for Python 2.x and Python 3.x.
For the Python 2.x code, near the start of my function, I currently have a line:
if (!PyArg_ParseTuple(args, "s#:in_bytes", &src_ptr, &src_len))
...
I notice that the s# f... | [
"I agree with you -- it's one of several spots where the C API migration of Python 3 was clearly not designed as carefully and thouroughly as the Python coder-visible parts. I do also agree that probably the best workaround for now is focusing on \"buffer views\", per that macro -- until and unless something bette... | [
3
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0002422572_python_python_3.x.txt |
Q:
Filter across three tables using Django
I have 3 django models, where the first has a foreign key to the second, and the second has a foreign key to the third. Like this:
class Book(models.Model):
year_published = models.IntField()
author = models.ForeignKey(Author)
class Author(models.Model):
author... | Filter across three tables using Django | I have 3 django models, where the first has a foreign key to the second, and the second has a foreign key to the third. Like this:
class Book(models.Model):
year_published = models.IntField()
author = models.ForeignKey(Author)
class Author(models.Model):
author_id = models.AutoField(primary_key=True)
... | [
"LitAgent.objects.filter(author__book__year_published=2006)\n\n"
] | [
11
] | [] | [] | [
"django",
"python"
] | stackoverflow_0002422668_django_python.txt |
Q:
Unable to set iPython to use 2.6.1 Python
I have installed the newest iPython in Mac. However, it uses the Python verion 2.5.1.
I installed the Python 2.6.1 by MacPython package at here.
How can I make my iPython to use Python 2.6.1?
I am not sure where the MacPython package exactly installed the newest Python.
T... | Unable to set iPython to use 2.6.1 Python | I have installed the newest iPython in Mac. However, it uses the Python verion 2.5.1.
I installed the Python 2.6.1 by MacPython package at here.
How can I make my iPython to use Python 2.6.1?
I am not sure where the MacPython package exactly installed the newest Python.
The newest Python should somehow put the PATH so... | [
"A good way to get it to work is here. I needed to restart my terminal before ipython pointed to python2.6. Note the latest ipython distribution is 0.10, not 0.9.\n",
"you should have a python, python2.5 and python2.6, is that correct? If you wan't to use python2.6 system wide the symple solution would be to sym ... | [
4,
1
] | [] | [] | [
"ipython",
"python"
] | stackoverflow_0000641000_ipython_python.txt |
Q:
Python: avoiding if condition?
Which is better?
if not var:
var = get_var()
(or)
var = var or get_var()
Also, How do I know the better of the two?
edit:One more option from steve,
var = var if var else get_var()
A:
The better is the one you like better. I would use first version with if but this is very pe... | Python: avoiding if condition? | Which is better?
if not var:
var = get_var()
(or)
var = var or get_var()
Also, How do I know the better of the two?
edit:One more option from steve,
var = var if var else get_var()
| [
"The better is the one you like better. I would use first version with if but this is very personal.\n",
"When two style variations are so close stylistically, I use timeit as the tie-breaker: faster must mean closer to Python's mainstream, i.e., better. Hey, it's better than endless debate, y?-) So:\n$ python -... | [
7,
7,
4,
3,
2,
1,
1,
1,
1
] | [] | [] | [
"conditional_statements",
"python",
"variable_assignment"
] | stackoverflow_0002422905_conditional_statements_python_variable_assignment.txt |
Q:
Best practices for logging in django project
It is always good to utilize existing patterns for solving the given problem rather then reinventing the wheel. This time it is about doing logging stuffs in django based project.
Can you please share your ideas with me and other about how do you prefer to implement log... | Best practices for logging in django project | It is always good to utilize existing patterns for solving the given problem rather then reinventing the wheel. This time it is about doing logging stuffs in django based project.
Can you please share your ideas with me and other about how do you prefer to implement logging in django based project in the following cont... | [
"In Django, like in any other Python application, I'd use the standard library's logging module and call logging.debug, logging.info etc as appropriate to each message.\n"
] | [
7
] | [] | [] | [
"django",
"logging",
"python"
] | stackoverflow_0002423005_django_logging_python.txt |
Q:
Similar to ``tabnanny``, how can I check that all the python code is using 4 spaces as an indent?
Similar to tabnanny, is there a utility for python to check if a python file is using 4 spaces for indentation?
A:
Pylint can check this among many other things. Here's a warning it gave me with a test file:
W: 3: ... | Similar to ``tabnanny``, how can I check that all the python code is using 4 spaces as an indent? | Similar to tabnanny, is there a utility for python to check if a python file is using 4 spaces for indentation?
| [
"Pylint can check this among many other things. Here's a warning it gave me with a test file:\nW: 3: Bad indentation. Found 3 spaces, expected 4\n\nIt's also possible to make it expect another indent type using this command line option:\n--indent-string=<string>\n String used as indentation unit. This ... | [
4,
4,
1
] | [] | [] | [
"python",
"tabs"
] | stackoverflow_0002421755_python_tabs.txt |
Q:
In Python, is this a good practice?
try:
spam.foo
except AttributeError:
do_somthing()
(Is it wise to check an attribute like that without using it?)
A:
Update:
If you are really only interested in whether the attribute foo exists (and not doing something with the attribute) than of course hasattr() mig... | In Python, is this a good practice? | try:
spam.foo
except AttributeError:
do_somthing()
(Is it wise to check an attribute like that without using it?)
| [
"Update:\nIf you are really only interested in whether the attribute foo exists (and not doing something with the attribute) than of course hasattr() might be better way to check for the attribute.\nFrom a developer/user point of view I have to confess that, for me, the use of hasattr() better reflects your intenti... | [
14,
2
] | [] | [] | [
"python"
] | stackoverflow_0002423145_python.txt |
Q:
The data format for post in urllib2.Request
What should data look like before data encoding in:
urllib2.Request(someurl,data) I tried [('name1','value1'),('name2','value2'),...]but not work.:(
EDIT:
I made a log in the program and recorded the value of urllib.urlencode(data):
content=%E5%8F%91%E5%B8%83%E4%BA%86%E... | The data format for post in urllib2.Request | What should data look like before data encoding in:
urllib2.Request(someurl,data) I tried [('name1','value1'),('name2','value2'),...]but not work.:(
EDIT:
I made a log in the program and recorded the value of urllib.urlencode(data):
content=%E5%8F%91%E5%B8%83%E4%BA%86%E4%B8%80%E4%B8%AA%E6%96%B0%E4%B8%BB%E9%A2%98%EF%BC... | [
"data may be a string specifying additional data to send to the server, or None if no such data is needed. Currently HTTP requests are the only ones that use data; the HTTP request will be a POST instead of a GET when the data parameter is provided. data should be a buffer in the standard application/x-www-form-url... | [
2
] | [] | [] | [
"python"
] | stackoverflow_0002423146_python.txt |
Q:
Uneditable file and Unreadable(for further processing) file( WHY? ) after processing it through C++ Program
:) This might look to be a very long question to you I understand, but trust me on this its not long. I am not able to identify why after processing this text is not being able to be read and edited. I tried... | Uneditable file and Unreadable(for further processing) file( WHY? ) after processing it through C++ Program | :) This might look to be a very long question to you I understand, but trust me on this its not long. I am not able to identify why after processing this text is not being able to be read and edited. I tried using the ord() function in python to check if the text contains any Unicode characters( non ascii characters) a... | [
"(now i can reply, after taking some time editing the post. when posting, please use the preview and read the help !)\nThere is no problem Python cannot tackle... and this problam can definitely be solved using python.\nAfter modifying a bit your python script (indentation is messed up !), i was able to process the... | [
2
] | [] | [] | [
"c++",
"file",
"perl",
"python"
] | stackoverflow_0002423380_c++_file_perl_python.txt |
Q:
Python: installing multiprocessing
I need to import the multiprocessing module in Python 2.5.
I've followed the instructions here exactly: http://code.google.com/p/python-multiprocessing/wiki/Install
make and make test run without errors. I've also edited $PYTHONPATH to include the directory where the package is ... | Python: installing multiprocessing | I need to import the multiprocessing module in Python 2.5.
I've followed the instructions here exactly: http://code.google.com/p/python-multiprocessing/wiki/Install
make and make test run without errors. I've also edited $PYTHONPATH to include the directory where the package is installed.
But 'import multiprocessing' ... | [
"Navigate to the directory containing the package then type:\npython setup.py install\n\nThis info was contained in the INSTALL.txt file.\nhttp://code.google.com/p/python-multiprocessing/source/browse/trunk/INSTALL.txt\n"
] | [
4
] | [
"perhaps you can try:\nimport sys\nsys.path.append('/path/to/processingdotpylibs/')\nimport processing\n\n"
] | [
-1
] | [
"module",
"python"
] | stackoverflow_0002424078_module_python.txt |
Q:
manipulating list items python
line = "english: while french: pendant que spanish: mientras german: whrend "
words = line.split('\t')
for each in words:
each = each.rstrip()
print words
the string in 'line' is tab delimited but also features a single white space character after each translated word, so whi... | manipulating list items python | line = "english: while french: pendant que spanish: mientras german: whrend "
words = line.split('\t')
for each in words:
each = each.rstrip()
print words
the string in 'line' is tab delimited but also features a single white space character after each translated word, so while split returns the list I'm after,... | [
"Just line.split() could give you stripped words list.\nUpdating each inside the loop does not make any changes to the words list\nShould be done like this\nfor i in range(len(words)):\n words[i]=words[i].rstrip()\n\nOr\nwords=map(str.rstrip,words)\n\nSee the map docs for details on map.\nOr one liner with list ... | [
1,
1,
0
] | [] | [] | [
"python",
"string"
] | stackoverflow_0002424226_python_string.txt |
Q:
Append previous lines of a file based on a condition
I have a text file with a few 1000 lines of text in it. A sample is given below:
person1
person2
person3
person4
have paid
---------
person5
person6
person7
person9
person10
person11
have paid
---------
Each line starts with either "p" or "h" or "-". When "... | Append previous lines of a file based on a condition | I have a text file with a few 1000 lines of text in it. A sample is given below:
person1
person2
person3
person4
have paid
---------
person5
person6
person7
person9
person10
person11
have paid
---------
Each line starts with either "p" or "h" or "-". When "have paid" is encountered while reading the file, I want t... | [
"data=open(\"file\").read().split(\"\\n\\n\")\nfor rec in data:\n if \"have paid\" in rec:\n print rec.split(\"have paid\")[0]\n\n",
"Just iterate the file putting every line into a List or a hashtable. Then iterate the collection and for each match grab the two previous entries using the index of mat... | [
1,
0,
0
] | [] | [] | [
"append",
"list",
"python"
] | stackoverflow_0002424411_append_list_python.txt |
Q:
creating a frame to put pictures in it and saving back to database
I'm working on a mobile site and what I have to do is 1.create a picture frame 2.add to it pictures posted by users individually, then save each picture back to the database. Does anyone know how to go about this
A:
Start with this: http://docs.d... | creating a frame to put pictures in it and saving back to database | I'm working on a mobile site and what I have to do is 1.create a picture frame 2.add to it pictures posted by users individually, then save each picture back to the database. Does anyone know how to go about this
| [
"Start with this: http://docs.djangoproject.com/en/dev/ref/models/fields/#imagefield\nIf you need to have multiple images for user, you probably need similar model:\nclass ImageUpload(Model):\n user = ForeignKey(User)\n image = ImageField(..)\n\n"
] | [
1
] | [] | [] | [
"django",
"python",
"python_imaging_library"
] | stackoverflow_0002423162_django_python_python_imaging_library.txt |
Q:
How to get a list with elements that are contained in two other lists?
We have two lists:
a=['1','2','3','4']
b=['2','3','4','5']
How to get a list with elements that are contained in both lists:
a_and_b=['2','3','4']
and a list with elements that are contained only in one list, but not the other:
only_a=['1']
o... | How to get a list with elements that are contained in two other lists? | We have two lists:
a=['1','2','3','4']
b=['2','3','4','5']
How to get a list with elements that are contained in both lists:
a_and_b=['2','3','4']
and a list with elements that are contained only in one list, but not the other:
only_a=['1']
only_b=['5']
Yes, I can use cycles, but it's lame =)
| [
"if order is not important\n>>> a=['1','2','3','4']\n>>> b=['2','3','4','5']\n>>> set(a) & set(b)\nset(['3', '2', '4'])\n\nonly a\n>>> set(a).difference(b) # or set(a) - set(b)\nset(['1'])\n\nonly b\n>>> set(b).difference(a) # or set(b) - set(a)\nset(['5'])\n\n",
"Simply with the use of sets:\n>>> a=['1','2','3'... | [
8,
5
] | [] | [] | [
"python"
] | stackoverflow_0002424700_python.txt |
Q:
How to save django FileField to user folder?
I've got a model like this
def upload_location(instance, filename):
return 'validate/%s/builds/%s' % (get_current_user(), filename)
class MidletPair(models.Model):
jad_file = models.FileField(upload_to = upload_location)
jar_file = models.FileField(upload... | How to save django FileField to user folder? | I've got a model like this
def upload_location(instance, filename):
return 'validate/%s/builds/%s' % (get_current_user(), filename)
class MidletPair(models.Model):
jad_file = models.FileField(upload_to = upload_location)
jar_file = models.FileField(upload_to = upload_location)
upload_to=tempfile.ge... | [
"The current user is stored in the request object, and you can't get that in a model method unless you pass it in from elsewhere - which you can't do in the upload_to function.\nSo you'll need to approach this in a different manner - I would suggest doing it at the form level. You can pass the request object into t... | [
8,
5,
4
] | [] | [] | [
"django",
"django_models",
"python",
"upload"
] | stackoverflow_0000858213_django_django_models_python_upload.txt |
Q:
Testing for Inactivity in Python on Mac
Is there a way to test, using Python, how long the system has been idle on Mac? Or, failing that, even if the system is currently idle?
Answer
Using the information from the accepted solution, here is an ugly but functional and fairly efficient function for the job:
from sub... | Testing for Inactivity in Python on Mac | Is there a way to test, using Python, how long the system has been idle on Mac? Or, failing that, even if the system is currently idle?
Answer
Using the information from the accepted solution, here is an ugly but functional and fairly efficient function for the job:
from subprocess import *
def idleTime():
'''Retu... | [
"Untested (for now), but according to this thread you could parse the output of \n\nioreg -c IOHIDSystem\n\n"
] | [
2
] | [] | [] | [
"macos",
"python"
] | stackoverflow_0002425087_macos_python.txt |
Q:
Does the MySQLdb module support prepared statements?
Does MySQLdb support server-side prepared statements? I can't figure this out from its manual.
A:
Check the MySQLdb Package Comments:
"Parameterization" is done in MySQLdb by escaping strings and then blindly interpolating them into the query, instead of usin... | Does the MySQLdb module support prepared statements? | Does MySQLdb support server-side prepared statements? I can't figure this out from its manual.
| [
"Check the MySQLdb Package Comments:\n\n\"Parameterization\" is done in MySQLdb by escaping strings and then blindly interpolating them into the query, instead of using the MYSQL_STMT API. As a result unicode strings have to go through two intermediate representations (encoded string, escaped encoded string) before... | [
18,
12
] | [] | [] | [
"mysql",
"prepared_statement",
"python"
] | stackoverflow_0002424531_mysql_prepared_statement_python.txt |
Q:
Python: PSP & HTML tables
I have a python psp page code is shown below. Currently it only prints out the characters in single rows of 60, with the character count in the left column.
<table>
<%
s = ''.join(aa[i] for i in table if i in aa)
for i in range(0, len(s), 60):
req.write('<tr><td><TT>%04d</td><td><TT>%... | Python: PSP & HTML tables | I have a python psp page code is shown below. Currently it only prints out the characters in single rows of 60, with the character count in the left column.
<table>
<%
s = ''.join(aa[i] for i in table if i in aa)
for i in range(0, len(s), 60):
req.write('<tr><td><TT>%04d</td><td><TT>%s</TT></td></tr>' % (i+1, s[i:i... | [
"for k in s[i:i+60]:\n req.write('<td>%s</td>' % k)\nreq.write('</tr>')\n\n"
] | [
0
] | [] | [] | [
"html",
"html_table",
"python",
"python_server_pages"
] | stackoverflow_0002425787_html_html_table_python_python_server_pages.txt |
Q:
django forms MultipleChoiceField reverts to original value on save
I have wrote a custom MultipleChoiceField. I have everything working ok but when I submit the form the selected values go back to the original choices even though the form validates ok.
my code looks something like this:
class ProgrammeField(forms... | django forms MultipleChoiceField reverts to original value on save | I have wrote a custom MultipleChoiceField. I have everything working ok but when I submit the form the selected values go back to the original choices even though the form validates ok.
my code looks something like this:
class ProgrammeField(forms.MultipleChoiceField):
widget = widgets.SelectMultiple
class Progra... | [
"You're always passing back an unbound instance of the form, try this:\nview.py\nif request.method == 'POST':\n form = ProgrammeForm(user=request.user, data=request.POST)\n if form.is_valid():\n form.save()\nelse: ##this is the changge\n form = ProgrammeForm(request.user)\nreturn render_to_response(... | [
3
] | [] | [] | [
"django",
"django_forms",
"python"
] | stackoverflow_0002425668_django_django_forms_python.txt |
Q:
Django deployment. Error loading MySQLdb module. Trouble reading/writing from /tmp directory
I'm deploying my Django app to another host/server using mod_wsgi and MySQLdb. Right now, I'm getting a 500 error with the following log:
ImproperlyConfigured: Error loading MySQLdb module: /tmp/MySQL_python-1.2.3c1-py2.4-... | Django deployment. Error loading MySQLdb module. Trouble reading/writing from /tmp directory | I'm deploying my Django app to another host/server using mod_wsgi and MySQLdb. Right now, I'm getting a 500 error with the following log:
ImproperlyConfigured: Error loading MySQLdb module: /tmp/MySQL_python-1.2.3c1-py2.4-linux-i686.egg-tmp/_mysql.so: failed to map segment from shared object: Operation not permitted
Di... | [
"Point the WSGIPythonEggs directive to a writable, executable path.\n"
] | [
1
] | [] | [] | [
"apache",
"django",
"mysql",
"python"
] | stackoverflow_0002425715_apache_django_mysql_python.txt |
Q:
Requesting a JavaScript property in Python (GAE)
I'm currently making an iphone web app based on Google App Engine (python). I need to check if the user is browsing not through safari but by the home screen. I can check this with an read-only 'window.navigator.standalone' Boolean JavaScript property as read on: ht... | Requesting a JavaScript property in Python (GAE) | I'm currently making an iphone web app based on Google App Engine (python). I need to check if the user is browsing not through safari but by the home screen. I can check this with an read-only 'window.navigator.standalone' Boolean JavaScript property as read on: https://developer.apple.com/library/archive/documentatio... | [
"According to this page on HTTP headers and MobileSafari, you can tell if the user has launched your site from their home screen by testing to see whether the string Safari is found in the HTTP_USER_AGENT header. If it's missing, they are browsing from the home screen.\nThis seems awfully fragile (and doesn't appe... | [
2
] | [] | [] | [
"google_app_engine",
"iphone",
"javascript",
"python"
] | stackoverflow_0002426232_google_app_engine_iphone_javascript_python.txt |
Q:
Python: list assignment out of range
This module is part of a simple todo app I made with Python...
def deleteitem():
showlist()
get_item = int(raw_input( "\n Enter number of item to delete: \n"))
f = open('todo.txt')
lines = f.readlines()
f.close()... | Python: list assignment out of range | This module is part of a simple todo app I made with Python...
def deleteitem():
showlist()
get_item = int(raw_input( "\n Enter number of item to delete: \n"))
f = open('todo.txt')
lines = f.readlines()
f.close()
lines[get_item] = ""
... | [
"Either catch IndexError when indexing or check the len() of the list beforehand.\n",
"First read the file, and then ask user in a loop, until the answer is acceptable:\nwhile True:\n get_item = int(raw_input( \"\\n Enter number of item to delete: \\n\"))\n if get_item >=0 and get_item < len(lines):\n ... | [
3,
3,
1,
0,
0,
0
] | [] | [] | [
"error_handling",
"list",
"python"
] | stackoverflow_0002425543_error_handling_list_python.txt |
Q:
Python server pages, tables and lists
I am using MySQL and python server pages to show the data in a database. In the db I have selected this data: a list x =[1, 61, 121, 181, 241, 301] and a list of lists z = (['a','b'],['c','d'],['e','f'],['g','h'],['i','j'],['k','l']) and I would like to put these in a table to... | Python server pages, tables and lists | I am using MySQL and python server pages to show the data in a database. In the db I have selected this data: a list x =[1, 61, 121, 181, 241, 301] and a list of lists z = (['a','b'],['c','d'],['e','f'],['g','h'],['i','j'],['k','l']) and I would like to put these in a table to look like:
001 a b
061 c d
121 e f
1... | [
"for index, (a, b) in zip(x, z):\n print(index, a, b) # format as appropriate\n\nAlso, your creation of z list might be improved upon:\nz = [dic[row[1]] for row in rows] # calling variable dict shadows built-in\n\nx can either be created as range(1, len(rows), 60)\n",
"You're doing the \"step b... | [
1,
1,
0,
0
] | [] | [] | [
"python",
"python_server_pages"
] | stackoverflow_0002426401_python_python_server_pages.txt |
Q:
Python: For loop problem
I have a simple for loop problem, when i run the code below it prints out series of 'blue green' sequences then a series of 'green' sequences. I want the output to be; if row[4] is equal to 1 to print blue else print green.
for row in rows:
for i in `row[4]`:
if i ==`... | Python: For loop problem | I have a simple for loop problem, when i run the code below it prints out series of 'blue green' sequences then a series of 'green' sequences. I want the output to be; if row[4] is equal to 1 to print blue else print green.
for row in rows:
for i in `row[4]`:
if i ==`1`:
print 'blu... | [
"Try something like this:\nfor i in xrange(len(rows)):\n if rows[i] == '1':\n print \"blue\"\n else:\n print \"green\"\n\nOr, since you don't actually seem to care about the index, you can of course do it more cleanly:\nfor r in rows:\n if r == \"1\":\n print \"blue\"\n else:\n print \"green\"\n\n",... | [
3,
2,
1
] | [] | [] | [
"for_loop",
"loops",
"python"
] | stackoverflow_0002426719_for_loop_loops_python.txt |
Q:
Create a user-group in linux using python
I want to create a user group using python on CentOS system. When I say 'using python' I mean I don't want to do something like os.system and give the unix command to create a new group. I would like to know if there is any python module that deals with this.
Searching on ... | Create a user-group in linux using python | I want to create a user group using python on CentOS system. When I say 'using python' I mean I don't want to do something like os.system and give the unix command to create a new group. I would like to know if there is any python module that deals with this.
Searching on the net did not reveal much about what I want, ... | [
"I don't know of a python module to do it, but the /etc/group and /etc/gshadow format is pretty standard, so if you wanted you could just open the files, parse their current contents and then add the new group if necessary.\nBefore you go doing this, consider:\n\nWhat happens if you try to add a group that already ... | [
11,
5,
1
] | [
"If you are looking at Python, then try this program. Its fairly simple to use, and the code can easily be customized http://aleph-null.tv/downloads/mpb-adduser-1.tgz\n"
] | [
-2
] | [
"linux",
"python",
"usergroups"
] | stackoverflow_0001570401_linux_python_usergroups.txt |
Q:
Compare DB row values efficiently
I want to loop through a database of documents and calculate a pairwise comparison score.
A simplistic, naive method would nest a loop within another loop. This would result in the program comparing documents twice and also comparing each document to itself.
Is there a name for t... | Compare DB row values efficiently | I want to loop through a database of documents and calculate a pairwise comparison score.
A simplistic, naive method would nest a loop within another loop. This would result in the program comparing documents twice and also comparing each document to itself.
Is there a name for the algorithm for doing this task effici... | [
"Assume all items have a number ItemNumber\nSimple solution -- always have the 2nd element's ItemNumber greater than the first item.\neg\nfor (firstitem = 1 to maxitemnumber)\n for (seconditem = firstitemnumber+1 to maxitemnumber)\n compare(firstitem, seconditem)\n\nvisual note: if you think of the compare as a... | [
3,
2,
0,
0
] | [] | [] | [
"database",
"logic",
"mysql",
"python"
] | stackoverflow_0002426246_database_logic_mysql_python.txt |
Q:
PostgreSQL pgdb driver raises "can't rollback" exception
for some reason I'm experiencing the Operational Error with "can't rollback" message when I attempt to roll back my transaction in the following context:
try:
cursors[instance].execute("lock revision, app, timeout IN SHARE MODE")
cursors[instance].ex... | PostgreSQL pgdb driver raises "can't rollback" exception | for some reason I'm experiencing the Operational Error with "can't rollback" message when I attempt to roll back my transaction in the following context:
try:
cursors[instance].execute("lock revision, app, timeout IN SHARE MODE")
cursors[instance].execute("insert into app (type, active, active_revision, content... | [
"You are looking in the wrong place. What does the PostgreSQL log say about what you are doing?\n",
"What happens if you exclude the lock statement?\nThis is what's happening inside pgdb.py:\ndef rollback(self):\n \"\"\"Roll back to the start of any pending transaction.\"\"\"\n if self._cnx:\n if sel... | [
1,
0,
0
] | [] | [] | [
"exception",
"postgresql",
"python",
"transactions"
] | stackoverflow_0002419500_exception_postgresql_python_transactions.txt |
Q:
Introspection of win32com module / pythoncom module
what is the best way to see what all functions that can be performed using pythoncom module?
Specifically, i was working with the win32com module to operate upon excel files. I was not able to find introspection for it as we do for the rest of the modules.
Can an... | Introspection of win32com module / pythoncom module | what is the best way to see what all functions that can be performed using pythoncom module?
Specifically, i was working with the win32com module to operate upon excel files. I was not able to find introspection for it as we do for the rest of the modules.
Can anyone please suggest how can i retrieve this information?
| [
"run the make.py file in \\lib\\site-packages\\win32com\\client.\nWhen you run it, a dialog comes up showing installed COM objects... choose the one for the Excel Ojbect library and you'll get something like this:\nc:\\Python26\\Lib\\site-packages\\win32com\\client>makepy.py\nGenerating to C:\\Python26\\lib\\site-p... | [
5,
2
] | [] | [] | [
"python"
] | stackoverflow_0002379809_python.txt |
Q:
Python and a "time value of money" problem
(I asked this question earlier today, but I did a poor job of explaining myself. Let me try again)
I have a client who is an industrial maintenance company. They sell service agreements that are prepaid 20 hour blocks of a technician's time. Some of their larger customer... | Python and a "time value of money" problem | (I asked this question earlier today, but I did a poor job of explaining myself. Let me try again)
I have a client who is an industrial maintenance company. They sell service agreements that are prepaid 20 hour blocks of a technician's time. Some of their larger customers might burn through that agreement in two weeks... | [
"If you want to consider the problem in terms of present value of future revenue (that's what \"time value of money\" implies to me), then you have the following parameters: discount rate D (on a monthly basis for convenience), time T a customer will take to exhaust their prepaid hours, likelihood L that they will ... | [
1,
0
] | [] | [] | [
"finance",
"math",
"python"
] | stackoverflow_0002376355_finance_math_python.txt |
Q:
How does this decorator make a call to the 'register' method?
I'm trying to understand what is going on in the decorator @not_authenticated.
The next step in the TraceRoute is to the method 'register' which is also located in django_authopenid/views.py which I just don't understand because I don't see anywhere th... | How does this decorator make a call to the 'register' method? | I'm trying to understand what is going on in the decorator @not_authenticated.
The next step in the TraceRoute is to the method 'register' which is also located in django_authopenid/views.py which I just don't understand because I don't see anywhere that register is even mentioned in signin()
How is the method 'regist... | [
"Without attempting to understand all of that why don't you insert:\nimport pdb; pdb.set_trace()\n\nwherever this \"register\" method is?\nThan hit \"bt\"\n",
"Are you sure the call gets into signin()?\nBecause if the user is already authenticated (request.user.is_authenticated()) , the openid code is called dire... | [
0,
0,
0
] | [] | [] | [
"decorator",
"django",
"python"
] | stackoverflow_0002313666_decorator_django_python.txt |
Q:
Python appengine Query does not work when using a variable
I am trying to use a fetcher method to retrieve items from my datastore. If I use the following
def getItem(item_id):
q = Item.all()
q.filter("itemid = ", item_id)
It fails because nothing is returned. If I hard code in an item like
def getItem... | Python appengine Query does not work when using a variable | I am trying to use a fetcher method to retrieve items from my datastore. If I use the following
def getItem(item_id):
q = Item.all()
q.filter("itemid = ", item_id)
It fails because nothing is returned. If I hard code in an item like
def getItem(item_id):
q = Item.all()
q.filter("itemid = ", 9000)
i... | [
"Does it make any difference if you do this:\ndef getItem(item_id):\n q = Item.all()\n q.filter(\"itemid = \", int(item_id))\n\nThe most likely cause of the problem that I can see is that the item_id parameter may be a string even though it is holding a numerical value. Coerce it to an int, and see if that ma... | [
2
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0002428047_google_app_engine_google_cloud_datastore_python.txt |
Q:
Silence output from SimpleXMLRPCServer
I am running an xml-rpc server using SimpleXMLRPCServer from the stdlib.
My code looks something like this:
import SimpleXMLRPCServer
import socket
class RemoteStarter:
def start(self):
return 'foo'
rs = RemoteStarter()
host = socket.gethostbyaddr(socket.gethost... | Silence output from SimpleXMLRPCServer | I am running an xml-rpc server using SimpleXMLRPCServer from the stdlib.
My code looks something like this:
import SimpleXMLRPCServer
import socket
class RemoteStarter:
def start(self):
return 'foo'
rs = RemoteStarter()
host = socket.gethostbyaddr(socket.gethostname())[0]
port = 9000
server = SimpleXMLRPC... | [
"the answer is:\npass logRequests=False to SimpleXMLRPCServer when you create it:\nserver = SimpleXMLRPCServer.SimpleXMLRPCServer((host, port), logRequests=False)\n\n"
] | [
9
] | [] | [] | [
"python",
"xml_rpc"
] | stackoverflow_0002419405_python_xml_rpc.txt |
Q:
How to create instances of a class from a static method?
Here is my problem. I have created a pretty heavy readonly class making many database calls with a static "factory" method. The goal of this method is to avoid killing the database by looking in a pool of already-created objects if an identical instance of t... | How to create instances of a class from a static method? | Here is my problem. I have created a pretty heavy readonly class making many database calls with a static "factory" method. The goal of this method is to avoid killing the database by looking in a pool of already-created objects if an identical instance of the same object (same type, same init parameters) already exist... | [
"import weakref\n\nclass A(object):\n _get_obj_cache = weakref.WeakValueDictionary()\n @classmethod\n def get_obj(cls, identifier):\n cache = cls._get_obj_cache\n obj = cache.get((cls, identifier))\n if obj is None:\n obj = cache[(cls, identifier)] = cls(identifier)\n return obj\n\nclass B(A):\n... | [
5,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0002426690_python.txt |
Q:
datetime command line argument in python 2.4
I want to pass a datetime value into my python script on the command line. My first idea was to use optparse and pass the value in as a string, then use datetime.strptime to convert it to a datetime. This works fine on my machine (python 2.6), but I also need to run thi... | datetime command line argument in python 2.4 | I want to pass a datetime value into my python script on the command line. My first idea was to use optparse and pass the value in as a string, then use datetime.strptime to convert it to a datetime. This works fine on my machine (python 2.6), but I also need to run this script on machines that are running python 2.4, ... | [
"Go by way of the time module, which did already have strptime in 2.4:\n>>> import time\n>>> t = time.strptime(\"2010-02-02 7:31\", \"%Y-%m-%d %H:%M\")\n>>> t\n(2010, 2, 2, 7, 31, 0, 1, 33, -1)\n>>> import datetime\n>>> datetime.datetime(*t[:6])\ndatetime.datetime(2010, 2, 2, 7, 31)\n\n"
] | [
16
] | [] | [] | [
"datetime",
"python"
] | stackoverflow_0002428746_datetime_python.txt |
Q:
os.path.getmtime() doesn't return fraction of a second
I compiled python 2.6.4 for centos 5.3 and find this issue that os.path.getmtime() or os.stat().m_time doesn't have the fraction part. As per docs, if os.stat_float_times() returns True, then it should return float value. In my case, I do see it as float, but ... | os.path.getmtime() doesn't return fraction of a second | I compiled python 2.6.4 for centos 5.3 and find this issue that os.path.getmtime() or os.stat().m_time doesn't have the fraction part. As per docs, if os.stat_float_times() returns True, then it should return float value. In my case, I do see it as float, but no fraction part (it is 0).
In [3]: os.path.getmtime('/tmp')... | [
"This is a filesystem limitation, rather than a Python one. Centos is still on ext3, which provides integer mtimes. You can see this if you display the mtimes with ls. Try\nls -ld --full-time /tmp\n\nOn my ext3 Centos box, I get\ndrwxrwxrwt 11 root root 69632 2010-03-11 13:16:30.000000000 -0800 /tmp\n\nOn my ext4 U... | [
6
] | [] | [] | [
"centos",
"linux",
"python"
] | stackoverflow_0002428556_centos_linux_python.txt |
Q:
Most efficent way to create all possible combinations of four lists in Python?
I have four different lists. headers, descriptions, short_descriptions and misc. I want to combine these into all the possible ways to print out:
header\n
description\n
short_description\n
misc
like if i had (i'm skipping short_descrip... | Most efficent way to create all possible combinations of four lists in Python? | I have four different lists. headers, descriptions, short_descriptions and misc. I want to combine these into all the possible ways to print out:
header\n
description\n
short_description\n
misc
like if i had (i'm skipping short_description and misc in this example for obvious reasons)
headers = ['Hello there', 'Hi the... | [
"Is this what you're looking for?\nhttp://docs.python.org/library/itertools.html#itertools.product\n",
"import itertools\n\nheaders = ['Hello there', 'Hi there!']\ndescription = ['I like pie', 'Ho ho ho']\n\nfor p in itertools.product(headers,description):\n print('\\n'.join(p)+'\\n')\n\n",
"A generator expr... | [
10,
4,
3,
0,
0
] | [] | [] | [
"algorithm",
"python"
] | stackoverflow_0002390316_algorithm_python.txt |
Q:
Mimic Haskell with Python
Haskell provides the feature something like f = f1 . f2
How can I mimic that with Python?
For example, if I have to do the 'map' operation two times, is there any way to do something like map . map in Python?
x = ['1','2','3']
x = map(int,x)
x = map(lambda i:i+1, x)
A:
I think you a... | Mimic Haskell with Python | Haskell provides the feature something like f = f1 . f2
How can I mimic that with Python?
For example, if I have to do the 'map' operation two times, is there any way to do something like map . map in Python?
x = ['1','2','3']
x = map(int,x)
x = map(lambda i:i+1, x)
| [
"I think you are looking for function composition in Python.\nYou can do this:\nf = lambda x: f1(f2(x))\n\n",
"There have been several proposals for a compose operation, but none have been formalized. In the meantime it is possible to use a list comprehension or a generator expression to apply complex transformat... | [
2,
1,
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0002429039_python.txt |
Q:
How to determine if the given object is of given type in Python?
I always thought operator is determined if the given variable is of the given type. But I just determined it was not true:
>>> class A():
pass
...
>>> a = A()
>>> a is A
False
How do I test if a is of type class A?
Please advise.
Thanks, Boda... | How to determine if the given object is of given type in Python? | I always thought operator is determined if the given variable is of the given type. But I just determined it was not true:
>>> class A():
pass
...
>>> a = A()
>>> a is A
False
How do I test if a is of type class A?
Please advise.
Thanks, Boda Cydo.
| [
"You want isinstance(a, A).\nKeep in mind, it might be better to avoid the isinstance check by adding methods to A that make it do what you want without explicitly determining that it is an A.\nis determines if two objects are the same object.\n",
"isinstance(a,A)\n"
] | [
7,
2
] | [] | [] | [
"python",
"types"
] | stackoverflow_0002429164_python_types.txt |
Q:
Merging all sub-arrays with mutual elements into one sub-array
I need to find all sub-arrays which share any mutual element and merge them into one sub-array.
(Implementing in Python but any algorithmic idea would be helpful)
Multidimensional array structure:
categories = {'car':['automobile','auto'],
... | Merging all sub-arrays with mutual elements into one sub-array | I need to find all sub-arrays which share any mutual element and merge them into one sub-array.
(Implementing in Python but any algorithmic idea would be helpful)
Multidimensional array structure:
categories = {'car':['automobile','auto'],
'bike':['vehicle','motorcycle','motorbike','automobile'],
... | [
"Note that there is no \"first key\" -- dicts don't keep order, so if you need some order preserved you'll need to start from some different, alternative data structure.\nApart from order-related issues, I'd start with something like:\ndef merged(dictoflists):\n result = dict()\n reversed = dict()\n for k, l in ... | [
2,
0,
0
] | [] | [] | [
"algorithm",
"arrays",
"performance",
"python"
] | stackoverflow_0002098948_algorithm_arrays_performance_python.txt |
Q:
Difference between Python dynamic field lookup
What's the difference (if any) between
model.__dict__['title_en']
and
model.__getattribute__('title_en')
and what's best practice ?
A:
Best practice? Use getattr.
getattr(model, 'title_en')
You only want __getattr__ or __getattribute__ when you want to override t... | Difference between Python dynamic field lookup | What's the difference (if any) between
model.__dict__['title_en']
and
model.__getattribute__('title_en')
and what's best practice ?
| [
"Best practice? Use getattr.\ngetattr(model, 'title_en')\n\nYou only want __getattr__ or __getattribute__ when you want to override the default attribute fetching mechanism.\n",
"As others have said, the getattr built-in is the right way to get an attribute (in general you don't access Python special methods dire... | [
5,
5,
1
] | [] | [] | [
"python"
] | stackoverflow_0002429232_python.txt |
Q:
Why is Decimal('0') > 9999.0 True in Python?
This is somehow related to my question Why is ''>0 True in Python?
In Python 2.6.4:
>> Decimal('0') > 9999.0
True
From the answer to my original question I understand that when comparing objects of different types in Python 2.x the types are ordered by their name. But ... | Why is Decimal('0') > 9999.0 True in Python? | This is somehow related to my question Why is ''>0 True in Python?
In Python 2.6.4:
>> Decimal('0') > 9999.0
True
From the answer to my original question I understand that when comparing objects of different types in Python 2.x the types are ordered by their name. But in this case:
>> type(Decimal('0')).__name__ > typ... | [
"Because the decimal module does not compare against any type except long, int, and Decimal. In all other cases, decimal silently returns the \"not something it knows about object\" as greater. You can see this behavior in the _convert_other() function of decimal.py\nSilly, silly Decimal class. \nOh, see http:/... | [
12,
1
] | [] | [] | [
"comparison",
"logic",
"operators",
"python",
"types"
] | stackoverflow_0002429475_comparison_logic_operators_python_types.txt |
Q:
python: variable not getting defined after several conditionals
For some reason this program is saying that 'switch' is not defined. What is going on?
#PYTHON 3.1.1
class mysrt:
def __init__(self):
self.DATA = open('ORDER.txt', 'r')
self.collect = 0
cache1 = str(self.DAT... | python: variable not getting defined after several conditionals | For some reason this program is saying that 'switch' is not defined. What is going on?
#PYTHON 3.1.1
class mysrt:
def __init__(self):
self.DATA = open('ORDER.txt', 'r')
self.collect = 0
cache1 = str(self.DATA.readlines())
cache2 = []
for i in range(len... | [
"If CACHE_LIST_1 is an empty sequence then switch will never get bound.\n"
] | [
5
] | [] | [] | [
"class",
"python",
"python_3.x"
] | stackoverflow_0002429637_class_python_python_3.x.txt |
Q:
What is the purpose of a zip function (as in Python or C# 4.0)?
Someone asked How to do Python’s zip in C#?...
...which leads me to ask, what good is zip? In what scenarios do I need this? Is it really so foundational that I need this in the base class library?
A:
A use case:
>>> fields = ["id", "name", "loc... | What is the purpose of a zip function (as in Python or C# 4.0)? | Someone asked How to do Python’s zip in C#?...
...which leads me to ask, what good is zip? In what scenarios do I need this? Is it really so foundational that I need this in the base class library?
| [
"A use case:\n>>> fields = [\"id\", \"name\", \"location\"]\n>>> values = [\"13\", \"bill\", \"redmond\"]\n>>> dict(zip(fields, values))\n{'location': 'redmond', 'id': '13', 'name': 'bill'}\n\nTry doing this without zip...\n",
"Someone actually asked a question here fairly recently that I answered with the Zip ex... | [
13,
13,
12,
8,
8,
3,
2
] | [] | [] | [
"c#",
"python",
"zip"
] | stackoverflow_0002429692_c#_python_zip.txt |
Q:
How to detect an 'image area' percentage inside an image?
Mhh, kinda hard to explain with my poor english ;)
So, lets say I have an image, doesnt matter what kind of (gif, jpg, png) with 200x200 pixel size (total area 40000 pixels)
This image have a background, that can be trasparent, or every color (but i know th... | How to detect an 'image area' percentage inside an image? | Mhh, kinda hard to explain with my poor english ;)
So, lets say I have an image, doesnt matter what kind of (gif, jpg, png) with 200x200 pixel size (total area 40000 pixels)
This image have a background, that can be trasparent, or every color (but i know the background-color in advance).
Lets say that in the middle of ... | [
"from PIL import Image\nimage = Image.open(\"pepper.png\")\nbg = image.getpixel((0,0))\nwidth, height = image.size\nbg_count = next(n for n,c in image.getcolors(width*height) if c==bg)\nimg_count = width*height - bg_count\nimg_percent = img_count*100.0/width/height\n\ngives 7.361875 for both images\n",
"I am assu... | [
4,
0,
0,
0
] | [] | [] | [
"image_manipulation",
"image_processing",
"php",
"python",
"web_applications"
] | stackoverflow_0002428916_image_manipulation_image_processing_php_python_web_applications.txt |
Q:
Need help understanding "TypeError: default __new__ takes no parameters" error in python
For some reason I am having trouble getting my head around __init__ and __new__. I have a bunch of code that runs fine from the terminal, but when I load it as a plugin for Google Quick Search Box, I get the error TypeError: d... | Need help understanding "TypeError: default __new__ takes no parameters" error in python | For some reason I am having trouble getting my head around __init__ and __new__. I have a bunch of code that runs fine from the terminal, but when I load it as a plugin for Google Quick Search Box, I get the error TypeError: default __new__ takes no parameters.
I have been reading about the error, and it's kind of maki... | [
"Simplest way to reproduce your problem:\n>>> class Bah(object): pass\n... \n>>> x = Bah(23)\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in ?\nTypeError: default __new__ takes no parameters\n\nSo it looks like there's a class in your code (not when run from the terminal, but then you do very di... | [
7,
2
] | [] | [] | [
"init",
"python",
"typeerror"
] | stackoverflow_0002429899_init_python_typeerror.txt |
Q:
Python help() function and the string.title function
Why doesn't
import string;help(string.title)
seem to work but
help(string.strip)
works just fine?
I get the error
Traceback (most recent call last):
File "", line 1, in
AttributeError: 'module' object has no
attribute 'title'
A:
title is ... | Python help() function and the string.title function | Why doesn't
import string;help(string.title)
seem to work but
help(string.strip)
works just fine?
I get the error
Traceback (most recent call last):
File "", line 1, in
AttributeError: 'module' object has no
attribute 'title'
| [
"title is a method on objects of type str, not a function in the string module. That means you can do \"foo\".title() or str.title(\"foo\") but not string.title(\"foo\").\n",
"help(str.title) seems to work just fine.\n"
] | [
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0002430166_python.txt |
Q:
Problem with makefile
I created a python project in IDE Anjuta, added some python files and the problem follows.
I need that would make the program after a few .py files lying in src copied to dir /usr/bin. Anjuta generates enormous configure- and makefiles. 'll Show you need to register and where that would make... | Problem with makefile | I created a python project in IDE Anjuta, added some python files and the problem follows.
I need that would make the program after a few .py files lying in src copied to dir /usr/bin. Anjuta generates enormous configure- and makefiles. 'll Show you need to register and where that would make described above.
Thank you... | [
"I'm also having trouble understanding your question, but it sounds like you want to run make and have the py files copied to a certain directory. This would look like:\n$(shell cp *.py /usr/bin)\n\nHope this helps.\n-tjw\n"
] | [
0
] | [] | [] | [
"anjuta",
"installation",
"makefile",
"python"
] | stackoverflow_0002325646_anjuta_installation_makefile_python.txt |
Q:
Add Keyboard Binding To Existing Emacs Mode
I'm attempting my first modification of Emacs. I recorded a little keyboard macro and had Emacs spit it out as elisp, resulting in:
(setq add-docstring
"\C-rdef\C-n\C-a\C-m\C-p\C-i\C-u6\"\C-u3\C-b")
(global-set-key "\C-c\C-d" 'add-docstring)
Searching the Emacs refe... | Add Keyboard Binding To Existing Emacs Mode | I'm attempting my first modification of Emacs. I recorded a little keyboard macro and had Emacs spit it out as elisp, resulting in:
(setq add-docstring
"\C-rdef\C-n\C-a\C-m\C-p\C-i\C-u6\"\C-u3\C-b")
(global-set-key "\C-c\C-d" 'add-docstring)
Searching the Emacs reference, though, revealed that C-c C-d is already b... | [
"It turns out, C-c C-d is already bound in python-mode (to 'python-pdbtrack-toggle-stack-tracking), so you may want to revisit your choice of key binding.\nNote: if you just want to cut/paste a solution, jump to the end of the answer. Read on for an explanation of how to get there - in case you want to do it again... | [
16,
4
] | [] | [] | [
"elisp",
"emacs",
"keyboard_shortcuts",
"python"
] | stackoverflow_0002429603_elisp_emacs_keyboard_shortcuts_python.txt |
Q:
Mocking imported modules in Python
I'm trying to implement unit tests for function that uses imported external objects.
For example helpers.py is:
import os
import pylons
def some_func(arg):
...
var1 = os.path.exist(...)
var2 = os.path.getmtime(...)
var3 = pylons.request.environ['HTTP_HOST']
...
S... | Mocking imported modules in Python | I'm trying to implement unit tests for function that uses imported external objects.
For example helpers.py is:
import os
import pylons
def some_func(arg):
...
var1 = os.path.exist(...)
var2 = os.path.getmtime(...)
var3 = pylons.request.environ['HTTP_HOST']
...
So when I'm creating unit test for it I d... | [
"Use voidspace's mocking library and it's patching/wrapping ability.\nhttp://www.voidspace.org.uk/python/mock/patch.html\n",
"Well, in minimock there is an easier paradigm for this than what you are using above:\n>>> from minimock import mock\n>>> import os.path\n>>> mock('os.path.isfile', returns=True)\n\nSee ht... | [
2,
1
] | [] | [] | [
"mocking",
"python",
"unit_testing"
] | stackoverflow_0002348712_mocking_python_unit_testing.txt |
Q:
How to ping an ip and get only the ms in the Tk with Python?
I want to make a little tk app that continuous ping an ip and only show the MS, like, "10ms"
how could I do?
A:
If you want to use Windows ping, you'll have to parse the output from the command line.
This is very specific, but should work:
import os
w... | How to ping an ip and get only the ms in the Tk with Python? | I want to make a little tk app that continuous ping an ip and only show the MS, like, "10ms"
how could I do?
| [
"If you want to use Windows ping, you'll have to parse the output from the command line.\nThis is very specific, but should work:\nimport os\nwhile(1):\n ping = os.popen('ping www.google.com -n 1')\n result = ping.readlines()\n msLine = result[-1].strip()\n print msLine.splot(' = ')[-1]\n\n",
"To cont... | [
3,
0
] | [] | [] | [
"ping",
"python",
"windows"
] | stackoverflow_0002430519_ping_python_windows.txt |
Q:
Old desktop programmer wants to create S+S project
I have an idea for a product that I want to be web-based. But because I live in a part of the world where the internet is not always available, there needs to be a client desktop component that is available for when the internet is down. Also, I have been a SQL pr... | Old desktop programmer wants to create S+S project | I have an idea for a product that I want to be web-based. But because I live in a part of the world where the internet is not always available, there needs to be a client desktop component that is available for when the internet is down. Also, I have been a SQL programmer, a desktop application programmer using dBase, ... | [
"If you want a 'desktop component' that is available for you to do development on whenever your internet is out, you could really choose any of those technologies. You can always have a local server (like apache) running on your machine, as well as a local sql database, though if your database contains a large amou... | [
0,
0,
0
] | [] | [] | [
"php",
"programming_languages",
"python",
"ruby_on_rails",
"saas"
] | stackoverflow_0002428077_php_programming_languages_python_ruby_on_rails_saas.txt |
Q:
Which XML library for what purposes?
A search for "python" and "xml" returns a variety of libraries for combining the two.
This list probably faulty:
xml.dom
xml.etree
xml.sax
xml.parsers.expat
PyXML
beautifulsoup?
HTMLParser
htmllib
sgmllib
Be nice if someone can offer a quick summary of when to use which, and ... | Which XML library for what purposes? | A search for "python" and "xml" returns a variety of libraries for combining the two.
This list probably faulty:
xml.dom
xml.etree
xml.sax
xml.parsers.expat
PyXML
beautifulsoup?
HTMLParser
htmllib
sgmllib
Be nice if someone can offer a quick summary of when to use which, and why.
| [
"The DOM/SAX divide is a basic one. It applies not just to python since DOM and SAX are cross-language.\nDOM: read the whole document into memory and manipulate it.\nGood for:\n\ncomplex relationships across tags in the markup\nsmall intricate XML documents\nCautions:\n\n\nEasy to use excessive memory\n\n\nSAX: par... | [
6,
4,
1,
1
] | [] | [] | [
"python",
"xml"
] | stackoverflow_0002430423_python_xml.txt |
Q:
Passing keyword arguments to a class method decorator
I have a class that has an output() method which returns a matplotlib Figure instance. I have a decorator I wrote that takes that fig instance and turns it into a Django response object.
My decorator looks like this:
class plot_svg(object):
def __init__(sel... | Passing keyword arguments to a class method decorator | I have a class that has an output() method which returns a matplotlib Figure instance. I have a decorator I wrote that takes that fig instance and turns it into a Django response object.
My decorator looks like this:
class plot_svg(object):
def __init__(self, view):
self.view = view
def __call__(self, ... | [
"Right: when you decorate with a class, instead of with a function, you have to make it a descriptor (give it a __get__ method, at least) to get the \"automatic self\". Simplest is to decorate with a function instead:\ndef plot_svg(view):\n\n def wrapper(*args, **kwargs):\n print args, kwargs\n fi... | [
5,
1
] | [] | [] | [
"decorator",
"python"
] | stackoverflow_0002430759_decorator_python.txt |
Q:
A list vs. tuple situation in Python
Is there a situation where the use of a list leads to an error, and you must use a tuple instead?
I know something about the properties of both tuples and lists, but not enough to find out the answer to this question. If the question would be the other way around, it would be t... | A list vs. tuple situation in Python | Is there a situation where the use of a list leads to an error, and you must use a tuple instead?
I know something about the properties of both tuples and lists, but not enough to find out the answer to this question. If the question would be the other way around, it would be that lists can be adjusted but tuples don't... | [
"You can use tuples as dictionary keys, because they are immutable, but you can't use lists. Eg:\nd = {(1, 2): 'a', (3, 8, 1): 'b'} # Valid.\nd = {[1, 2]: 'a', [3, 8, 1]: 'b'} # Error.\n\n",
"Because of their immutable nature, tuples (unlike lists) are hashable. This is what allows tuples to be keys in dictiona... | [
15,
10,
4
] | [] | [] | [
"list",
"python",
"tuples"
] | stackoverflow_0002280881_list_python_tuples.txt |
Q:
Technique to limit number of instances of our application under Terminal Server
I'm looking for simple ways to monitor and limit the number of instances of our application under Terminal Server (2003 and 2008).
The purpose of this restriction is to make sure we don't overload our servers. This is an internal admin... | Technique to limit number of instances of our application under Terminal Server | I'm looking for simple ways to monitor and limit the number of instances of our application under Terminal Server (2003 and 2008).
The purpose of this restriction is to make sure we don't overload our servers. This is an internal administrative requirement - I am not looking for a licensing solution.
The application in... | [
"The various instances of your application need some way to communicate with one another. When an instance starts up, it asks the question, 'how many are already running?'. If there are more than the allowed n, it chooses not to start up.\nOne implementation approach might be to make n files to lock for the n insta... | [
1,
1
] | [] | [] | [
"citrix",
"python",
"terminal_services"
] | stackoverflow_0002409200_citrix_python_terminal_services.txt |
Q:
Eclipse Pydev: Supress no-self errors in python wrappers generated with swig
when generating python wrappers with swig the python wrapper classes in the generated python file do not have an explicit self parameter, for example see below:
class PySwigIterator(_object):
def value(*args): return _spatiotemporalnm... | Eclipse Pydev: Supress no-self errors in python wrappers generated with swig | when generating python wrappers with swig the python wrapper classes in the generated python file do not have an explicit self parameter, for example see below:
class PySwigIterator(_object):
def value(*args): return _spatiotemporalnmf.PySwigIterator_value(*args)
def incr(*args): return _spatiotemporalnmf.PySwi... | [
"As from the documentation, any file with the comment \n#@PydevCodeAnalysisIgnore\n\ninside will not be analyzed.\nTherefore, you just need to add it to all SWIG-generated files, and you should be OK. It is just one place to change, and you could even write a very small processor that will add it automatically.\n"
... | [
1
] | [] | [] | [
"pydev",
"python",
"swig"
] | stackoverflow_0002431435_pydev_python_swig.txt |
Q:
doctest locally defined functions
is there any way to doctest locally defined functions? As an example I would want
def foo():
""" >>> foo()
testfoo"""
def foo2():
""" >>> 1/0 """
print 'testfoo'
foo2()
to NOT pass the test. But still I would not want to make foo2 global for the entire module.... | doctest locally defined functions | is there any way to doctest locally defined functions? As an example I would want
def foo():
""" >>> foo()
testfoo"""
def foo2():
""" >>> 1/0 """
print 'testfoo'
foo2()
to NOT pass the test. But still I would not want to make foo2 global for the entire module...
| [
"Thanks. I already feared there would be no way around code outside the docstring. Still I thought there might be a trick to import the locals of a function and thus get access to nested functions. Anyhow, a solution using Alex' approach would read\ndef foo(debug=False):\n \"\"\"\n >>> foo()\n testfoo\n ... | [
4,
1
] | [] | [] | [
"doctest",
"python"
] | stackoverflow_0002403237_doctest_python.txt |
Q:
using python 'with' statement with iterators?
I'm using Python 2.5. I'm trying to use this 'with' statement.
from __future__ import with_statement
a = []
with open('exampletxt.txt','r') as f:
while True:
a.append(f.next().strip().split())
print a
The contents of 'exampletxt.txt' are simple:
a
b
In th... | using python 'with' statement with iterators? | I'm using Python 2.5. I'm trying to use this 'with' statement.
from __future__ import with_statement
a = []
with open('exampletxt.txt','r') as f:
while True:
a.append(f.next().strip().split())
print a
The contents of 'exampletxt.txt' are simple:
a
b
In this case, I get the error:
Traceback (most recent ca... | [
"Raising StopIteration is what an iterator does when it gets to the end. Normally the for statement catches it silently and continues to the else clause, but if it's being iterated manually as in your case then the code has to be prepared to handle the exception itself.\n",
"Your while loop doesn't end, but the f... | [
3,
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0002430501_python.txt |
Q:
Python: Lits containg tuples and long int
I have a list containing a tuples and long integers the list looks like this:
table = [(1L,), (1L,), (1L,), (2L,), (2L,), (2L,), (3L,), (3L,)]
How do i convert the table to look like a formal list?
so the output would be:
table = ['1','1','1','2','2','2','3','3']
For ... | Python: Lits containg tuples and long int | I have a list containing a tuples and long integers the list looks like this:
table = [(1L,), (1L,), (1L,), (2L,), (2L,), (2L,), (3L,), (3L,)]
How do i convert the table to look like a formal list?
so the output would be:
table = ['1','1','1','2','2','2','3','3']
For information purposes the data was obtained from... | [
">>> table = [(1L,), (1L,), (1L,), (2L,), (2L,), (2L,), (3L,), (3L,)]\n>>> [int(e[0]) for e in table]\n[1, 1, 1, 2, 2, 2, 3, 3]\n\n>>> [str(e[0]) for e in table]\n['1', '1', '1', '2', '2', '2', '3', '3']\n\n",
"With itertools\nimport itertools\n\n>>> x=[(1L,), (1L,), (1L,), (2L,), (2L,), (2L,), (3L,), (3L,)]\n>>>... | [
8,
2,
1
] | [] | [] | [
"list",
"python",
"tuples"
] | stackoverflow_0002432402_list_python_tuples.txt |
Q:
Unbuffered subprocess output (last line missing)
I must be overlooking something terribly obvious. I need to execute a C program, display its output in real time and finally parse its last line, which should be straightforward as the last line printed is always the same.
process = subprocess.Popen(args, shell = Tr... | Unbuffered subprocess output (last line missing) | I must be overlooking something terribly obvious. I need to execute a C program, display its output in real time and finally parse its last line, which should be straightforward as the last line printed is always the same.
process = subprocess.Popen(args, shell = True,
stdout = subprocess.P... | [
"The problem is that you are reading lines till the process exits, (process.poll()) while you do use buffering because of the shell flag.\nYou would have to keep reading process.stdout till you reach the end of the file or the empty line.\n",
"readline() has to buffer the text, waiting for a new-line.\nYou'll alw... | [
3,
2
] | [] | [] | [
"popen",
"python",
"subprocess"
] | stackoverflow_0002432556_popen_python_subprocess.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.