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:
Array order in `numpy.dot`
In Python's numerical library NumPy, how does the numpy.dot function deal with arrays of different memory-order? numpy.dot(c-order, f-order) vs. dot(f-order, c-order) etc.
The reason I ask is that long time ago (numpy 1.0.4?), I made some tests and noticed numpy.dot performed worse than ... | Array order in `numpy.dot` | In Python's numerical library NumPy, how does the numpy.dot function deal with arrays of different memory-order? numpy.dot(c-order, f-order) vs. dot(f-order, c-order) etc.
The reason I ask is that long time ago (numpy 1.0.4?), I made some tests and noticed numpy.dot performed worse than calling dgemm from scipy.linalg ... | [
"Possibly what you were seeing may have been related to a blas-optimized dot import error being caught and handled silently (this code snippet is from numeric.py) \n# try to import blas optimized dot if available\ntry:\n # importing this changes the dot function for basic 4 types\n # to blas-optimized versio... | [
1
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0006061720_numpy_python.txt |
Q:
how to install python libraries in linux?
While I was installing Python libraries in linux, it throws below error. Can some one please help on this?
I ran below command to install
python setup.py install
o/p:
running install
running build
running build_ext
error: pyconfig.h: No such file or directory
A:
The fir... | how to install python libraries in linux? | While I was installing Python libraries in linux, it throws below error. Can some one please help on this?
I ran below command to install
python setup.py install
o/p:
running install
running build
running build_ext
error: pyconfig.h: No such file or directory
| [
"The first thing to try is to install the appropriate module via your package manager. Each distro has many, many, many Python modules already packaged and ready to go.\nIf you insist on installing a module from source then you'll need the development package for your distro's Python. This is usually called python-... | [
6
] | [] | [] | [
"python"
] | stackoverflow_0006165773_python.txt |
Q:
use python ctypes to interface with nvapi (follow up with demonstration code)
This is a follow up to my previous question: help with python ctypes and nvapi
I am posting another question because I already selected an answer in my previous question and the question has shifted direction now.
Using python, I am tryi... | use python ctypes to interface with nvapi (follow up with demonstration code) | This is a follow up to my previous question: help with python ctypes and nvapi
I am posting another question because I already selected an answer in my previous question and the question has shifted direction now.
Using python, I am trying to query nvapi.dll to get my gpu usage value.
This is how you would do it in C... | [
"\nIn order to query for the gpu usage I\n first need to call the\n NvAPI_Initialize function.\n\nThere are actually two initialization functions involved: the one from the static library nvapi.lib, which tries to dynamically load nvapi.dll, locates some functions and calls the second initialization function from... | [
4
] | [] | [] | [
"ctypes",
"nvidia",
"python"
] | stackoverflow_0006165628_ctypes_nvidia_python.txt |
Q:
How to call function in my python code on click button - from javascript onClick call Python
I'm trying to implement ajax on CherryPy site and I have problem. How to call function in my python code (function name: ajax_data is @cherrypy.expose and returns some json which I can easily processed ) on click button ( ... | How to call function in my python code on click button - from javascript onClick call Python | I'm trying to implement ajax on CherryPy site and I have problem. How to call function in my python code (function name: ajax_data is @cherrypy.expose and returns some json which I can easily processed ) on click button ( ) ? How to onClick to call ajax_data ? ( I looked first on Google but I find only when button is ... | [
"Ajax is initiated from Javascript in the the browser. I would recommend looking at Jquery and \nhttp://api.jquery.com/category/ajax/ and more specifically http://api.jquery.com/jQuery.getJSON/\nSimple example JS Code or call to the back end (NOTE: you will need to include jquery before this is called):\n$.getJSON... | [
0
] | [] | [] | [
"ajax",
"cherrypy",
"javascript",
"python"
] | stackoverflow_0006164765_ajax_cherrypy_javascript_python.txt |
Q:
Integrating Django with Amazon's Database 'SimpleDB'
Can somebody guide me to develop a django app with SimpleDB(Amazon's Database) as its database. I couldnt find any tutorials on searching. Can somebody help me by explaining the process involved in integrating Django with SimplDB for creating a small application... | Integrating Django with Amazon's Database 'SimpleDB' | Can somebody guide me to develop a django app with SimpleDB(Amazon's Database) as its database. I couldnt find any tutorials on searching. Can somebody help me by explaining the process involved in integrating Django with SimplDB for creating a small application. Or if somebody have any tutorials for it, please share i... | [
"There is now experimental support using django-norel with the django-simpledb backend.\n",
"It doesn't look like there's any way to use Django's ORM with SimpleDB at the moment, unless you want to write all the code yourself. I'd suggest interfacing with SimpleDB using normal Python code (which would get called ... | [
4,
2
] | [] | [] | [
"amazon",
"amazon_simpledb",
"amazon_web_services",
"django",
"python"
] | stackoverflow_0005065776_amazon_amazon_simpledb_amazon_web_services_django_python.txt |
Q:
python urllib2: connection reset by peer
I have a perl program that retrieves data from the database of my university library and it works well. Now I want to rewrite it in python but encounter the problem
<urlopen error [errno 104] connection reset by peer>
The perl code is:
my $ua = LWP::UserAgent->new;
... | python urllib2: connection reset by peer | I have a perl program that retrieves data from the database of my university library and it works well. Now I want to rewrite it in python but encounter the problem
<urlopen error [errno 104] connection reset by peer>
The perl code is:
my $ua = LWP::UserAgent->new;
$ua->cookie_jar( HTTP::Cookies->new() );
... | [
"I tried faking the User-Agent headers as Uku Loskit and Mikko Ohtamaa suggested, and solved my problem. The code is as follows:\n proxy = \"YOUR_PROXY_GOES_HERE\"\n proxies = {\"http\":\"http://%s\" % proxy}\n headers={'User-agent' : 'Mozilla/5.0'}\n proxy_support = urllib2.ProxyHandler(proxies)\n ... | [
9,
2,
1,
0
] | [] | [] | [
"python",
"urllib2"
] | stackoverflow_0006163732_python_urllib2.txt |
Q:
AJAX: Passing a string through CGI that contains '&' character
I am creating a website updater. I am passing strings over CGI using AJAX.
I have a problem where if my strings contain an '&' character they get incorrectly separated because CGI separates parameters/variables by a '&' character
So if I send this:
h... | AJAX: Passing a string through CGI that contains '&' character | I am creating a website updater. I am passing strings over CGI using AJAX.
I have a problem where if my strings contain an '&' character they get incorrectly separated because CGI separates parameters/variables by a '&' character
So if I send this:
http://mywebsite.com?user=blah&mystring=I_am_happy_&_sad
When I get ... | [
"You need to URL-encode the ampersand character:\nhttp://mywebsite.com?user=blah&mystring=I_am_happy_%26_sad\n\nTo do that, Javascript provides encodeURIComponent() and Python provides urllib.quote().\n"
] | [
4
] | [] | [] | [
"ajax",
"cgi",
"javascript",
"python"
] | stackoverflow_0006166040_ajax_cgi_javascript_python.txt |
Q:
Python Markdown module choking on unicode conversion, utf-8
I'm using the markdown module from web2py to handle marked up text. The problem is, people are submitting stuff with smartquotes, special characters etc, and I need to replace those with their equivalents.
I have text like this: '\n\r\nThe Colonels face p... | Python Markdown module choking on unicode conversion, utf-8 | I'm using the markdown module from web2py to handle marked up text. The problem is, people are submitting stuff with smartquotes, special characters etc, and I need to replace those with their equivalents.
I have text like this: '\n\r\nThe Colonels face paled a bit. \xe2\x80\x9cBut, then \xe2\x80" excuse my boldness, s... | [
"The \\xe2\\x80\\x9c is U+201C LEFT DOUBLE QUOTATION MARK (a \"smart quote\") when decoded as UTF-8. The two occurrences of \\xe2\\x80\" are not valid UTF-8 sequences and the presence there of a \" (a \"dumb\" quote) is suspicious. You appear to have a mangling problem or an encoding problem, or both. We need to so... | [
1
] | [] | [] | [
"markdown",
"python",
"unicode",
"utf_8"
] | stackoverflow_0006165893_markdown_python_unicode_utf_8.txt |
Q:
Single Vs. Multiple For Loops In Python?
When comparing the following code samples in python (the 300 is just an example; in practicality, assume there are 10,000,000 items that we need to loop through):
sum = 0
for i in xrange(0, 300):
sum += i
Vs.
sum = 0
for i in xrange(0, 100):
sum += i
for i in xrang... | Single Vs. Multiple For Loops In Python? | When comparing the following code samples in python (the 300 is just an example; in practicality, assume there are 10,000,000 items that we need to loop through):
sum = 0
for i in xrange(0, 300):
sum += i
Vs.
sum = 0
for i in xrange(0, 100):
sum += i
for i in xrange(100, 200):
sum += i
for i in xrange(200,... | [
"What kind of improvement were you hoping to see?\ntimeit will help you observe the difference:\n$ python -m timeit 'sum = 0\n> for i in xrange(0, 300):\n> sum += i'\n10000 loops, best of 3: 21.8 usec per loop\n\n$ python -m timeit 'sum = 0\n> for i in xrange(0, 100):\n> sum += i\n> for i in xrange(100, 200... | [
4,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0006166057_python.txt |
Q:
widget.setLayout(layout) vs layout = QLayout(widget)
Are
widget = QWidget()
layout = QVBoxLayout(widget)
and
widget = QWidget()
layout = QVBoxLayout()
widget.setLayout(layout)
the same things?
They look like the same. But may be I am missing something?
A:
Yea, they are doing the same thing: layout will become... | widget.setLayout(layout) vs layout = QLayout(widget) | Are
widget = QWidget()
layout = QVBoxLayout(widget)
and
widget = QWidget()
layout = QVBoxLayout()
widget.setLayout(layout)
the same things?
They look like the same. But may be I am missing something?
| [
"Yea, they are doing the same thing: layout will become the layout manager of widget in case there is no existing layout manager for widget.\n"
] | [
1
] | [] | [] | [
"pyqt",
"python",
"qt"
] | stackoverflow_0006165819_pyqt_python_qt.txt |
Q:
Trying to deploy files to planet-lab and failing at codeploy stage (permission denied?)
We've been trying to use planet-lab.
We have nodes on our slice, and we follow the instructions on http://www.cs.princeton.edu/~jbagdis/planetlab/hello_world.pdf
When we get to "./codeploy ...", we get the following:
<<generati... | Trying to deploy files to planet-lab and failing at codeploy stage (permission denied?) | We've been trying to use planet-lab.
We have nodes on our slice, and we follow the instructions on http://www.cs.princeton.edu/~jbagdis/planetlab/hello_world.pdf
When we get to "./codeploy ...", we get the following:
<<generating a script...>>
<<copying the script...>>
<<executing the script...>>
command is /usr/local... | [
"I think you solved it, but here is my idea; after uploading public key, you have to wait about 1 hours to get start to work on PlanetLab. Also some nodes may be down for some time.\nBy the way I suggest you to use PlMan to deploy and start your application.\nhttp://www.cs.washington.edu/research/networking/cplane/... | [
0
] | [] | [] | [
"deployment",
"networking",
"python"
] | stackoverflow_0005251577_deployment_networking_python.txt |
Q:
Is Scala a Functional Programming Language?
I've learned programming from Java, then tried to learn one programming language per year, second was C++, then Python. It came to learn next one, I looked for something new, I choose Scala because it was compatible with Java and could be some transition from OOP to Func... | Is Scala a Functional Programming Language? | I've learned programming from Java, then tried to learn one programming language per year, second was C++, then Python. It came to learn next one, I looked for something new, I choose Scala because it was compatible with Java and could be some transition from OOP to Functional Programming.
It was cool, learning new pa... | [
"Scala does not force you to write in a functional style. This is perfectly valid Scala:\nvar i = 1\nwhile (i < 10) {\n println(\"I like side effects, this is number \"+i)\n i += 1\n}\ncase class C(var i: Int, var set: Boolean = false)\ndef setMe(c: C) = { if (!c.set) { c.set = true; c.i += 1 }; c }\nsetMe(C(5))... | [
39,
21,
19
] | [] | [] | [
"functional_programming",
"haskell",
"java",
"python",
"scala"
] | stackoverflow_0006166155_functional_programming_haskell_java_python_scala.txt |
Q:
How do I uninstall python from OSX Leopard so that I can use the MacPorts version?
I want to use the macports version of python instead of the one that comes with Leopard.
A:
Don't. Apple ships various system utilities that rely on the system Python (and particularly the Python "framework" build); removing it wi... | How do I uninstall python from OSX Leopard so that I can use the MacPorts version? | I want to use the macports version of python instead of the one that comes with Leopard.
| [
"Don't. Apple ships various system utilities that rely on the system Python (and particularly the Python \"framework\" build); removing it will cause you problems.\nInstead, modify your PATH environ variable in your ~/.bash_profile to put /opt/local/bin first.\n",
"I have both installed:\n$ which python\n/usr/bin... | [
29,
22,
20,
17,
4,
3,
3
] | [] | [] | [
"macos",
"macports",
"osx_leopard",
"python"
] | stackoverflow_0000118813_macos_macports_osx_leopard_python.txt |
Q:
why I get [1, 2, 3],[1, 2, 3] instead of [1, 2, 3],[11, 2, 3]
sublista = [1, 2, 3]
lista = [sublista]
nsublista = sublista
nsublista[0] = sublista[0]+10
lista.append(nsublista)
print lista
Why do I get [1, 2, 3],[1, 2, 3] instead of [1, 2, 3],[11, 2, 3]?
A:
Python doesn't copy implicitly. When you do nsublista... | why I get [1, 2, 3],[1, 2, 3] instead of [1, 2, 3],[11, 2, 3] | sublista = [1, 2, 3]
lista = [sublista]
nsublista = sublista
nsublista[0] = sublista[0]+10
lista.append(nsublista)
print lista
Why do I get [1, 2, 3],[1, 2, 3] instead of [1, 2, 3],[11, 2, 3]?
| [
"Python doesn't copy implicitly. When you do nsublista = sublista, nsublista and sublista are the same list object. Changing an element in nsublista is reflected in sublista, because there's only one list.\nlista contains the same list twice, so that's what prints.\na = [1, 2, 3] # a = [1, 2, 3]\ncontai... | [
8
] | [] | [] | [
"list",
"python"
] | stackoverflow_0006166450_list_python.txt |
Q:
shrink parents widgets after child size changed
How can I make all widgets shrink, if one of their children changed height?
They expand if new height is bigger, but don't shrink if smaller.
I tried updateGeometry(), but it changed nothing.
Here is example, after child element shran, parents' height don't change:
... | shrink parents widgets after child size changed | How can I make all widgets shrink, if one of their children changed height?
They expand if new height is bigger, but don't shrink if smaller.
I tried updateGeometry(), but it changed nothing.
Here is example, after child element shran, parents' height don't change:
import sys
from PyQt4.QtGui import *
class MainWin... | [
"You should call the adjustSize() method on your \"toplevel\" widget (your MainWindow in this case).\nYou'll need to propagate that call up the widget hierarchy yourself for more complex layouts than your sample. In C++, you could do something like this:\nQWidget *w = <the widget you resized>->parentWidget();\nwhil... | [
7
] | [] | [] | [
"pyqt",
"python",
"qt"
] | stackoverflow_0006166484_pyqt_python_qt.txt |
Q:
Python spynner and native_click
I start to use https://github.com/kiorky/spynner/
First sample with google
import spynner
import pyquery
browser = spynner.Browser(debug_level=spynner.INFO)
browser.create_webview()
browser.show()
browser.load("http://www.google.com")
browser.fill("input[name=q]", "archlinux")
brow... | Python spynner and native_click | I start to use https://github.com/kiorky/spynner/
First sample with google
import spynner
import pyquery
browser = spynner.Browser(debug_level=spynner.INFO)
browser.create_webview()
browser.show()
browser.load("http://www.google.com")
browser.fill("input[name=q]", "archlinux")
browser.click("input[name=btnG]",True)
br... | [
"I had the same problem. Tried sorting out all the paths, pythonpaths and other things but gave up. Installed python 2.7 from source under my home directory, installed virtualenv and setup a new virtual environment with that python. Cloned the latest version of spynner from git and ran 'setup.py install' from withi... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0006156351_python.txt |
Q:
Does reportlab's renderPM work on Google appengine?
I wanted to use ReportLab's RenderPM to generate images on Google App-Engine but it looks like it depends on c libraries. Does anyone know if it's possible to get it working?
Thanks,
Richard
A:
Just to close the question - as indicated by Wooble, reportlab it... | Does reportlab's renderPM work on Google appengine? | I wanted to use ReportLab's RenderPM to generate images on Google App-Engine but it looks like it depends on c libraries. Does anyone know if it's possible to get it working?
Thanks,
Richard
| [
"Just to close the question - as indicated by Wooble, reportlab itself works fine on Appengine (being pure python) but the RenderPM library doesn't. \n"
] | [
0
] | [] | [] | [
"google_app_engine",
"image",
"python",
"reportlab"
] | stackoverflow_0006099592_google_app_engine_image_python_reportlab.txt |
Q:
'ModelOptions' object has no attribute 'local_many_to_many'
I'm trying to migrate a Django project into GAE ( Google App Engine )
The problem is I found this error when trying to login:
'ModelOptions' object has no attribute 'local_many_to_many'
Line provocking the error:
user = authenticate(username=uName,passw... | 'ModelOptions' object has no attribute 'local_many_to_many' | I'm trying to migrate a Django project into GAE ( Google App Engine )
The problem is I found this error when trying to login:
'ModelOptions' object has no attribute 'local_many_to_many'
Line provocking the error:
user = authenticate(username=uName,password=uPass)
Partial Code:
if request.method == 'POST':
i... | [
"Are you using the stock auth app provided with django-nonrel? It won't work because it requires JOINs. Install django-permission-backend-nonrel and things will work fine.\n"
] | [
0
] | [] | [] | [
"authentication",
"django",
"django_nonrel",
"google_app_engine",
"python"
] | stackoverflow_0005857516_authentication_django_django_nonrel_google_app_engine_python.txt |
Q:
Where to look for parameter that was just returned by signal?
QTabWidget has signal currentChanged(). And it returns index of current tab.
But how can I get this parameter in such expression:
tabs.currentChanged.connect(lambda: foo());
def foo(index):
...
Where should I look for this parameter that was just... | Where to look for parameter that was just returned by signal? | QTabWidget has signal currentChanged(). And it returns index of current tab.
But how can I get this parameter in such expression:
tabs.currentChanged.connect(lambda: foo());
def foo(index):
...
Where should I look for this parameter that was just returned?
| [
"Signals don't \"return\" anything. They can have parameters though, which is the case for currentIndex. If you want that argument passed to your function, you should try:\ntabs.currentChanged.connect(lambda index: foo(index));\n\n"
] | [
3
] | [] | [] | [
"pyqt",
"python",
"qt"
] | stackoverflow_0006166939_pyqt_python_qt.txt |
Q:
Pass current product_id to a Model in Django
I'm trying to give django a try by developing a simple page where people can ask something about a product
This is my model, i can create products in the admin area, display the product page, and the form shows up with the fields email, and text.
class Product(models.Mo... | Pass current product_id to a Model in Django | I'm trying to give django a try by developing a simple page where people can ask something about a product
This is my model, i can create products in the admin area, display the product page, and the form shows up with the fields email, and text.
class Product(models.Model):
category = models.ForeignKey(Category)
... | [
"You can either:\nSend product_id as form value\nMake product foreign key in your form a hidden field and set it's value to primary key value of the product in detail view. This way you don't need a product_id in your question view URL and arguments since the ID will be passed with POST data. (see link for examples... | [
3
] | [] | [] | [
"django",
"python"
] | stackoverflow_0006164728_django_python.txt |
Q:
Using regular expressions to modify a string
How can I use regular expressions to change this string
':: 1:62 2:31 :: 3:4 4:32'
to:
':: 1:62.0 2:31.0 :: 3:4.0 4:32.0'
Is there any clean way to do it without using re.split?
A:
>>> re.sub("([0-9]+:[0-9]+)", "\\1.0", ':: 1:62 2:31 :: 3:4 4:32')
':: 1:62.0 2:31.0 ... | Using regular expressions to modify a string | How can I use regular expressions to change this string
':: 1:62 2:31 :: 3:4 4:32'
to:
':: 1:62.0 2:31.0 :: 3:4.0 4:32.0'
Is there any clean way to do it without using re.split?
| [
">>> re.sub(\"([0-9]+:[0-9]+)\", \"\\\\1.0\", ':: 1:62 2:31 :: 3:4 4:32')\n':: 1:62.0 2:31.0 :: 3:4.0 4:32.0'\n\nIs that adequate?\n",
">>> re.sub(r'(\\d)( |$)', r'\\1.0\\2', ':: 1:62 2:31 :: 3:4 4:32')\n':: 1:62.0 2:31.0 :: 3:4.0 4:32.0'\n\n"
] | [
4,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0006167072_python_regex.txt |
Q:
Stripping irrelevant parts of a web page
Is there a API or systematic way of stripping irrelevant parts of a web page while scraping it via Python? For instance, take this very page -- the only important part is the question and the answers, not the side bar column, header, etc. One can guess things like that, but... | Stripping irrelevant parts of a web page | Is there a API or systematic way of stripping irrelevant parts of a web page while scraping it via Python? For instance, take this very page -- the only important part is the question and the answers, not the side bar column, header, etc. One can guess things like that, but is there any smart way of doing it?
| [
"In general, no. In specific cases, if you know something about the structure of the site you are scraping, you can use a tool like Beautiful Soup to manipulate the DOM.\n",
"There's the approach from the Readability bookmarklet, with at least two Python implementations available:\n\ndecruft\npython-readability\... | [
3,
3,
1,
0
] | [] | [] | [
"python",
"screen_scraping",
"web_scraping"
] | stackoverflow_0006051175_python_screen_scraping_web_scraping.txt |
Q:
Python django sqlalchemy and formencode
I create a table in database using sqlalchemy and now want to make a form according to the database using django and valid it use formencode. (mention I use Django Web Framework)
The python code is below
from sqlalchemy import *
from sqlalchemy.orm import *
engine = create... | Python django sqlalchemy and formencode | I create a table in database using sqlalchemy and now want to make a form according to the database using django and valid it use formencode. (mention I use Django Web Framework)
The python code is below
from sqlalchemy import *
from sqlalchemy.orm import *
engine = create_engine('mysql+mysqldb://root:@localhost/test... | [
"At last I crete my own solutions can any one prefer me better than this\n**and if any one want they can use it its really save data onto database (not comment this line from settings.py->middleware_classes ->> #'django.middleware.csrf.CsrfViewMiddleware', for using post method )**\nfrom django.shortcuts import ren... | [
2
] | [] | [] | [
"django",
"formencode",
"python",
"sqlalchemy"
] | stackoverflow_0006133393_django_formencode_python_sqlalchemy.txt |
Q:
Create a vim script for django code completion, but fail, why?
I tried two ways to do code completion, one is OK, the other fails.
OK one does like below:
$> cd myDjangoProject/
myDjangoProject $> export PYTHONPATH="."
myDjangoProject $> DJANGO_SETTINGS_MODULE=settings vim urls.py
Then ^x ^o can work well. But th... | Create a vim script for django code completion, but fail, why? | I tried two ways to do code completion, one is OK, the other fails.
OK one does like below:
$> cd myDjangoProject/
myDjangoProject $> export PYTHONPATH="."
myDjangoProject $> DJANGO_SETTINGS_MODULE=settings vim urls.py
Then ^x ^o can work well. But this method leads me repeatly do above when edit a file in project.
So... | [
"Try just settings DJANGO_SETTINGS_MODULE=settings as you did when it worked. My hope is that your setting of PYTHONPATH will be sufficient.\n",
"Create the vim_django executable script in /usr/bin\nContent in vim_django script:\n#!/bin/bash\nPROJECT=`python -c \"import os; print os.getcwd().partition('Solutions... | [
0,
0
] | [] | [] | [
"bash",
"django",
"python",
"shell"
] | stackoverflow_0006133187_bash_django_python_shell.txt |
Q:
Python ORM SQLAlchemy and Django usage
I am developing a Flex based dashboard and I am considering SQLAlchemy or Django to interact with the database.
I am new to both these frameworks. I know that Django can create the database with syncdb command and SQLAlchemy can do the same with *metadata.create_all(engine)* ... | Python ORM SQLAlchemy and Django usage | I am developing a Flex based dashboard and I am considering SQLAlchemy or Django to interact with the database.
I am new to both these frameworks. I know that Django can create the database with syncdb command and SQLAlchemy can do the same with *metadata.create_all(engine)* statement. How do I use these frameworks wit... | [
"For Django take a look at Integrating Django with a legacy database. I have no experience with SQLAlchemy, though I would assume they have something similar.\n",
"define a class for mapper function\ne.g\nengine = create_engine(\"mysql+mysqldb://root:@localhost/testdb\",echo = True)\n#testbd is ur database#use pa... | [
0,
0
] | [] | [] | [
"django",
"python",
"sqlalchemy"
] | stackoverflow_0005873883_django_python_sqlalchemy.txt |
Q:
Exception when trying to use an user-defined function in sqlite3 using python
I'm using Python 2.6.4 and its module sqlite3 for a small database project and I have the following problem: I'm trying to use a user-defined function, I mean, a function that you define in Python to use after inside your queries. The fu... | Exception when trying to use an user-defined function in sqlite3 using python | I'm using Python 2.6.4 and its module sqlite3 for a small database project and I have the following problem: I'm trying to use a user-defined function, I mean, a function that you define in Python to use after inside your queries. The function is a wrapper for other function I have in another module. The problem is tha... | [
"cur = con.cursor # sets `cur` to a method\n\nshould be\ncur = con.cursor() # calls the method and sets `cur` to the return value\n\nThis is why you were getting the error saying cur has no execute attribute:\n\nAttributeError exception with the\n message: 'builtin_function_or_method'\n object has no attribut... | [
2
] | [] | [] | [
"python",
"sqlite"
] | stackoverflow_0006167596_python_sqlite.txt |
Q:
Generate a click event in tkinter
I am tring to unittest my tkitner GUI.
Therefore I tried to generate click events from a separate thread.
Here is an example testing the Tkinter.Button:
import unittest, threading
from Tkinter import *
class clickThread(threading.Thread):
def __init__(self, root):
t... | Generate a click event in tkinter | I am tring to unittest my tkitner GUI.
Therefore I tried to generate click events from a separate thread.
Here is an example testing the Tkinter.Button:
import unittest, threading
from Tkinter import *
class clickThread(threading.Thread):
def __init__(self, root):
threading.Thread.__init__(self)
... | [
"If I recall correctly (and I may not since its been years since I tried this) the cursor needs to be over tne button for the binding to fire.\nAre you aware of the \"invoke\" method of buttons? You can use it to simulate the pressing of the buttun.\n"
] | [
5
] | [] | [] | [
"python",
"tkinter",
"unit_testing"
] | stackoverflow_0006167019_python_tkinter_unit_testing.txt |
Q:
Python Bencoding using BitTorrent-bencode 5.0.8.1
I'm new to python and bencoding. I need to read and write torrent files for my project using python. I have already imported the module and here's my code to parse the torrent:
Here's the link to my module http://paste2.org/p/1442120 which is a mod of http://pypi.p... | Python Bencoding using BitTorrent-bencode 5.0.8.1 | I'm new to python and bencoding. I need to read and write torrent files for my project using python. I have already imported the module and here's my code to parse the torrent:
Here's the link to my module http://paste2.org/p/1442120 which is a mod of http://pypi.python.org/pypi/BitTorrent-bencode/5.0.8.1
i... | [
"The problem is that Bencoded files are not line oriented files. What you're doing is like taking a report, putting it through the shredder, and handing it to your boss one shred at a time. Here is the correct way to decode a Bencoded file:\nimport bencode\nprint bencode.bdecode(open('file.torrent', 'rb').read())... | [
10
] | [] | [] | [
"python"
] | stackoverflow_0006167823_python.txt |
Q:
Determining modifying statements from non-modifying in SQLite
What is the most reliable way to determine what statements are "querying" versus "modifying"? For example, SELECT versus UPDATE / INSERT / CREATE.
Parsing the statement myself seems the obvious first attempt, but I can't help but think that this woul... | Determining modifying statements from non-modifying in SQLite | What is the most reliable way to determine what statements are "querying" versus "modifying"? For example, SELECT versus UPDATE / INSERT / CREATE.
Parsing the statement myself seems the obvious first attempt, but I can't help but think that this would be a flaky solution. Just looking for SELECT at the beginning do... | [
"Use the sqlite3_changes API call, which is also available from SQL using the changes function. \nAs TokenMacGuy mentioned, you can rollback the transaction containing the statement that caused the changes; the sqlite3_changes function will let you know if that is necessary.\nThere is also the update_hook callback ... | [
1
] | [] | [] | [
"python",
"sqlite"
] | stackoverflow_0006168662_python_sqlite.txt |
Q:
Python library for html to jpg converting
Is subject exists? The hard way is to convert html to pdf, and then pdf to jpg, but it is unwanted for web-based service.
A:
You can use the webkit2png python library to achieve this.
https://github.com/AdamN/python-webkit2png/
| Python library for html to jpg converting | Is subject exists? The hard way is to convert html to pdf, and then pdf to jpg, but it is unwanted for web-based service.
| [
"You can use the webkit2png python library to achieve this. \nhttps://github.com/AdamN/python-webkit2png/\n"
] | [
5
] | [] | [] | [
"python"
] | stackoverflow_0006168777_python.txt |
Q:
Trypsin digest (cleavage) does not work using regular expression
I have trying to code the theoretical tryptic cleavage of protein sequences in Python. The cleavage rule for trypsin is: after R or K, but not before P. (i.e. the trypsin cleaves (cuts) the protein sequence after each K or R, unless (K or R) is follo... | Trypsin digest (cleavage) does not work using regular expression | I have trying to code the theoretical tryptic cleavage of protein sequences in Python. The cleavage rule for trypsin is: after R or K, but not before P. (i.e. the trypsin cleaves (cuts) the protein sequence after each K or R, unless (K or R) is followed by a P).
Example: Cleavage (cut) of the sequence MVPPPPSRGGAAKPGQL... | [
"regexes are nice, but here's a solution that uses regular python. Since you're\nlooking for subsequences in the bases, it makes sense to build this as a generator,\nwhich yields the fragments.\nexample = 'MVPPPPSRGGAAKPGQLGRSLGPLLLLLRPEEPEDGDREICSESK'\n\ndef trypsin(bases):\n sub = ''\n while bases:\n ... | [
5,
3,
1
] | [] | [] | [
"python"
] | stackoverflow_0006168727_python.txt |
Q:
How do you properly setup pyssh (PYTHON)
I'm trying to test out pyssh, but I'm having trouble importing it.
I'm new to python so I'm not sure how to get this thing to import properly.
What do I have to do before I can import pyssh 0.3 into my code?
A:
In order for Python to import a module, it has to be either i... | How do you properly setup pyssh (PYTHON) | I'm trying to test out pyssh, but I'm having trouble importing it.
I'm new to python so I'm not sure how to get this thing to import properly.
What do I have to do before I can import pyssh 0.3 into my code?
| [
"In order for Python to import a module, it has to be either in the PYTHONPATH, or in the current directory. You can check this by looking at sys.path.\nCheck the documentation on modules.\n"
] | [
2
] | [] | [] | [
"python"
] | stackoverflow_0006168991_python.txt |
Q:
PyQt4 Windows - Toolbar Actions don't work. How can I fix them?
I have made a program that has a Toolbar with a few actions on it in Linux. The Toolbar and its actions work perfectly on a Linux OS, but when I run the code on a Windows machine, the actions just don't work. Everything looks the same as on Linux(yes ... | PyQt4 Windows - Toolbar Actions don't work. How can I fix them? | I have made a program that has a Toolbar with a few actions on it in Linux. The Toolbar and its actions work perfectly on a Linux OS, but when I run the code on a Windows machine, the actions just don't work. Everything looks the same as on Linux(yes I have PyQt4 installed on the Windows machine), even the toolbar, but... | [
"It's odd that it works in Linux, because I can only get it work on Windows by changing \nw.connect(action, QtCore.SIGNAL(\"activated()\"), aTest)\n\nto\nw.connect(action, QtCore.SIGNAL(\"triggered()\"), aTest)\n\nThe QAction class reference only lists changed(), hovered(), toggled() and triggered() as valid signal... | [
3
] | [] | [] | [
"action",
"pyqt4",
"python",
"toolbar",
"windows"
] | stackoverflow_0006168722_action_pyqt4_python_toolbar_windows.txt |
Q:
Web interface to a Python script, with "streaming text"
I have a Python command-line script that can take some time to run (from 5 seconds to 5 minutes), depending on the checks it does. The script uses many command-line arguments, some mandatory, most optional.
I'd like to "webify" this script, making it possible... | Web interface to a Python script, with "streaming text" | I have a Python command-line script that can take some time to run (from 5 seconds to 5 minutes), depending on the checks it does. The script uses many command-line arguments, some mandatory, most optional.
I'd like to "webify" this script, making it possible to access it from a Web browser, but without changing the co... | [
"You can log the output from your lengthy script to a file and use a javascript timer based code to pull, parse and display content of the log periodically. If pulling the entire log is too much, you can also delegate to a smaller/faster server side python script to parse the log and pass on the tail of the log to ... | [
1,
0
] | [] | [] | [
"python",
"web_applications"
] | stackoverflow_0003966567_python_web_applications.txt |
Q:
Python Random Slice Idiom
Is there a pythonic way to slice a sequence type such that the returned slice is of random length and in random order? For example, something like:
>>> l=["a","b","c","d","e"]
>>> rs=l[*:*]
>>> rs
['e','c']
A:
How about...
random.sample(l, random.randint(1, len(l)))
Quick link to d... | Python Random Slice Idiom | Is there a pythonic way to slice a sequence type such that the returned slice is of random length and in random order? For example, something like:
>>> l=["a","b","c","d","e"]
>>> rs=l[*:*]
>>> rs
['e','c']
| [
"How about... \nrandom.sample(l, random.randint(1, len(l)))\n\nQuick link to docs for the random module can be found here.\n",
"No idiom that I'm aware of, but random.sample does what you need.\n>>> from random import sample, randint\n>>> \n>>> def random_sample(seq):\n... return sample(seq, randint(0, len(... | [
13,
4,
4
] | [] | [] | [
"python",
"random",
"slice"
] | stackoverflow_0006168787_python_random_slice.txt |
Q:
Getting two strings in variable from URL in Django
I'm having some trouble sending along more than one variable to the view.
my urls.py is as follows:
urlpatterns = patterns('',
url(r'^rss/(?P<anything>[^/]+)/$', 'rss.rssama.views.makerss', name='anything'),
url(r'^$', 'rss.rssama.views.home'),
)
view... | Getting two strings in variable from URL in Django | I'm having some trouble sending along more than one variable to the view.
my urls.py is as follows:
urlpatterns = patterns('',
url(r'^rss/(?P<anything>[^/]+)/$', 'rss.rssama.views.makerss', name='anything'),
url(r'^$', 'rss.rssama.views.home'),
)
views.py
def maakrss(request, anything):
So now it takes f... | [
"To begin with, the regex part should look like this:\nr'^/rss/(?P<anynumber>\\d+)/(?P<anystring>.+)/$'\n\nThose strings inside the <...> parts allow you to give a name to whatever the regex matches. Django will then use that name to pass the value to your function. Therefore your function must have an argument w... | [
28,
1,
0
] | [] | [] | [
"django",
"python",
"url"
] | stackoverflow_0006164540_django_python_url.txt |
Q:
Python setup.py install uses wrong Python installation path
I'm on a bluehost-server which has a "rudimental" installation of python2.6.
I installed python2.6 in my user-directory which works fine so far, but when I try to install python packages with "setup.py install", "easy_install" or "pip install" I get:
erro... | Python setup.py install uses wrong Python installation path | I'm on a bluehost-server which has a "rudimental" installation of python2.6.
I installed python2.6 in my user-directory which works fine so far, but when I try to install python packages with "setup.py install", "easy_install" or "pip install" I get:
error: invalid Python installation: unable to open /usr/lib/python2.6... | [
"You need to execute setup.py by specifying which python interpreter on the command line, like this:\n/path/to/python setup.py install\n\nUPDATE:\nThe error message indicates that you don't have the python-dev package \ninstalled on your system.\n",
"I just solved the problem by installing the needed packages man... | [
5,
0
] | [] | [] | [
"python",
"pythonpath"
] | stackoverflow_0006168035_python_pythonpath.txt |
Q:
Parental Control Software
I have been developing a parental control software program for my company, but have run into a problem. The software uses policy listings stored in a MySQL DB to determine whether to block a website or not. It uses a local proxy. Each time a website is visited, the proxy sends that site t... | Parental Control Software | I have been developing a parental control software program for my company, but have run into a problem. The software uses policy listings stored in a MySQL DB to determine whether to block a website or not. It uses a local proxy. Each time a website is visited, the proxy sends that site to the server, then the server d... | [
"Are you caching the server's responses locally on the client? If not, you should - it ought to speed things up considerably.\nAnd if you're asking your server about each URL, you should only ask about the domain name, so that the number of requests per site goes down from lots to only one. (Unless there are doma... | [
1
] | [] | [] | [
"php",
"proxy",
"python"
] | stackoverflow_0006169479_php_proxy_python.txt |
Q:
Syntax error in fresh copy of pyssh 0.3? (PYTHON)
I am trying to test out pyssh, however I am getting a syntax error whenever I try to import it.
Python 3.2 (r32:88445, Feb 20 2011, 21:29:02) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> =================... | Syntax error in fresh copy of pyssh 0.3? (PYTHON) | I am trying to test out pyssh, however I am getting a syntax error whenever I try to import it.
Python 3.2 (r32:88445, Feb 20 2011, 21:29:02) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> ================================ RESTART ===============================... | [
"As far as I know pyssh does not support python 3.X, this is obvious from the error message you are getting. In python 3.X the print statement is a function.\n"
] | [
2
] | [] | [] | [
"python"
] | stackoverflow_0006169709_python.txt |
Q:
Django admin auto-save
I was asking myself how it would be possible to auto-save one of my models field I'm currently updating in the django admin every x seconds. For example, if I'm writing a blog post, I'd like it to be auto-saved every x seconds. That way, if I ever stupidly close the tab, I wouldn't lose all ... | Django admin auto-save | I was asking myself how it would be possible to auto-save one of my models field I'm currently updating in the django admin every x seconds. For example, if I'm writing a blog post, I'd like it to be auto-saved every x seconds. That way, if I ever stupidly close the tab, I wouldn't lose all my work.
Any ideas on how to... | [
"As HTTP is stateless, you have to use JavaScript for this task and submit the actual changes, nowadays it is called Ajax ;-)\nMaybe you like Dajax\n"
] | [
2
] | [] | [] | [
"django",
"django_admin",
"python"
] | stackoverflow_0006170032_django_django_admin_python.txt |
Q:
Django {% if forloop.first %} question
I have the following code in my template:
{% for object in object_list %}
{% with game=object.game %}
{% for category in object.game.objectmeta.categories.all %}
{% if category.name|title == 'Puzzle' %}
{% if forloop.first %}
<div class='side_header' id='dark_gamelink_s... | Django {% if forloop.first %} question | I have the following code in my template:
{% for object in object_list %}
{% with game=object.game %}
{% for category in object.game.objectmeta.categories.all %}
{% if category.name|title == 'Puzzle' %}
{% if forloop.first %}
<div class='side_header' id='dark_gamelink_side'>
<a class='actionheader' href="... | [
"Edited:\nI have never used these variables but I think forloop.parentloop.first should do it. If not blame me to have misunderstand the Django docs. ;-)\nYou should check if you are within the parentloop and and then within the first nested node. Please try this modified template. It should you give the right dire... | [
27,
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0006170259_django_python.txt |
Q:
ExtJS 4.0, Django and ExtDirect
Do you know if I can use this Django Ext.Direct router with ExtJS 4.0? Do you have any examples where I can find how to do it? I'm new to JavaScript programming.
Will it be easy to integrate server side form validation with ExtJS? What about file upload?
Can I use ExtJS library dra... | ExtJS 4.0, Django and ExtDirect | Do you know if I can use this Django Ext.Direct router with ExtJS 4.0? Do you have any examples where I can find how to do it? I'm new to JavaScript programming.
Will it be easy to integrate server side form validation with ExtJS? What about file upload?
Can I use ExtJS library drawing (or charts) to draw a hall where... | [
"\nDo you know if I can use this Django\n Ext.Direct router with ExtJS 4.0?\n\nWe recently switched from Ext3 to Ext4 (with Django as backend). \nOur experience involved a lot of trouble with changes in the ExtJS 4 API (especially in the area of datagrid stores). All reasonable and good changes but huge. Given the... | [
2
] | [] | [] | [
"django",
"ext_direct",
"extjs",
"javascript",
"python"
] | stackoverflow_0006162302_django_ext_direct_extjs_javascript_python.txt |
Q:
Access to errno from Python?
I am stuck with a fairly complex Python module that does not return useful error codes (it actually fails disturbingly silently). However, the underlying C library it calls sets errno.
Normally errno comes in over OSError attributes, but since I don't have an exception, I can't get at ... | Access to errno from Python? | I am stuck with a fairly complex Python module that does not return useful error codes (it actually fails disturbingly silently). However, the underlying C library it calls sets errno.
Normally errno comes in over OSError attributes, but since I don't have an exception, I can't get at it.
Using ctypes, libc.errno doesn... | [
"Here is a snippet of code that allows to access errno:\nfrom ctypes import *\n\nlibc = CDLL(\"libc.so.6\")\n\nget_errno_loc = libc.__errno_location\nget_errno_loc.restype = POINTER(c_int)\n\ndef errcheck(ret, func, args):\n if ret == -1:\n e = get_errno_loc()[0]\n raise OSError(e)\n return ret\... | [
19,
15,
9,
9,
1,
1
] | [] | [] | [
"errno",
"linux",
"python",
"python_2.5"
] | stackoverflow_0000661017_errno_linux_python_python_2.5.txt |
Q:
Is it possible to use numpy.argmax with a custom field of objects in a list?
Something like:
class Test:
def __init__(self, n):
self.id = n
def __str__(self):
return str(self.id)
my_list = []
my_list.append(Test(1))
my_list.append(Test(2))
my_list.append(Test(3))
Would it be possible to ... | Is it possible to use numpy.argmax with a custom field of objects in a list? | Something like:
class Test:
def __init__(self, n):
self.id = n
def __str__(self):
return str(self.id)
my_list = []
my_list.append(Test(1))
my_list.append(Test(2))
my_list.append(Test(3))
Would it be possible to get the element in the list with the maximum or minimum id?
| [
"You wouldn't even need to resort to numpy.argmax() in your example. Since your objects are in a standard Python list, you can also use Python's built-in max() function:\nindex = max(range(len(my_list)), key=lambda i: my_list[i].id)\n\nor\nindex = max(enumerate(my_list), key=lambda x: x[1].id)[0]\n\nwill also give... | [
3,
2
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0006170158_numpy_python.txt |
Q:
How do I run a python script using a specific interpreter?
I'm having problems with pygame as documented here:
PyGame bogging down linux?
After a bit of searching around and brainstorming I realized it may be because I'm using python2.7 instead of 2.6 which PyGame was designed for.
How do I run my script using th... | How do I run a python script using a specific interpreter? | I'm having problems with pygame as documented here:
PyGame bogging down linux?
After a bit of searching around and brainstorming I realized it may be because I'm using python2.7 instead of 2.6 which PyGame was designed for.
How do I run my script using the 2.6 interpreter instead of 2.7 (which seems to be the default)... | [
"Python installs different binaries (and links to binaries):\n\npython links to the system's standard Python (2) version\npython3 links to the system's standard Python 3 version\npython2 links to the system's standard Python 2 version\npython2.7 is the Python 2.7 interpreter\npython2.6 is the Python 2.6 interpreter... | [
2,
0
] | [] | [] | [
"pygame",
"python",
"ubuntu"
] | stackoverflow_0006170681_pygame_python_ubuntu.txt |
Q:
Using Python to measure audio "loudness"
I'm looking to calculate the loudness of a piece of audio using Python — probably by extracting the peak volume of a piece of audio, or possibly using a more accurate measure (RMS?).
What's the best way to do this? I've had a look at pyaudio, but that didn't seem to do what... | Using Python to measure audio "loudness" | I'm looking to calculate the loudness of a piece of audio using Python — probably by extracting the peak volume of a piece of audio, or possibly using a more accurate measure (RMS?).
What's the best way to do this? I've had a look at pyaudio, but that didn't seem to do what I wanted. What looked good was ruby-audio, as... | [
"I think that the RMS would be the the most accurate measure. One thing to note is that we percieve loudness differently at different frequencies, so convert the audio to frequency space with an fft (numpy.fft should work great on only 30s of audio). Now compute a power spectral density from this. Weight the PSD by... | [
4
] | [] | [] | [
"audio",
"audio_analysis",
"python"
] | stackoverflow_0006170548_audio_audio_analysis_python.txt |
Q:
Django: Model.objects.get fails with ImportError exception
I've model which represents settings in my system and I use it from another part of my application so that import has 3 levels WORKING CODE <- Module <- Model
Model Variables
from django.db import models
class Variables(models.Model):
key = models.Ch... | Django: Model.objects.get fails with ImportError exception | I've model which represents settings in my system and I use it from another part of my application so that import has 3 levels WORKING CODE <- Module <- Model
Model Variables
from django.db import models
class Variables(models.Model):
key = models.CharField(max_length = 20, verbose_name = 'Variable')
value ... | [
"Get rid of the models directory, and put all your models in a models.py file, unless you have a VERY good reason not to. Change your imports to from core.models import Variable (rename your Variables class to Variable - django models should be named as the singular not the plural).\nThe problem probably has to do ... | [
0
] | [] | [] | [
"django_models",
"exception",
"importerror",
"python"
] | stackoverflow_0006166654_django_models_exception_importerror_python.txt |
Q:
send push notifications to iphone from python
I am trying to create a python server that sends push notifications. I am using the pyAPNs module and when I try to connect to apple's server I get this error:
[Errno 336265225] _ssl.c:347: error:140B0009:SSL routines:SSL_CTX_use_PrivateKey_file:PEM lib.
Anyone know ... | send push notifications to iphone from python | I am trying to create a python server that sends push notifications. I am using the pyAPNs module and when I try to connect to apple's server I get this error:
[Errno 336265225] _ssl.c:347: error:140B0009:SSL routines:SSL_CTX_use_PrivateKey_file:PEM lib.
Anyone know what causes that? What format does the ssl cert hav... | [
"Documentation http://pypi.python.org/pypi/pyapns/0.3.0 says that certificate should be in PEM format. Remember that APNS authenticates client using Client Certificate, so private key is also required. Convert unencrypted private key to PEM format and concatenate with matching, PEM-encoded, certificate file. This w... | [
4
] | [] | [] | [
"apple_push_notifications",
"iphone",
"python"
] | stackoverflow_0006157303_apple_push_notifications_iphone_python.txt |
Q:
Working with data exceeded memory
I have a data structure which represents a list of objects and links between them. Each objects owns a dict with properties which can even be nested Python objects.
Occationally these objects exceed the available memory, due to sheer number or sometimes due to individual large pro... | Working with data exceeded memory | I have a data structure which represents a list of objects and links between them. Each objects owns a dict with properties which can even be nested Python objects.
Occationally these objects exceed the available memory, due to sheer number or sometimes due to individual large properties.
Is there an easy way to still ... | [
"There are 4 \"real\" solutions and 2 \"literally what you want\" solution:\n\nModify the schema, so you aren't keeping giant pieces of data you don't need; perhaps you are using a database and don't need to retrieve those pieces of data in the query.\nModify your goals: maybe you don't really need to process such ... | [
1,
0
] | [] | [] | [
"database",
"memory",
"python"
] | stackoverflow_0006171030_database_memory_python.txt |
Q:
Building Python and more on missing modules
I have another thread asking help on "missing zlib". With the nice help the problem has been resolved (almost).
Now I am interested in building Python myself (on Ubuntu 10.10).
A few important questions have caught my attention:
After building Python (say 2.7.1), do I n... | Building Python and more on missing modules | I have another thread asking help on "missing zlib". With the nice help the problem has been resolved (almost).
Now I am interested in building Python myself (on Ubuntu 10.10).
A few important questions have caught my attention:
After building Python (say 2.7.1), do I need to rebuild Python if I have missing modules?
... | [
"Here is how to build Python and fix any dependencies. I am assuming that you want this Python to be entirely separate from the Ubuntu release Python, so I am specifying the --prefix option to install it all in /home/python27 using the standard Python layout, i.e. site-packages instead of dist-packages. \n1. Get th... | [
48
] | [] | [] | [
"python",
"ubuntu"
] | stackoverflow_0006171210_python_ubuntu.txt |
Q:
How would I keep a constant piece of data updated through a socket in Python?
I have a client and a server, both written in Python 2.7.
Lets say I wanted to make a multiplayer game server (which I don't at the moment but I'm working towards it). I would need to keep the server up to date (and other clients) on my ... | How would I keep a constant piece of data updated through a socket in Python? | I have a client and a server, both written in Python 2.7.
Lets say I wanted to make a multiplayer game server (which I don't at the moment but I'm working towards it). I would need to keep the server up to date (and other clients) on my characters whereabouts, correct?
How would I do this with sockets? Send or request ... | [
"With TCP sockets it is more typical to leave the connections open, given the teardown & rebuild cost. \nEventually when scaling you will do look into NewIO\\RawIO.\nIf you do not, imagine that the game client might take a step & not get confirmation if sending it to the server & other players.\n",
"Definitely ke... | [
1,
0
] | [] | [] | [
"python",
"sockets"
] | stackoverflow_0006171112_python_sockets.txt |
Q:
Loop socket request every 5 seconds (Python)
How would i loop every 5 seconds the following code :
sendSocket = socket.socket (socket.AF_INET, socket.SOCK_STREAM)
sendSocket.connect ( ( 'CENSORED', 1234 ) )
sendSocket.send ( 'request posit' )
data = sendSocket.recv( 100 )
chatLog.insert(END, data)
I want a client... | Loop socket request every 5 seconds (Python) | How would i loop every 5 seconds the following code :
sendSocket = socket.socket (socket.AF_INET, socket.SOCK_STREAM)
sendSocket.connect ( ( 'CENSORED', 1234 ) )
sendSocket.send ( 'request posit' )
data = sendSocket.recv( 100 )
chatLog.insert(END, data)
I want a client to recieve data every 5 seconds from a server, i ... | [
"See this question:\nHow to make tkinter repond events while waiting socket data?\nYou can also use after_idle\ndef read_the_socket():\n sendSocket.send ( 'request posit' )\n data = sendSocket.recv( 100 )\n gui.after(5000, read_the_socket)\n\n\ngui.after_idle(read_the_socket)\n\nafter_idle schedules a func... | [
2,
1
] | [] | [] | [
"loops",
"python",
"sockets"
] | stackoverflow_0006171578_loops_python_sockets.txt |
Q:
Debugging test code
I wrote this just to test the "Property" function. However, I am getting a bug in the get_name function. I'd appreciate any help.
#The Property Critter
#Using New Classes vs Old Classes:
class Critter (object):
def __init__ (self, name):
print "A new critter has been born."
... | Debugging test code | I wrote this just to test the "Property" function. However, I am getting a bug in the get_name function. I'd appreciate any help.
#The Property Critter
#Using New Classes vs Old Classes:
class Critter (object):
def __init__ (self, name):
print "A new critter has been born."
self.__name = name
... | [
"You need to indent your name = property (get_name, set_name) so that it is part of your Critter class:\nclass Critter (object):\n def __init__ (self, name):\n print \"A new critter has been born.\"\n self.__name = name\n\n def get_name (self):\n return self.__name\n\n def set_name (se... | [
3
] | [] | [] | [
"debugging",
"python"
] | stackoverflow_0006171737_debugging_python.txt |
Q:
Multithreading in ArcGIS with Python
I have a python script that works great when run by itself. Based on a hardcoded input directory it scans for all .mdb files and puts that into a list, then iterates through them all in a for loop. Each iteration involves multiple table restrictions, joins, queries, and more.... | Multithreading in ArcGIS with Python | I have a python script that works great when run by itself. Based on a hardcoded input directory it scans for all .mdb files and puts that into a list, then iterates through them all in a for loop. Each iteration involves multiple table restrictions, joins, queries, and more.
The only problem.. it takes about 36 hour... | [
"Thought I'd share what ended up working for me and my experiences.\nUsing the backport of the multiprocessing module (code.google.com/p/python-multiprocessing) as per Joe's comment worked well. I had to change a couple things around in my script to deal with local/global variables and logging.\nMain script is now... | [
5
] | [
"I compared the above methods in the same function.\nthe result: \nStarting pp with 1 workers\nTime elapsed: 4.625 s\n\nStarting pp with 2 workers\nTime elapsed: 2.43700003624 s\n\nStarting pp with 4 workers\nTime elapsed: 2.42100000381 s\n\nStarting pp with 8 workers\nTime elapsed: 2.375 s\n\nStarting pp with ... | [
-1
] | [
"arcgis",
"multithreading",
"python"
] | stackoverflow_0004893809_arcgis_multithreading_python.txt |
Q:
Python sockets connection timeout problem
I'm trying to write a simple script that connects to the freenode IRC network (irc.freenode.net on port 6667) to periodically post information on a channel. To do this, I am employing Python sockets. This has worked fine in the past, however now I am experiencing a strange... | Python sockets connection timeout problem | I'm trying to write a simple script that connects to the freenode IRC network (irc.freenode.net on port 6667) to periodically post information on a channel. To do this, I am employing Python sockets. This has worked fine in the past, however now I am experiencing a strange problem: the socket takes an incredibly long t... | [
"Networks always have intermittent problems and your code will need to deal with them. I suggest two levels of action. First, use the timeout= argument on socket.create_connection to wait a bit longer before giving up. Then put the socket opening inside a try except socket.timeout pair and retry a couple of times, ... | [
1
] | [] | [] | [
"python",
"python_3.x",
"sockets"
] | stackoverflow_0006169481_python_python_3.x_sockets.txt |
Q:
Mining Wikipedia for mapping relations for text mining
I am planning to develop a web-based application which could crawl wikipedia for finding relations and store it in a database. By relations, I mean searching for a name say,'Bill Gates' and find his page, download it and pull out the various information from t... | Mining Wikipedia for mapping relations for text mining | I am planning to develop a web-based application which could crawl wikipedia for finding relations and store it in a database. By relations, I mean searching for a name say,'Bill Gates' and find his page, download it and pull out the various information from the page and store it in a database. Information may include ... | [
"If you haven't already, you should have a look at DBpedia. Many categories of wiki articles have \"Infoboxes\" for the kinds of information you describe, and they've made a database out of it:\nhttp://en.wikipedia.org/wiki/DBpedia\nYou might also leverage some of the information in Metaweb's Freebase (which overl... | [
6,
2,
1
] | [] | [] | [
"data_mining",
"pattern_matching",
"python",
"text_mining",
"wikipedia"
] | stackoverflow_0006171764_data_mining_pattern_matching_python_text_mining_wikipedia.txt |
Q:
How to get the percentage frequency of letters at each position from a list of strings in python?
I have a list of strings like this:
list:
('aatt')
('aaga')
('aaac')
('gtag')
#the real list have thousands of strings
the optimal desired result is a tabular separated file like this:
0 1 2 3
a:7... | How to get the percentage frequency of letters at each position from a list of strings in python? | I have a list of strings like this:
list:
('aatt')
('aaga')
('aaac')
('gtag')
#the real list have thousands of strings
the optimal desired result is a tabular separated file like this:
0 1 2 3
a:75% a:75% a:50% a:25%
g:25% t:25% g:25% c:25%
t:25% g:25%
... | [
"Getting some harsh comments here but I will try to give you some pointers :) From the looks of your data it seems like you are trying to do SNP calling for a list of sequences you have? Given such data:\nd = ['aatt','aaga','aaac','gtag']\n\nThe first thing you should do is preallocate a dictionary that would store... | [
3
] | [] | [] | [
"grouping",
"list",
"position",
"python"
] | stackoverflow_0006171916_grouping_list_position_python.txt |
Q:
Regex Python - Find every keyword instance, extract keyword and proceeding characters
This is driving me insane.
I'm trying to find every instance of "DOI" or it's mis-scanned equivalents in a series of documents. I then want to collect the term "DOI" and up to 15 alpha numeric characters that should come after ... | Regex Python - Find every keyword instance, extract keyword and proceeding characters | This is driving me insane.
I'm trying to find every instance of "DOI" or it's mis-scanned equivalents in a series of documents. I then want to collect the term "DOI" and up to 15 alpha numeric characters that should come after it. But I also need to ensure I find these even if they overlap with a previous match.
I'v... | [
"Using the \"DOI variations\" DOI|DO1|D01|D0I|001|00I|0O1|0OI|O01|O0I|OO1|OOI literally in that form is not a good idea. Start from basics: D+0+O, O+0, and I+1. This leads immediately to the pattern \"[D0O][O0][I1]\" which is much more compact, less error prone, and capable of much faster execution (if you wanted t... | [
2
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0006172091_python_regex.txt |
Q:
Memory management of large lists in Python
Today I wrote a program using an array/list with 64000000 entries. However, when writing sigma=[1]*64000000 using Python it runs fine, but later on, as the program computes, my Ubuntu freezes - without any reaction to inputs, not even mouse movement. I tried twice and the... | Memory management of large lists in Python | Today I wrote a program using an array/list with 64000000 entries. However, when writing sigma=[1]*64000000 using Python it runs fine, but later on, as the program computes, my Ubuntu freezes - without any reaction to inputs, not even mouse movement. I tried twice and the results are the same.
When implemented in C++, ... | [
"Python lists are lists of objects. A number in Python is an object in itself, and takes up somewhat more storage than the 64 bits needed to represent a long long in C++. In particular, Python transparently handles numbers larger than 32 bits, which end up taking a lot more space than a simple integer.\nYou may be ... | [
7,
2
] | [] | [] | [
"list",
"memory_management",
"python"
] | stackoverflow_0006172351_list_memory_management_python.txt |
Q:
make a number of lines of string into one long line in python
Say i had the string:
string = '''
this line number 1
line 2
line 3
line 4
'''
How would you make it into:
this is line number 1line 2line 3line4
Does anyone know?
A:
Use join and splitlines:
>>> string = '''
... this line number 1
... line 2
... li... | make a number of lines of string into one long line in python | Say i had the string:
string = '''
this line number 1
line 2
line 3
line 4
'''
How would you make it into:
this is line number 1line 2line 3line4
Does anyone know?
| [
"Use join and splitlines:\n>>> string = '''\n... this line number 1\n... line 2\n... line 3\n... line 4\n... '''\n>>> ''.join(string.splitlines())\n'this line number 1line 2line 3line 4'\n\nThis is better than a .replace(\"\\n\", \"\") because it deals with \\r\\n and \\n:\n>>> \"\".join(\"a\\r\\nb\\nc\".splitlines... | [
7,
2,
1,
0
] | [] | [] | [
"python",
"string"
] | stackoverflow_0006172404_python_string.txt |
Q:
Config python script which knows its filename
I'd like to save complex configuration by writing some Python code with variable assignments and functions which I will import later by a ConfigReader class.
Basically so far I've written my config file:
a=1
And a class that works like
c=ConfigReader("C:\my_file")
pri... | Config python script which knows its filename | I'd like to save complex configuration by writing some Python code with variable assignments and functions which I will import later by a ConfigReader class.
Basically so far I've written my config file:
a=1
And a class that works like
c=ConfigReader("C:\my_file")
print(c.a)
For that I used exec(), but now I also wan... | [
"When you exec a Python script, there is no filename, because you are giving exec a string or a compiled object. The exec command has no way to know where you got this string.\nBut there is a way to share the knowledge with the config file that you are passing to exec. For example...\nLet's say you have a config fi... | [
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0006170141_python.txt |
Q:
PyGTK properties versus python properties
When deriving from a GObject class in PyGTK, you can define GObject properties like in C, using a __gproperties__ dict, and do_get_property/do_set_property methods, as described here in Sub-classing GObject in Python. Note that this was written before we had the @property ... | PyGTK properties versus python properties | When deriving from a GObject class in PyGTK, you can define GObject properties like in C, using a __gproperties__ dict, and do_get_property/do_set_property methods, as described here in Sub-classing GObject in Python. Note that this was written before we had the @property decorator in Python.
GObject properties have th... | [
"\nOther than that, is there any good reason to use GObject properties instead of Python's @property decorator?\n\nNot really. There's a lot of boilerplate for them, so unless I need the notify signals, I write whatever I need in Python.\nHaving said that, it's fairly common that I'll think \"I don't need notificat... | [
1,
1
] | [] | [] | [
"gobject",
"properties",
"pygtk",
"python"
] | stackoverflow_0005964634_gobject_properties_pygtk_python.txt |
Q:
Static root page on Google AppEngine
I'm trying to set up a static landing page for a google appengine application. However I get 404 when I go to the root of the site. It works fine locally just doesn't work when I deploy it. The app.html page work so its just the landing page thats not working.
Here's something ... | Static root page on Google AppEngine | I'm trying to set up a static landing page for a google appengine application. However I get 404 when I go to the root of the site. It works fine locally just doesn't work when I deploy it. The app.html page work so its just the landing page thats not working.
Here's something from app.yaml
handlers:
- url: /rest/.*
... | [
"Change those backslashes to forward-slashes.\nShould be:\n\n- url: /\n static_files: static/index.html\n upload: static/index.html\n\nBackslashes are escape characters.\nSo you were specifying a path that doesn't exist.\n"
] | [
9
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0006172585_google_app_engine_python.txt |
Q:
Random searching and modification of a file in python
I feel like this is simple, but I just don't know enough about python to do it correctly.
I have two files:
File with lines listing an id number and whether that id is used. Format is 'id, isUsed'.
File with rules containing one rule for each id.
So what I wa... | Random searching and modification of a file in python | I feel like this is simple, but I just don't know enough about python to do it correctly.
I have two files:
File with lines listing an id number and whether that id is used. Format is 'id, isUsed'.
File with rules containing one rule for each id.
So what I want to do is to parse through the file with id-used pairs an... | [
"I suggest you read the rules file into a dictionary (id -> rule). Then, as you read the config file, write out the corresponding rule (including a comment if you need to).\nsome pseudocode:\nrules = {}\nfor id, rule in read_rules_file():\n rules[id] = rule\nfor id, isUsed in read_pairs_file():\n if isUsed:\n... | [
4,
0
] | [] | [] | [
"find",
"python",
"replace",
"string"
] | stackoverflow_0006124701_find_python_replace_string.txt |
Q:
My python build binaries not really running as 64bit program in AMD Win2003r2x64 machine
My problem is
my python binaries not running as 64bits program on my amd64(Opteron 8214, 4 cpu) server.
The machine is a Dual-Core, so there are 8 core shown in taskmgr.
It shown no "*32" in taskmgr(so it probably already in 6... | My python build binaries not really running as 64bit program in AMD Win2003r2x64 machine | My problem is
my python binaries not running as 64bits program on my amd64(Opteron 8214, 4 cpu) server.
The machine is a Dual-Core, so there are 8 core shown in taskmgr.
It shown no "*32" in taskmgr(so it probably already in 64bits mode), but use only one core.
And I take same code(project) to compiled and executed on ... | [
"You might want to check out the subprocess and threading modules that come with the standard Python library with regards to your multi-core issue. As for the 64bit issue, are you sure you need the additional memory space? I've never had any issue with 32bit python.\n"
] | [
0
] | [] | [] | [
"py2exe",
"python",
"pywin32",
"windows_server_2003",
"x86_64"
] | stackoverflow_0005179743_py2exe_python_pywin32_windows_server_2003_x86_64.txt |
Q:
Python Scraper for Javascript?
Can anyone direct me to a good Python screen scraping library for javascript code (hopefully one with good documentation/tutorials)? I'd like to see what options are out there, but most of all the easiest to learn with fastest results... wondering if anyone had experience. I've heard... | Python Scraper for Javascript? | Can anyone direct me to a good Python screen scraping library for javascript code (hopefully one with good documentation/tutorials)? I'd like to see what options are out there, but most of all the easiest to learn with fastest results... wondering if anyone had experience. I've heard some stuff about spidermonkey, but ... | [
"What I usually do is automate an actual browser in these cases, and grab the processed HTML from there.\nEdit:\nHere's an example of automating InternetExplorer to navigate to a URL and grab the title and location after the page loads.\nfrom win32com.client import Dispatch\n\nfrom ctypes import Structure, pointer,... | [
1,
1,
1
] | [] | [] | [
"javascript",
"python",
"screen_scraping"
] | stackoverflow_0002926338_javascript_python_screen_scraping.txt |
Q:
Google App Engine - Go vs. Python recommendations?
I'm looking into writing my first application of Google App Engine. C# is my 'native' language, and so writing the app in Java would of course be most logical. BUT, I'm a geek and would like to take to opportunity to learn something new.
Therefore its a toss-up be... | Google App Engine - Go vs. Python recommendations? | I'm looking into writing my first application of Google App Engine. C# is my 'native' language, and so writing the app in Java would of course be most logical. BUT, I'm a geek and would like to take to opportunity to learn something new.
Therefore its a toss-up between Python and Go.
Do you have a strong preference b... | [
"The recently-released Go runtime for App Engine is labelled experimental for a reason: Both Go and Go-on-appengine are new and in a state of change.\nIf you want to experiment with Go and running Go apps in the cloud, go for it. If you want to write a production app on App Engine, use Python or Java.\n",
"This q... | [
13,
5,
5,
4,
3,
1
] | [] | [] | [
"go",
"google_app_engine",
"java",
"python"
] | stackoverflow_0006166660_go_google_app_engine_java_python.txt |
Q:
How do I read album artwork using python?
In my searches I have found that there are a few libraries that might be able to do this by reading ID3 tags. If so - which one would be the best to use? I don't plan on writing any data just reading.
Also I'm trying to make this app as portable as possible so the least a... | How do I read album artwork using python? | In my searches I have found that there are a few libraries that might be able to do this by reading ID3 tags. If so - which one would be the best to use? I don't plan on writing any data just reading.
Also I'm trying to make this app as portable as possible so the least amount of dependencies would be a huge bonus. ... | [
"I'd recommend mutagen, it's a pure python library with no other dependencies and it supports a lot of different audio metadata formats/tags (MP3, FLAC, M4A, Monkey's Audio, Musepack, and more). To extract artwork from an ID3 v2.4 MP3 saved with iTunes:\nfrom mutagen import File\n\nfile = File('some.mp3') # mutagen... | [
18,
1
] | [] | [] | [
"id3",
"mp3",
"object",
"python"
] | stackoverflow_0006171565_id3_mp3_object_python.txt |
Q:
Calling .php within a Django/Python file
I am building an application in Django and want to run a .php script I already have made earlier. I need to be able to give along a string to the .php file and catch the returning output. Does anyone have an idea how to do this? Can I make some kind of http request and catc... | Calling .php within a Django/Python file | I am building an application in Django and want to run a .php script I already have made earlier. I need to be able to give along a string to the .php file and catch the returning output. Does anyone have an idea how to do this? Can I make some kind of http request and catch the response?
p.s. I already tried converti... | [
"try this one, i've found it here\nimport subprocess\n\n#simple caller, disguard output\n\nsubprocess.call(\"php /path/to/my/old/script.php\")\n\n# if you want output\n\nproc = subprocess.Popen(\"php /path/to/my/script.php\", shell=True,\nstdout=subprocess.PIPE)\n\nscript_response = proc.stdout.read()\n\n",
"If i... | [
8,
0
] | [] | [] | [
"django",
"php",
"python"
] | stackoverflow_0006171318_django_php_python.txt |
Q:
python noobie scoping question
I wrote this code:
x = 0
def counter():
x = 1
def temp(self):
print x
x += 1
return temp
Trying to test if python is lexical or dynamic scope. My thinking was that
y = counter()
y()
Should either print 0 or 1, and that would tell me how python is scoped. However, calling y ... | python noobie scoping question | I wrote this code:
x = 0
def counter():
x = 1
def temp(self):
print x
x += 1
return temp
Trying to test if python is lexical or dynamic scope. My thinking was that
y = counter()
y()
Should either print 0 or 1, and that would tell me how python is scoped. However, calling y throws an exception saying that x is... | [
"From the docs:\n\nA special quirk of Python is that – if\n no global statement is in effect –\n assignments to names always go into\n the innermost scope. Assignments do\n not copy data — they just bind names\n to objects.\n\nSo, when Python parses\n def temp(self):\n print x\n x += 1\n\nit sees the assignm... | [
10,
6,
2,
2,
1
] | [] | [] | [
"python",
"scoping"
] | stackoverflow_0006171033_python_scoping.txt |
Q:
What is an easy way to clean an unparsable csv file
The csv file was created correctly but the name and address fields contain every piece of punctuation there is available. So when you try to import into mysql you get parsing errors. For example the name field could look like this, "john ""," doe". I have no cont... | What is an easy way to clean an unparsable csv file | The csv file was created correctly but the name and address fields contain every piece of punctuation there is available. So when you try to import into mysql you get parsing errors. For example the name field could look like this, "john ""," doe". I have no control over the data I receive so I'm unable to stop people ... | [
"This may not be a usable answer but someone needs to say it. You shouldn't have to do this. CSV is a file format with an expected data encoding. If someone is supplying you a CSV file then it should be delimited and escaped properly, otherwise its a corrupted file and you should reject it. Make the supplier re-exp... | [
7,
1,
1,
0,
0,
0
] | [] | [] | [
"csv",
"mysql",
"php",
"python"
] | stackoverflow_0006172123_csv_mysql_php_python.txt |
Q:
Parsing php array in python
I'm getting a PHP array from a web page (as a string).
It looks like :
Array
(
[k1] => Array
(
[a] => Array
(
[id] => 1
[age] => 60
)
[b] => Array
(
[id] => 2
[age] =... | Parsing php array in python | I'm getting a PHP array from a web page (as a string).
It looks like :
Array
(
[k1] => Array
(
[a] => Array
(
[id] => 1
[age] => 60
)
[b] => Array
(
[id] => 2
[age] => 30
)
)
[k2] =... | [
"That's not JSON, that's just how PHP prints arrays. If you want to create JSON of the array, check out json_encode for PHP. Then use Python's JSON library (or here for py3) to read it.\n",
"If I understood you correctly, you are using print_r on array to get that output. This is a visual representation of array ... | [
10,
4
] | [] | [] | [
"parsing",
"php",
"python"
] | stackoverflow_0006174031_parsing_php_python.txt |
Q:
Reraise HTTPError with extra info
I want to catch a urllib2.HTTPError with extra information if it's a 404:
try:
data = urlopen(url)
except HTTPError, e: # Python 2.5 syntax
if e.code == 404:
raise HTTPError('data not found on remote')
else:
raise
but this doesn't work because HTTPErr... | Reraise HTTPError with extra info | I want to catch a urllib2.HTTPError with extra information if it's a 404:
try:
data = urlopen(url)
except HTTPError, e: # Python 2.5 syntax
if e.code == 404:
raise HTTPError('data not found on remote')
else:
raise
but this doesn't work because HTTPError's init takes multiple arguments, whi... | [
"The HTTPError already contains all the information you require, you can simply reraise it like this\nraise HTTPError(e.url, e.code, \"your message.\", e.hdrs, e.fp)\n\n",
"You just need to use e.msg rather than e.message. The script:\nfrom urllib2 import urlopen, HTTPError\n\nurl = 'http://www.red-dove.com/frob'... | [
10,
5
] | [] | [] | [
"exception",
"exception_handling",
"python",
"urllib2"
] | stackoverflow_0006174560_exception_exception_handling_python_urllib2.txt |
Q:
Any ready solution for basic asynchronous (non-blocking) HTTP clients with Stackless Python 3.1?
UPDATE: after much laboring with Py3, including writing my own asynchronous webserver (following a presentation given by Dave Beazley), i finally dumped Python (and a huge stack of my code )-: in favor of CoffeeScript ... | Any ready solution for basic asynchronous (non-blocking) HTTP clients with Stackless Python 3.1? | UPDATE: after much laboring with Py3, including writing my own asynchronous webserver (following a presentation given by Dave Beazley), i finally dumped Python (and a huge stack of my code )-: in favor of CoffeeScript running on NodeJS. Check it out: GitHub (where you'll find like 95% of all interesting code these days... | [
"I know this is like resurrecting the dead (and flow has probably long since solved his problem), but for completeness stackless is available for 3.1.3:\n\nhttp://www.stackless.com/download\n\nFor information on implementing a HTTP server using stacklesssocket:\n\nhttp://code.google.com/p/stacklessexamples/wiki/Sta... | [
0,
0
] | [] | [] | [
"http",
"python",
"python_stackless",
"stackless"
] | stackoverflow_0002372762_http_python_python_stackless_stackless.txt |
Q:
Generate in flight string from [A-z]
I want to know what is a simplest way to write method which generates me number from 1 to 50, and then depends of generated number returns me string like:
Abcdef if generated number is 6
Abcdefghi if generated number is 9.
I'm using python 3.2
A:
There's a few approaches, the... | Generate in flight string from [A-z] | I want to know what is a simplest way to write method which generates me number from 1 to 50, and then depends of generated number returns me string like:
Abcdef if generated number is 6
Abcdefghi if generated number is 9.
I'm using python 3.2
| [
"There's a few approaches, the simplest:\n>>> import string\n>>> import random\n>>> string.ascii_letters[:random.randint(1, 50)].title()\n'Abcdefghijklmnopq'\n>>> string.ascii_letters[:random.randint(1, 50)].title()\n'Abcdefghijklmnopqrstuvwxyzabcdefghijklmnopq'\n>>> string.ascii_letters[:random.randint(1, 50)].tit... | [
8
] | [] | [] | [
"python",
"random"
] | stackoverflow_0006174827_python_random.txt |
Q:
Getting filenames matching an extension using BeautifulSoup
I am trying to parse a HTML page using BeautifulSoup which has text files, ending with the .txt extension. I want to parse the HTML, and fetch the string that ends with .txt.
All such strings are within a <a href> tag and here are some examples:
<a href =... | Getting filenames matching an extension using BeautifulSoup | I am trying to parse a HTML page using BeautifulSoup which has text files, ending with the .txt extension. I want to parse the HTML, and fetch the string that ends with .txt.
All such strings are within a <a href> tag and here are some examples:
<a href = "foo.txt">
<a href = "bar.txt">
How do I get the foo.txt and bar... | [
"BeautifulSoup accepts regexps as parameter form find() and findAll()\nThis should work:\nlinks = soup.findAll(href=re.compile(\"\\.txt$\"))\n\n"
] | [
8
] | [] | [] | [
"beautifulsoup",
"python"
] | stackoverflow_0006174825_beautifulsoup_python.txt |
Q:
Alternative to deprecated sqlite pragma "default_cache_size"
The sqlite docs says that using the pragma default_cache_size is deprecated. I looked, but I couldn't see any explanation for why. Is there a reason for this? I'm working on an embedded python program, and we open and close connections a lot. Is the only... | Alternative to deprecated sqlite pragma "default_cache_size" | The sqlite docs says that using the pragma default_cache_size is deprecated. I looked, but I couldn't see any explanation for why. Is there a reason for this? I'm working on an embedded python program, and we open and close connections a lot. Is the only alternative to use the pragma cache_size on every database connec... | [
"As Firefox is massively using SQLite I wouldn't be surprised if this request came from their camp to prevent any kind of 3rd party interference (e.g. \"trashing\" with large/small/invalid/obscure values) by this kind of pragma propagating through all database connections\nHence, my strong belief is that there is n... | [
2
] | [] | [] | [
"python",
"sqlite"
] | stackoverflow_0006062999_python_sqlite.txt |
Q:
How to improve performance in visualizing data from database on admin site of django?
This are my first steps with django so please take no offense if this seems trivial.
I have a very huge table mynames (~ 1 000 000 entrys) and I want to make this table editable in the django admin site. I hooked things up like ... | How to improve performance in visualizing data from database on admin site of django? | This are my first steps with django so please take no offense if this seems trivial.
I have a very huge table mynames (~ 1 000 000 entrys) and I want to make this table editable in the django admin site. I hooked things up like described in the official django book: I have a model, and I registered it by admin.site.re... | [
"It would be easier to see what the problem is if you pasted your full model class. Is there a specified ordering on the table? If so, you need to create a corresponding index to make pagination on that field fast. Is the list_display attribute set on the ModelAdmin class for the model? By default, django should or... | [
0
] | [] | [] | [
"django",
"django_admin",
"mysql",
"performance",
"python"
] | stackoverflow_0006156352_django_django_admin_mysql_performance_python.txt |
Q:
Optimize method in python. Similar to permutation
I have a method which generates me number of passengers to reservation process. The parameters are the minimum and maximum numbers of passengers.
There are only 2 conditions:
number_of_adults must be greater than 0
number_of_infants must be less than or equal to ... | Optimize method in python. Similar to permutation | I have a method which generates me number of passengers to reservation process. The parameters are the minimum and maximum numbers of passengers.
There are only 2 conditions:
number_of_adults must be greater than 0
number_of_infants must be less than or equal to number_of_adults
This is code:
def generate_numbe... | [
"Your number_of_infants calculation should be simply:\nnumber_of_infants = number_of_passengers - number_of_adults - number_of_youths - number_of_children\n\nOtherwise it is likely to be lower than the required number to meet your passenger requirements (a random number between 0 and number_of_passengers - number_o... | [
2
] | [] | [] | [
"optimization",
"permutation",
"python"
] | stackoverflow_0006175237_optimization_permutation_python.txt |
Q:
Searching for a string from a line number in both directions
Using Python 2.4, I am reading a large flat file and picking a particular line number. Now I want to search for a string, say, START before that line number, and a string END, after that line number.
How do I get the line numbers of the nearest occurrenc... | Searching for a string from a line number in both directions | Using Python 2.4, I am reading a large flat file and picking a particular line number. Now I want to search for a string, say, START before that line number, and a string END, after that line number.
How do I get the line numbers of the nearest occurrences of the strings START (before current line number) and END (afte... | [
"How about this:\nline_no = 1\n\n# Seek the last START before reaching the target line.\nstart_line_no = -1\nwhile line_no != target_line_no:\n line = input.readline()\n if line == \"\":\n # File is shorter than you think.\n break\n line_no += 1\n if START in line:\n start_line_no =... | [
2
] | [] | [] | [
"python",
"search",
"string",
"variables"
] | stackoverflow_0006175091_python_search_string_variables.txt |
Q:
Correct xpath syntax with pythons lxml library for parsing all the text from arbitrary nested html tags
Using lxml in python I created this xpath syntax
htmlPage.xpath("/html/body//a/text()")
It gets me all <a>-tags in certain html scopes I desire. Now I encountered that the <a>-tags could look like this:
<a>Thi... | Correct xpath syntax with pythons lxml library for parsing all the text from arbitrary nested html tags | Using lxml in python I created this xpath syntax
htmlPage.xpath("/html/body//a/text()")
It gets me all <a>-tags in certain html scopes I desire. Now I encountered that the <a>-tags could look like this:
<a>This is a sentence with some <italic>italic text</italic>-formatting I want to parse.</a>
xpath returns me a li... | [
"I solved my problem by first getting all <a>-tags\nresults = htmlPage.xpath(\"/html/body//a\")\n\nand then iterating the returned list and using text_content() on the list elements\nfor a_tag in results:\n print a_tag.text_content() # prints bthe whol string: \"This is a sentence with some italic text-formattin... | [
2
] | [] | [] | [
"html",
"lxml",
"parsing",
"python",
"xpath"
] | stackoverflow_0006175049_html_lxml_parsing_python_xpath.txt |
Q:
decrypt excel files
Hi I have 1000 encrypted workbooks which I would like to decrypt by providing a pwd.
I could not find a decrypt method under apache poi or python's xlrd module.
Does anyone know a library which could handle this (wbc.decrypt(pwd)). I would prefer a lib i could you use from a unix box.
Thanks
A... | decrypt excel files | Hi I have 1000 encrypted workbooks which I would like to decrypt by providing a pwd.
I could not find a decrypt method under apache poi or python's xlrd module.
Does anyone know a library which could handle this (wbc.decrypt(pwd)). I would prefer a lib i could you use from a unix box.
Thanks
| [
"Use the COM bindings to call the Unprotect method.\nimport win32com.client\n\nexcel = win32com.client.Dispatch('Excel.Application')\n\nworkbook = excel.Workbooks.open(r'c:\\mybook.xls', 'password')\n\nworkbook.SaveAs('unencrypted.xls')\n\nSaveAs can apply a new password. See: http://msdn.microsoft.com/en-us/librar... | [
6,
1
] | [] | [] | [
"apache_poi",
"excel",
"python"
] | stackoverflow_0002450530_apache_poi_excel_python.txt |
Q:
Populate arrays in python (numpy)?
Given a file in the format below:
a a 0
a b 1
a c 1
b b 0
b a 1
b c 1
c c 0
c a 1
c b 1
The third column is the distance between the items in the first and second columns. If I read such a file into pyton as a nested list, how do I convert it to a symmetrical matrix, i.e.,
a b... | Populate arrays in python (numpy)? | Given a file in the format below:
a a 0
a b 1
a c 1
b b 0
b a 1
b c 1
c c 0
c a 1
c b 1
The third column is the distance between the items in the first and second columns. If I read such a file into pyton as a nested list, how do I convert it to a symmetrical matrix, i.e.,
a b c
a 0 1 1
b 1 0 1
b 1 1 0
? I also wis... | [
"import numpy as np\nfrom itertools import count\n\ndata = [line.split() for line in inputfile.readlines()]\nrows = dict(zip(sorted(set(line[0] for line in data)), count()))\ncols = dict(zip(sorted(set(line[1] for line in data)), count()))\narray = np.zeros((len(rows), len(cols)))\n\nfor row, col, val in data:\n ... | [
4,
2
] | [] | [] | [
"arrays",
"numpy",
"python"
] | stackoverflow_0006150375_arrays_numpy_python.txt |
Q:
twisted and more clients in script
Hello
I'm new in twisted, but have some questions after read manual:
1. How to use different protocols with different reactor in one program? (for example, txNetTools have own reactor and internal IRC support in twisted have own reactor from twisted.internet)
2. How to start more... | twisted and more clients in script | Hello
I'm new in twisted, but have some questions after read manual:
1. How to use different protocols with different reactor in one program? (for example, txNetTools have own reactor and internal IRC support in twisted have own reactor from twisted.internet)
2. How to start more one client in one time? (many client wi... | [
"Well, for the third question at least, are you talking about using protocols of different classes or multiple protocol instances of the same class? Protocol instances can communicate between each other by having the factory that creates them store their data, like the following:\nclass p(Protocol):\n factory = ... | [
1,
1
] | [] | [] | [
"asynchronous",
"multithreading",
"python",
"twisted"
] | stackoverflow_0006170129_asynchronous_multithreading_python_twisted.txt |
Q:
How to fill colors in piechart using Pychart
I am using python Pychart.
I have done the following code to generate pie chart:
from pychart import *
import sys
data = [("foo", 10),("bar", 20), ("baz", 30), ("ao", 40)]
theme.get_options()
ar = area.T(size=(150,150), legend=legend.T(),
x_grid_style ... | How to fill colors in piechart using Pychart | I am using python Pychart.
I have done the following code to generate pie chart:
from pychart import *
import sys
data = [("foo", 10),("bar", 20), ("baz", 30), ("ao", 40)]
theme.get_options()
ar = area.T(size=(150,150), legend=legend.T(),
x_grid_style = None, y_grid_style = None)
plot = pie_plot.T(dat... | [
"Add theme.use_color = True before the call to get_options().\nFor the theme documentation:\n\nuse_color\nThe default value of this variable is\n False. If the value is True, PyChart\n colorizes some of the default objects.\n If the value is False, PyChart uses\n gray scale for the color of these\n objects.\n\... | [
2,
1,
1
] | [] | [] | [
"charts",
"python"
] | stackoverflow_0006175871_charts_python.txt |
Q:
Adding row to xml using lxml
I have a method which saves from reservations, but overwrites the output file every time when I create a new instance of XmlReportGenerator
from lxml import etree
from Flights.FlightTravelReservation import FlightTravelReservation
class XmlReportGenerator:
root = None
doc = No... | Adding row to xml using lxml | I have a method which saves from reservations, but overwrites the output file every time when I create a new instance of XmlReportGenerator
from lxml import etree
from Flights.FlightTravelReservation import FlightTravelReservation
class XmlReportGenerator:
root = None
doc = None
def __init__(self):
... | [
"You'll need to define a Load function for XmlReportGenerator to load the old results.\nclass XmlReportGenerator(object):\n def __init__(self):\n # __init__, add_flight_row, and Save\n\n def load(self, path='Flights.xml'):\n try:\n self.doc = etree.ElementTree()\n self.root = s... | [
2,
0
] | [] | [] | [
"lxml",
"python"
] | stackoverflow_0006174765_lxml_python.txt |
Q:
how to show a preview of link (not a screenshot) in a website
I wanna show small preview(not screenshot) of a website link in a page..like in pulse app it show the preview of feeds.Is there any api in python.How will u do in python and django .Any help would be appreciate
A:
You could create an ImageField to ho... | how to show a preview of link (not a screenshot) in a website | I wanna show small preview(not screenshot) of a website link in a page..like in pulse app it show the preview of feeds.Is there any api in python.How will u do in python and django .Any help would be appreciate
| [
"You could create an ImageField to hold the JPEG preview, and modifiy the save() method of your model to create a preview if the field is blank\nA simple tool to create the preview is wkhtmltopdf.\nBeware it can be necessary to install a lot of libraries to make it work...\n"
] | [
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0006175013_django_python.txt |
Q:
Python, best approach for unicode support?
I have a Python application that gets multilingual information from websites, and it presents them in a small GUI window (wxpython based).
I (currently) don't use any specific unicode statements in my source files.
Now, when I run my python application from within Eclipse... | Python, best approach for unicode support? | I have a Python application that gets multilingual information from websites, and it presents them in a small GUI window (wxpython based).
I (currently) don't use any specific unicode statements in my source files.
Now, when I run my python application from within Eclipse, French characters (like ë) are displayed nicel... | [
"The best approach is to ensure the strings are unicode as soon as possible. If the library you are scraping websites with are not proving you with unicode then they are not doing what they should (imho). Then you have to your self decode them to unicode using the same encoding that the web pages you are scraping i... | [
6,
1,
0
] | [] | [] | [
"py2exe",
"python",
"unicode"
] | stackoverflow_0006175238_py2exe_python_unicode.txt |
Q:
How to set the button sticky property properly?
I've been playing around with tkinter a bit and I can't figure out why the "sticky" attribute doesn't seem to be working with my button. I've specified sticky to be NW which should cause my button to stick to the top left edge but for some reason it sticks to the to... | How to set the button sticky property properly? | I've been playing around with tkinter a bit and I can't figure out why the "sticky" attribute doesn't seem to be working with my button. I've specified sticky to be NW which should cause my button to stick to the top left edge but for some reason it sticks to the top right. Any idea why?
from tkinter import *
from tk... | [
"The sticky attribute applies to the cell that the widget is in, rather than to the whole grid or whole window. So, the widget is anchored to the nw corner of its cell, it's just that you can't tell because the cell is exactly the same width as the button.\nSince you are placing the button in the upper right cell (... | [
11,
1
] | [] | [] | [
"python",
"sticky",
"tkinter"
] | stackoverflow_0006171493_python_sticky_tkinter.txt |
Q:
Get browser object via python?
I'm ready to write a program to analyze some statics in webpages,
and I found many python library for HTML DOM parsing such as html5lib, Beautiful Soup...
However, I found it hard to access browser object like window object by python.
Is it possible to use python to fetch browser obj... | Get browser object via python? | I'm ready to write a program to analyze some statics in webpages,
and I found many python library for HTML DOM parsing such as html5lib, Beautiful Soup...
However, I found it hard to access browser object like window object by python.
Is it possible to use python to fetch browser object just like javascript?
e.g window... | [
"It's impossible. The window object is available only for JavaScript code running inside a browser, but you are parsing a HTML file in a Python script. Maybe you should ask a more specific question explaining in more detail what are you actually trying to achieve.\n",
"Maybe you can try PyQt's QWebkit, it can acc... | [
0,
0
] | [] | [] | [
"html_parsing",
"python"
] | stackoverflow_0006175663_html_parsing_python.txt |
Q:
python: complexity of os.path.exists with a ext4 filesystem?
Does anyone know what the complexity of the os.path.exists function is in python with a ext4 filesystem?
A:
Underlying directory structure used by Ext4 (and Ext3) is exactly the same as in Ext2. Ext3 adds journaling, Ext4 improves that journaling. Jour... | python: complexity of os.path.exists with a ext4 filesystem? | Does anyone know what the complexity of the os.path.exists function is in python with a ext4 filesystem?
| [
"Underlying directory structure used by Ext4 (and Ext3) is exactly the same as in Ext2. Ext3 adds journaling, Ext4 improves that journaling. Journaling is irrelevant to your question. \nOriginally Ext2 used to store that as list, but that of course was inefficient for large directories. So it's has been changed to ... | [
9,
0
] | [] | [] | [
"complexity_theory",
"ext4",
"linux",
"python"
] | stackoverflow_0006176547_complexity_theory_ext4_linux_python.txt |
Q:
Returning objects to Python from C
I've read the documentation for the Python C-API, and even written a few extension modules. However, I'm still a bit unclear on the exact semantics when it comes to returning Python objects from a C function.
The limited examples in the Python docs usually show a C function whic... | Returning objects to Python from C | I've read the documentation for the Python C-API, and even written a few extension modules. However, I'm still a bit unclear on the exact semantics when it comes to returning Python objects from a C function.
The limited examples in the Python docs usually show a C function which returns the result of Py_BuildValue. ... | [
"Python expects any function you expose to it to return a new reference, yes. If you only have a borrowed reference, you have to call Py_INCREF to give a new reference. If you return a borrowed reference, Python will proceed to call Py_DECREF (when it's done with the reference), and eventually that will cause the o... | [
6
] | [] | [] | [
"c",
"python",
"python_c_api",
"python_c_extension"
] | stackoverflow_0006176668_c_python_python_c_api_python_c_extension.txt |
Q:
How to split python tasks across a network
I have a python program that performs several independent and time consuming processes. The python code is generally an automater, that calls into several batch files via popen.
The program currently takes several hours, so I'd like to split it up across multiple machine... | How to split python tasks across a network | I have a python program that performs several independent and time consuming processes. The python code is generally an automater, that calls into several batch files via popen.
The program currently takes several hours, so I'd like to split it up across multiple machines. How can I split tasks to process in parallel... | [
"There are many Python parallelisation frameworks out there. Just two of the options:\n\nThe parallel computing facilities of IPython\nThe parallelisation framework jug\n\n",
"For the remote execution you could use execnet. Do you have to distribute the data too?\n",
"I might suggest STAF. It's advertised as ... | [
6,
0,
0
] | [] | [] | [
"parallel_processing",
"python"
] | stackoverflow_0006176440_parallel_processing_python.txt |
Q:
Building a list of monthly totals
I have a list of objects representing widgets. Each widget object has a manufactured DateTime field that holds the date and time when the widget was made. All the widgets in the list were manufactured in a particular year.
I would like to get a list with the total widgets manufact... | Building a list of monthly totals | I have a list of objects representing widgets. Each widget object has a manufactured DateTime field that holds the date and time when the widget was made. All the widgets in the list were manufactured in a particular year.
I would like to get a list with the total widgets manufactured each month - e.g.:
>>> totals
[1,... | [
"totals = [0] * 12\nfor widget in widgets:\n totals[widget.datetime.month - 1] += 1\n\nThe indices of totals are in the range 0 to 11, while months usually are in the range 1 to 12, so we need the - 1.\nAn alternative in Python 2.7 or 3.1 or above:\nfrom collections import Counter\ntotals = Counter(widget.dateti... | [
5,
0
] | [] | [] | [
"python"
] | stackoverflow_0006176797_python.txt |
Q:
Developing OAuth for Google apps engine ...Python
RequestError: Unable to upgrade OAuth request token to access token: 400, signature_invalid
base_string:POST&https%3A%2F%2Fwww.google.com%2Faccounts%2FOAuthGetAccessToken&oauth_consumer_key%3Dcalendar-auth.appspot.com%26oauth_nonce%3D646112512717164%26oauth_signat... | Developing OAuth for Google apps engine ...Python | RequestError: Unable to upgrade OAuth request token to access token: 400, signature_invalid
base_string:POST&https%3A%2F%2Fwww.google.com%2Faccounts%2FOAuthGetAccessToken&oauth_consumer_key%3Dcalendar-auth.appspot.com%26oauth_nonce%3D646112512717164%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1306760936%2... | [
"https://www.google.com/accounts/OAuthGetAccessToken\n{\noauth_consumer_key=calendar-auth.appspot.com\noauth_nonce=646112512717164\noauth_signature_method=HMAC-SHA1\noauth_timestamp=1306760936\noauth_token=4/-cP-Ai1NzxDtLehvtzRbGd4SHZ1-\noauth_verifier=PYGMYX8riH9AfpJvTEh_Ztzm\noauth_version=1.0\n}\n\nI would recom... | [
0
] | [] | [] | [
"google_app_engine",
"oauth",
"python"
] | stackoverflow_0006177033_google_app_engine_oauth_python.txt |
Q:
how to configure the hotkey of notepad++ for python?
hi I am using notepad++ for python.
I want a hotkey that will run my python script at the path of the script instead of the path of notepad++.
Besides, at the end of process, i want it to show "press any key to continue".
I've tried:
cmd /k "$(FULL_CURRENT_PAT... | how to configure the hotkey of notepad++ for python? | hi I am using notepad++ for python.
I want a hotkey that will run my python script at the path of the script instead of the path of notepad++.
Besides, at the end of process, i want it to show "press any key to continue".
I've tried:
cmd /k "$(FULL_CURRENT_PATH)"
python "$(FULL_CURRENT_PATH)"
But none of them meets ... | [
"That's a good find - Notepad++ seems to always set the current working directory to it's own executable directory when scripts are run.\nOne workaround is to use this: Notepad++ Python Plug-in. This is a plug-in for Notepad++ and adds options to run your scripts in Python from the Plugins menu in Notepad++ (inste... | [
1
] | [] | [] | [
"notepad++",
"python"
] | stackoverflow_0006173209_notepad++_python.txt |
Q:
Regex Question: How can I check if any of values in list are matched?
I want to create a RE object that matches if the string contains at least one of the elements of a list.
For example, if bad_words["censored","stupid","idiot"] is the list, the RE would match if at least one of them exist.
This is my RE: re.comp... | Regex Question: How can I check if any of values in list are matched? | I want to create a RE object that matches if the string contains at least one of the elements of a list.
For example, if bad_words["censored","stupid","idiot"] is the list, the RE would match if at least one of them exist.
This is my RE: re.compile("(%s)+" % ("|".join(bad_words)), re.IGNORECASE)
Problem is that 'youare... | [
"While it's possible to do this with a regular expression, I think you are better off without a regex here. To test a string s against bad_words, try something like\ns = s.lower()\nany(bad in s for bad in bad_words)\n\nYour bad_words should all be lower case.\n",
"Are you using re.match? Try re.search. See Match... | [
11,
4
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0006177208_python_regex.txt |
Q:
Simple CGI web server in Python on VMS
I am trying to run an extremely simple CGI server on VMS done in python.
import sys
from BaseHTTPServer import HTTPServer
from CGIHTTPServer import CGIHTTPRequestHandler
server_address=('',8080)
httpd = HTTPServer(server_address, CGIHTTPRequestHandler)
httpd.serve_fo... | Simple CGI web server in Python on VMS | I am trying to run an extremely simple CGI server on VMS done in python.
import sys
from BaseHTTPServer import HTTPServer
from CGIHTTPServer import CGIHTTPRequestHandler
server_address=('',8080)
httpd = HTTPServer(server_address, CGIHTTPRequestHandler)
httpd.serve_forever()
The problem I have is that it serve... | [
"Are you using the Python port from http://hg.vmspython.org/vmspython/ ?\nIf so, I think this thread, and this file (which appears to implement a form of popen2), may hold the keys to your salvation. There appear to be VMS-specific modules (at least vms.starlet, vms.rtl.lib, vms.dvidef, vms.clidef) in the port that... | [
1,
0
] | [
"To execute a subprocess and get its output on posix:\nPython 2.7.1+ (r271:86832, Apr 11 2011, 18:13:53) \n[GCC 4.5.2] on linux2\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> from subprocess import Popen, PIPE\n>>> output = Popen(['/bin/ls', '/'], stdout = PIPE).communicate()[... | [
-1
] | [
"cgi",
"python",
"vms"
] | stackoverflow_0005864139_cgi_python_vms.txt |
Q:
Treectrl from database
I have a treectrl in my wxpython app. It is built from a database. It contains parent items and child items under their parent. What I need to do is grab some data related to the child parent which is selected. But there is a problem with this. Child parents may have the same name, even if t... | Treectrl from database | I have a treectrl in my wxpython app. It is built from a database. It contains parent items and child items under their parent. What I need to do is grab some data related to the child parent which is selected. But there is a problem with this. Child parents may have the same name, even if they are under the same paren... | [
"You can use the SetPyData and GetPyData methods to associate arbitrary data to your treectrl items. \n"
] | [
1
] | [] | [] | [
"database",
"python",
"wxpython"
] | stackoverflow_0006173057_database_python_wxpython.txt |
Q:
How to check from python, if an arbitrary program is installed
I guess what I'm looking for is closer to this question.
I'm running a python script (on a windows machine) that requires a program and a service to be installed. Since I have no control over which machines my script will be run on, I need to check fro... | How to check from python, if an arbitrary program is installed | I guess what I'm looking for is closer to this question.
I'm running a python script (on a windows machine) that requires a program and a service to be installed. Since I have no control over which machines my script will be run on, I need to check from within my script, whether or not the program and service are insta... | [
"Original answer edited since you clarified your question.\nyou can use the winreg module to do a check similar to your Java post.\nMore specifically, you can use the OpenKey method in a try block, catching a WindowsError if the key isn't found.\n"
] | [
1
] | [] | [] | [
"checkinstall",
"python",
"service",
"windows"
] | stackoverflow_0006177587_checkinstall_python_service_windows.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.