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:
Google app engine handle html form post array
My HTML code as following:
<INPUT type="text" name="txt[]">
<INPUT type="checkbox" name="chk[]"/>
I get the value in PHP by
<?php
$chkbox = $_POST['chk'];
$txtbox = $_POST['txt'];
foreach($txtbox as $a => $b)
echo "$chkbox[$a] - $txtbox[$a] <br />";
?>
How do ge... | Google app engine handle html form post array | My HTML code as following:
<INPUT type="text" name="txt[]">
<INPUT type="checkbox" name="chk[]"/>
I get the value in PHP by
<?php
$chkbox = $_POST['chk'];
$txtbox = $_POST['txt'];
foreach($txtbox as $a => $b)
echo "$chkbox[$a] - $txtbox[$a] <br />";
?>
How do get the value in Google App Engine using Python?
| [
"You don't need that trick in Python. You can have for example many fields with the same names:\n<INPUT type=\"text\" name=\"txt\">\n<INPUT type=\"text\" name=\"txt\">\n<INPUT type=\"text\" name=\"txt\">\n\n<INPUT type=\"checkbox\" name=\"chk\">\n<INPUT type=\"checkbox\" name=\"chk\">\n<INPUT type=\"checkbox\" name... | [
8
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0003342012_google_app_engine_python.txt |
Q:
django-mptt children selection works on localhost but not on server
I have the same code on localhost and on server (thanks to mercurial), but it works a little bit different. I want to render category and its subcategories in template using this code:
views.py:
def category(request, category_slug):
try:
... | django-mptt children selection works on localhost but not on server | I have the same code on localhost and on server (thanks to mercurial), but it works a little bit different. I want to render category and its subcategories in template using this code:
views.py:
def category(request, category_slug):
try:
category = Category.objects.get(slug=category_slug)
except:
... | [
"The problem was solved - it was in .pyc files, which are recreating only after apache is restarted. That's why the right code in .py files didn't work.\n"
] | [
0
] | [] | [] | [
"django",
"django_mptt",
"python"
] | stackoverflow_0003337565_django_django_mptt_python.txt |
Q:
I want one backslash - not two
I have a string that after print is like this: \x4d\xff\xfd\x00\x02\x8f\x0e\x80\x66\x48\x71
But I want to change this string to "\x4d\xff\xfd\x00\x02\x8f\x0e\x80\x66\x48\x71" which is not printable (it is necessary to write to serial port). I know that it ist problem with '\'. how ca... | I want one backslash - not two | I have a string that after print is like this: \x4d\xff\xfd\x00\x02\x8f\x0e\x80\x66\x48\x71
But I want to change this string to "\x4d\xff\xfd\x00\x02\x8f\x0e\x80\x66\x48\x71" which is not printable (it is necessary to write to serial port). I know that it ist problem with '\'. how can I replace this printable backslash... | [
"If you want to decode your string, use decode() with 'string_escape' as parameter which will interpret the literals in your variable as python literal string (as if it were typed as constant string in your code).\nmystr.decode('string_escape')\n\n",
"Use decode():\n>>> st = r'\\x4d\\xff\\xfd\\x00\\x02\\x8f\\x0e\... | [
5,
2,
1,
1
] | [] | [] | [
"backslash",
"python",
"string"
] | stackoverflow_0003342681_backslash_python_string.txt |
Q:
urllib and proxies
I need in using Tor+Privoxy with my python-script.
proxies = {
'http' : '127.0.0.1:8118',
'ssl' : '127.0.0.1:8118',
'socks' : '127.0.0.1:9050'
}
The first question: is the 'socks' name right? Maybe there should be something like 'socks5'?
The next step is that I should pass user... | urllib and proxies | I need in using Tor+Privoxy with my python-script.
proxies = {
'http' : '127.0.0.1:8118',
'ssl' : '127.0.0.1:8118',
'socks' : '127.0.0.1:9050'
}
The first question: is the 'socks' name right? Maybe there should be something like 'socks5'?
The next step is that I should pass user-agent string with this ... | [
"not sure whether urllib is able to deal with socks proxy..\nyou may try socksipy\n",
"I suggest you use urllib2 instead. This post might be useful.\nhope it helps\n"
] | [
0,
0
] | [] | [] | [
"header",
"proxy",
"python",
"urllib"
] | stackoverflow_0002829919_header_proxy_python_urllib.txt |
Q:
lxml version problem - unable to call fndall method !
lxml gives following error on version 1.3 for the below line..
self.doc.findall('.//field[@on_change]')
File "/home/.../code_generator/xmlGenerator.py", line 158, in processOnChange
onchangeNodes = self.doc.findall('.//field[@on_change]')
File "etree.pyx", lin... | lxml version problem - unable to call fndall method ! | lxml gives following error on version 1.3 for the below line..
self.doc.findall('.//field[@on_change]')
File "/home/.../code_generator/xmlGenerator.py", line 158, in processOnChange
onchangeNodes = self.doc.findall('.//field[@on_change]')
File "etree.pyx", line 1042, in etree._Element.findall
File "/usr/lib/python2.5... | [
"Predicates in ElementPath expressions were only added in a later version. The original (c)ElementTree module (included in stdlib) has this only as of version 1.3 (in stdlib python 2.7). Lxml started using ElementTree 1.3 compatible expressions from version 2.0 on I think (when ElementTree 1.3 was still alpha)\nThe... | [
3
] | [] | [] | [
"lxml",
"python"
] | stackoverflow_0003342942_lxml_python.txt |
Q:
Does XML-RPC in general allows to call few functions at once?
Can I ask for few question in one post to XML-RPC server?
If yes, how can I do it in python and xmlrpclib?
I'm using XML-RPC server on slow connection, so I would like to call few functions at once, because each call costs me 700ms.
A:
http://docs.pyt... | Does XML-RPC in general allows to call few functions at once? | Can I ask for few question in one post to XML-RPC server?
If yes, how can I do it in python and xmlrpclib?
I'm using XML-RPC server on slow connection, so I would like to call few functions at once, because each call costs me 700ms.
| [
"http://docs.python.org/library/xmlrpclib.html#multicall-objects\n",
"Whether or not possible support of multicall makes any difference to you depends on where the 700ms is going.\nHow did you measure your 700ms?\nRun a packet capture of a query and analyse the results. It should be possible to infer roughly roun... | [
0,
0
] | [] | [] | [
"python",
"soap",
"xml_rpc",
"xmlrpclib"
] | stackoverflow_0003343082_python_soap_xml_rpc_xmlrpclib.txt |
Q:
Django comment moderation error: AlreadyModerated at /
I'm trying to add the comments framework to a weblog I'm creating in Django. Adding the comments system appears to be working fine until I attempt to enable comment moderation.
I add the following code to my models.py as per the instructions on the above link.... | Django comment moderation error: AlreadyModerated at / | I'm trying to add the comments framework to a weblog I'm creating in Django. Adding the comments system appears to be working fine until I attempt to enable comment moderation.
I add the following code to my models.py as per the instructions on the above link. My model is called Post which represents a post in the webl... | [
"Just had a similar problem today, but I think I've solved it :)\nIn my case the issue was that django was loading models.py twice and therefore trying to register the model for comment moderation twice as well. I fixed this by modifying the code from:\nmoderator.register(Post, PostModerator)\n\nto:\nif Post not in... | [
8,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003277474_django_python.txt |
Q:
Django: construct form without validating fields?
I have a form MyForm which I update using ajax as the user fills it out. I have a view method which updates the form by constructing a MyForm from request.POST and feeding it back.
def update_form(request):
if request.method == 'POST':
dict = {}
... | Django: construct form without validating fields? | I have a form MyForm which I update using ajax as the user fills it out. I have a view method which updates the form by constructing a MyForm from request.POST and feeding it back.
def update_form(request):
if request.method == 'POST':
dict = {}
dict['form'] = MyForm(request.POST).as_p()
re... | [
"Validation never invokes until you call form.is_valid().\nBut as i am guessing, you want your form filled with data user types in, until user clicks submit.\ndef update_form(request):\n if request.method == 'POST':\n if not request.POST.get('submit'):\n dict = {}\n dict['form'] = My... | [
3
] | [] | [] | [
"django",
"django_forms",
"forms",
"python",
"validation"
] | stackoverflow_0003343723_django_django_forms_forms_python_validation.txt |
Q:
Sqlite db, multiple row updates: handling text and floats
I have a large SQLite database with a mix of text and lots of other columns var1 ... var 50. Most of these are numeric, though some are text based.
I am trying to extract data from the database, process it in python and write it back - I need to do this for... | Sqlite db, multiple row updates: handling text and floats | I have a large SQLite database with a mix of text and lots of other columns var1 ... var 50. Most of these are numeric, though some are text based.
I am trying to extract data from the database, process it in python and write it back - I need to do this for all rows in the db.
So far, the below sort of works:
# get row... | [
"As others have stressed, use parametrized arguments. Here is an example of how you might construct the SQL statement when it has a variable number of keys:\nsql=('UPDATE results SET '\n + ', '.join(key+' = ?' for key in keys)\n + 'WHERE id = ?')\nargs = [results[key] for key in keys] + [id]\ncur.execute(sq... | [
3,
1,
0
] | [] | [] | [
"python",
"sql",
"sqlite"
] | stackoverflow_0003343565_python_sql_sqlite.txt |
Q:
Merging two datasets in Python efficiently
What would anyone consider the most efficient way to merge two datasets using Python?
A little background - this code will take 100K+ records in the following format:
{user: aUser, transaction: UsersTransactionNumber}, ...
and using the following data
{transaction: aTran... | Merging two datasets in Python efficiently | What would anyone consider the most efficient way to merge two datasets using Python?
A little background - this code will take 100K+ records in the following format:
{user: aUser, transaction: UsersTransactionNumber}, ...
and using the following data
{transaction: aTransactionNumber, activationNumber: assoiciatedActi... | [
"Here's a radical approach.\nDon't.\nYou have two CSV files; one (users) is clearly the driver. Leave this alone.\nThe other -- transaction codes for a user -- can be turned into a simple dictionary.\nDon't \"combine\" or \"join\" anything except when absolutely necessary. Certainly don't \"merge\" or \"pre-join\... | [
6,
1,
1,
0
] | [] | [] | [
"data_structures",
"performance",
"python"
] | stackoverflow_0003343768_data_structures_performance_python.txt |
Q:
Python package for Microsoft Active Accessibility library?
Is there a package for Microsoft Active Accessibility library other than
http://pypi.python.org/pypi/pyAA/2.0
which seems to have been abandoned (I can't seem to get the source code from sourceforge )and does not support Python 2.6.
Thanks.
A:
I hate to... | Python package for Microsoft Active Accessibility library? | Is there a package for Microsoft Active Accessibility library other than
http://pypi.python.org/pypi/pyAA/2.0
which seems to have been abandoned (I can't seem to get the source code from sourceforge )and does not support Python 2.6.
Thanks.
| [
"I hate to answer my own question, but here it is for those who are interested:\nja.nishimotz.com/pyaa \nis what I was looking for.\n",
"Since MSAA is, I believe, COM-based, you could just use pywin32's general purpose Python-to-COM interface to access anything in that package. Could you please explain why this ... | [
1,
0
] | [] | [] | [
"accessibility",
"automation",
"python",
"windows"
] | stackoverflow_0003313843_accessibility_automation_python_windows.txt |
Q:
Django - complex forms with multiple models
Django 1.1
models.py:
class Property(models.Model):
name = models.CharField()
addr = models.CharField()
phone = models.CharField()
etc....
class PropertyComment(models.Model):
user = models.ForeignKey(User)
prop = models.ForeignKey(Property)
... | Django - complex forms with multiple models | Django 1.1
models.py:
class Property(models.Model):
name = models.CharField()
addr = models.CharField()
phone = models.CharField()
etc....
class PropertyComment(models.Model):
user = models.ForeignKey(User)
prop = models.ForeignKey(Property)
text = models.TextField()
etc...
I have a fo... | [
"Have you thought about using the comment framework:\nhttp://docs.djangoproject.com/en/dev/ref/contrib/comments/\nIf that doesnt work for you then maybe look into inlineformset_factory:\nhttp://docs.djangoproject.com/en/dev/topics/forms/modelforms/#inline-formsets\nfrom django.forms.models import inlineformset_fact... | [
2
] | [] | [] | [
"django",
"django_forms",
"python"
] | stackoverflow_0003343747_django_django_forms_python.txt |
Q:
Why does the istitle() string method return false if the string is clearly in title-case?
Of the istitle() string method, the Python 2.6.5 manual reads:
Return true if the string is a titlecased string and there is at least one character, for example uppercase characters may only follow uncased characters and low... | Why does the istitle() string method return false if the string is clearly in title-case? | Of the istitle() string method, the Python 2.6.5 manual reads:
Return true if the string is a titlecased string and there is at least one character, for example uppercase characters may only follow uncased characters and lowercase characters only cased ones. Return false otherwise.
But in this case it returns false:
... | [
"book.title() does not change the variable book. It just returns the string in title case.\n>>> book.title()\n'What Every Programmer Must Know'\n>>> book # still not in title case\n'what every programmer must know'\n>>> book.istitle() # hence it returns False.\nFalse\n>>> book.title().istitle() # re... | [
8,
7,
3,
1
] | [] | [] | [
"python",
"string"
] | stackoverflow_0003344218_python_string.txt |
Q:
How can I use decorators in Python to specify and document repeated used arguments of methods?
One of my classes has a logical numpy array as parameter in many methods repeated (idx_vector=None).
How can I use a decorator to:
automatically specify idx_vector
automatically insert the description into the docstring... | How can I use decorators in Python to specify and document repeated used arguments of methods? | One of my classes has a logical numpy array as parameter in many methods repeated (idx_vector=None).
How can I use a decorator to:
automatically specify idx_vector
automatically insert the description into the docstring
Example without decorator:
import numpy as np
class myarray(object):
def __init__(self, data):
... | [
"I'm not sure I understand you correctly. As I see it, your problem is that you have a lot of functions which all need to take the argument idx_vector, and you don't want to add it to each of their argument lists. If that's the case:\nShort answer: you can't.\nLonger answer: well, you could, but the function needs ... | [
2,
2,
1
] | [] | [] | [
"decorator",
"python"
] | stackoverflow_0003341752_decorator_python.txt |
Q:
Templates in different directory
I want to place the project hierarchy in this way
project
|-app
| \app1
| |-templates
| \app1_templ.html
| |- views.py
| \-models.py
|-templates
| \main.html
|-views.py
|-models.py
...
But in the main.html i want to use `{%include app1_templ... | Templates in different directory | I want to place the project hierarchy in this way
project
|-app
| \app1
| |-templates
| \app1_templ.html
| |- views.py
| \-models.py
|-templates
| \main.html
|-views.py
|-models.py
...
But in the main.html i want to use `{%include app1_templ.html%}. Assuming the views.py from th... | [
"Try passing in the context_instance:\nreturn render_to_response('main.html', {'a': info}, context_instance=RequestContext(request))\n\n"
] | [
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003337615_django_python.txt |
Q:
Hiding the time in a datetime model field in Django?
I'm using Thauber's lovely Django schedule app, but have run into a problem: I can't figure out how to exclude the time portion of the datetime field.
My form class and lame exclusion attempt looks like this:
class LaundryDeliveryForm(EventForm):
start = fo... | Hiding the time in a datetime model field in Django? | I'm using Thauber's lovely Django schedule app, but have run into a problem: I can't figure out how to exclude the time portion of the datetime field.
My form class and lame exclusion attempt looks like this:
class LaundryDeliveryForm(EventForm):
start = forms.DateTimeField(widget=forms.SplitDateTimeWidget)
en... | [
"You can use, DateInput widget as widget for current form, or forms.DateField(), which has default DateInput widget.\n"
] | [
3
] | [] | [] | [
"datetime",
"django",
"python",
"schedule"
] | stackoverflow_0003344630_datetime_django_python_schedule.txt |
Q:
sqlalchemy in a single python script file
I've read about using sqlalchemywithin the pylons framework.
How will things work if I need it for a simple script file?
I have like importer.py that is spidering a site and I want to save to mysql.
If things are in a single file, can I still using sqlalchemy?
How do I s... | sqlalchemy in a single python script file | I've read about using sqlalchemywithin the pylons framework.
How will things work if I need it for a simple script file?
I have like importer.py that is spidering a site and I want to save to mysql.
If things are in a single file, can I still using sqlalchemy?
How do I setup my model/mappings then?
| [
"\nIf things are in a single file, can I still using sqlalchemy? \n\nYes, SQLAlchemy does not impose any restrictions on the way you use it. \nYou can see example on single-script initialization here: http://www.sqlalchemy.org/trac/attachment/ticket/1328/sqlalchemy-bug-query_Employee_company.py\n"
] | [
3
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0003344607_python_sqlalchemy.txt |
Q:
Python - When Is It Ok to Use os.system() to issue common Linux commands
Spinning off from another thread, when is it appropriate to use os.system() to issue commands like rm -rf, cd, make, xterm, ls ?
Considering there are analog versions of the above commands (except make and xterm), I'm assuming it's safer to u... | Python - When Is It Ok to Use os.system() to issue common Linux commands | Spinning off from another thread, when is it appropriate to use os.system() to issue commands like rm -rf, cd, make, xterm, ls ?
Considering there are analog versions of the above commands (except make and xterm), I'm assuming it's safer to use these built-in python commands instead of using os.system()
Any thoughts? I... | [
"Rule of thumb: if there's a built-in Python function to achieve this functionality use this function. Why? It makes your code portable across different systems, more secure and probably faster as there will be no need to spawn an additional process.\n",
"One of the problems with system() is that it implies knowl... | [
19,
5,
4,
3,
3,
2,
1
] | [] | [] | [
"centos",
"linux",
"python"
] | stackoverflow_0003338616_centos_linux_python.txt |
Q:
Splitting a string separated by "\r\n" into a list of lines?
I am reading in some data from the subprocess module's communicate method. It is coming in as a large string separated by "\r\n"s. I want to split this into a list of lines. How is this performed in python?
A:
Use the splitlines method on the string... | Splitting a string separated by "\r\n" into a list of lines? | I am reading in some data from the subprocess module's communicate method. It is coming in as a large string separated by "\r\n"s. I want to split this into a list of lines. How is this performed in python?
| [
"Use the splitlines method on the string.\nFrom the docs:\n\nstr.splitlines([keepends])\n Return a list of the lines in the string, breaking at line boundaries.\n Line breaks are not included in the\n resulting list unless keepends is\n given and true.\n\nThis will do the right thing whether the line ending... | [
56,
2,
1
] | [] | [] | [
"python",
"string"
] | stackoverflow_0003345030_python_string.txt |
Q:
Dynamically update wxPython staticText
i was wondering how to update a StaticText dynamically in wxpython?
I have a script that goes every five minutes and reads a status from a webpage, then prints using wxpython the status in a static input.
How would i dynamically, every 5 minutes update the statictext to refle... | Dynamically update wxPython staticText | i was wondering how to update a StaticText dynamically in wxpython?
I have a script that goes every five minutes and reads a status from a webpage, then prints using wxpython the status in a static input.
How would i dynamically, every 5 minutes update the statictext to reflect the status?
thanks alot
-soule
| [
"Use a wx.Timer. You bind the timer to an event and in the event handler you call the StaticText control's SetLabel.\nSee the following page for an example on timers:\nhttp://www.blog.pythonlibrary.org/2009/08/25/wxpython-using-wx-timers/\nAs for setting the label, the code would look something like this:\nself.myS... | [
11,
1
] | [] | [] | [
"python",
"refresh",
"wxpython"
] | stackoverflow_0003339263_python_refresh_wxpython.txt |
Q:
I'm trying to make a wx.Frame with variable transparancy (based on the png mapped in the erase bk event)
I'm trying to make a special splash screen that is displayed while the application is loading,
it outputs messages of the various components loading and features a progress bar.
The first job I am tackling is m... | I'm trying to make a wx.Frame with variable transparancy (based on the png mapped in the erase bk event) | I'm trying to make a special splash screen that is displayed while the application is loading,
it outputs messages of the various components loading and features a progress bar.
The first job I am tackling is mapping a .png image to the frame that will host the splash screen.
import wx
class edSplash(wx.Frame):
... | [
"Maybe you should try putting the background image onto a panel rather than the frame. Here's one way to do it:\nhttp://www.blog.pythonlibrary.org/2010/03/18/wxpython-putting-a-background-image-on-a-panel/\n"
] | [
1
] | [] | [] | [
"python",
"wxpython",
"wxwidgets"
] | stackoverflow_0003343095_python_wxpython_wxwidgets.txt |
Q:
What are the existing open-source Python WxWidgets designers?
What are the usable tools?
I am aware of wxformbuilder and wxGlade, but none of them seems to be complete yet.
A:
Here are a few of the most popular wxPython related GUI builders:
Boa Constructor (mostly dead)
wxGlade
wxFormBuilder
XRCed
wxDesigne... | What are the existing open-source Python WxWidgets designers? | What are the usable tools?
I am aware of wxformbuilder and wxGlade, but none of them seems to be complete yet.
| [
"Here are a few of the most popular wxPython related GUI builders:\n\nBoa Constructor (mostly dead) \nwxGlade\nwxFormBuilder \nXRCed \nwxDesigner (not FOSS)\nDabo - one of their videos shows a way to interactively design an app...\n\nI personally just use a Python IDE to hand code my applications. My current favori... | [
2,
1,
1
] | [] | [] | [
"python",
"wxpython",
"wxwidgets"
] | stackoverflow_0003329762_python_wxpython_wxwidgets.txt |
Q:
Python: drawbacks to using `signal.alert` to timeout I/O?
What are the disadvantages to using signal.alert to timeout Python I/O?
I ask because I have found that socket.settimeout isn't entirely reliable[0] and I'd like finer control over the timeouts for different operations[1].
So, as far as I can tell, the draw... | Python: drawbacks to using `signal.alert` to timeout I/O? | What are the disadvantages to using signal.alert to timeout Python I/O?
I ask because I have found that socket.settimeout isn't entirely reliable[0] and I'd like finer control over the timeouts for different operations[1].
So, as far as I can tell, the drawbacks are:
Added signal call overhead (but if you're doing I/O... | [
"You will likely not get far when using signals and threads together. From the signal documentation:\n\n...\n only the main thread can set a new\n signal handler, and the main thread\n will be the only one to receive\n signals (this is enforced by the\n Python signal module, even if the\n underlying thread i... | [
2
] | [] | [] | [
"python",
"timeout"
] | stackoverflow_0003345519_python_timeout.txt |
Q:
Python: Deleting files of a certain age
So at the moment I'm trying to delete files listed in the directory that are 1 minute old, I will change that value once I have the script working.
The code below returns the error: AttributeError: 'str' object has no attribute 'mtime'
import time
import os
#from path impor... | Python: Deleting files of a certain age | So at the moment I'm trying to delete files listed in the directory that are 1 minute old, I will change that value once I have the script working.
The code below returns the error: AttributeError: 'str' object has no attribute 'mtime'
import time
import os
#from path import path
seven_days_ago = time.time() - 60
fol... | [
"import time\nimport os\n\none_minute_ago = time.time() - 60 \nfolder = '/home/rv/Desktop/test'\nos.chdir(folder)\nfor somefile in os.listdir('.'):\n st=os.stat(somefile)\n mtime=st.st_mtime\n if mtime < one_minute_ago:\n print('remove %s'%somefile)\n # os.unlink(somefile) # uncomment only if... | [
13,
7
] | [] | [] | [
"python"
] | stackoverflow_0003345953_python.txt |
Q:
Efficient way of adding one character at a time from one string to another in Python
I'm currently making a function using pygame that draws a message on the screen, adding one character each frame (i.e. The Hunt for Red October). I know that I could simply copy (or pass) gradually bigger slices from the original... | Efficient way of adding one character at a time from one string to another in Python | I'm currently making a function using pygame that draws a message on the screen, adding one character each frame (i.e. The Hunt for Red October). I know that I could simply copy (or pass) gradually bigger slices from the original string, but I know that it would be very resource-intensive. Is there a better way to do... | [
"In a place where you are intentionally slowing down the game (for the text fade-in) - does it really matter? You could pass the whole string, and change the display routine to display one more letter in every frame.\n",
"Can't you just print the characters one at a time displaced without clearing the background?... | [
4,
1,
1
] | [
"You can access a single character from a string using indexes:\n>>> s = 'string'\n>>> s[2]\n'r'\n\n"
] | [
-2
] | [
"processing_efficiency",
"python",
"string"
] | stackoverflow_0003346005_processing_efficiency_python_string.txt |
Q:
Why is it not safe to modify sequence being iterated on?
It is not safe to modify the sequence being iterated over in the loop (this can only happen for mutable sequence types, such as lists). If you need to modify the list you are iterating over (for example, to duplicate selected items) you must iterate over a c... | Why is it not safe to modify sequence being iterated on? |
It is not safe to modify the sequence being iterated over in the loop (this can only happen for mutable sequence types, such as lists). If you need to modify the list you are iterating over (for example, to duplicate selected items) you must iterate over a copy. The slice notation makes this particularly convenient:
... | [
"Without getting too technical:\nIf you're iterating through a mutable sequence in Python and the sequence is changed while it's being iterated through, it is not always entirely clear what will happen. If you insert an element in the sequence while iterating through it, what would now reasonably be considered the ... | [
17,
13,
3
] | [] | [] | [
"python"
] | stackoverflow_0003346696_python.txt |
Q:
PYTHONPATH hell with overlapping package structures
I'm having problems with my PythonPath on windows XP, and I'm wondering if I'm doing something wrong.
Say that I have a project (created with Pydev) that has an src directory. Under src I have a single package, named common, and in it a single class module, named... | PYTHONPATH hell with overlapping package structures | I'm having problems with my PythonPath on windows XP, and I'm wondering if I'm doing something wrong.
Say that I have a project (created with Pydev) that has an src directory. Under src I have a single package, named common, and in it a single class module, named service.py with a class name Service
Say now that I have... | [
"If you really must have a split package like this, read up on the module level attribute __path__.\nIn short, make one of the 'src' directories the main one, and give it an __init__.py that appends the path of other 'src' to the __path__ list. Python will now look in both places when looking up submodules of 'src'... | [
2,
1,
1
] | [] | [] | [
"python",
"pythonpath"
] | stackoverflow_0003346482_python_pythonpath.txt |
Q:
Python Base64 print problem
I have a base64 encoded string
When I decode the string this way:
>>> import base64
>>> base64.b64decode("XH13fXM=")
'\\}w}s'
The output is fine.
But when i use it like this:
>>> d = base64.b64decode("XH13fXM=")
>>> print d
\}w}s
some characters are missing
Can anyone advise ?
Thank... | Python Base64 print problem | I have a base64 encoded string
When I decode the string this way:
>>> import base64
>>> base64.b64decode("XH13fXM=")
'\\}w}s'
The output is fine.
But when i use it like this:
>>> d = base64.b64decode("XH13fXM=")
>>> print d
\}w}s
some characters are missing
Can anyone advise ?
Thank you in advanced.
| [
"It is just a matter of presentation:\n>>> '\\\\}w}s'\n'\\\\}w}s'\n>>> print(_, len(_))\n\\}w}s 5\n\nThis string has 5 characters. When you use it in code you need to escape backslash, or use raw string literals:\n>>> r'\\}w}s'\n'\\\\}w}s'\n>>> r'\\}w}s' == '\\\\}w}s'\nTrue\n\n",
"When you print a string, the cha... | [
3,
1
] | [] | [] | [
"python",
"string"
] | stackoverflow_0003346824_python_string.txt |
Q:
Set custom 'name' attribute for RadioSelect in Django
I'm trying to set custom 'name' attribute in django form.
I've been trying this kind of approach:
class BaseQuestionForm(forms.Form):
question_id = forms.CharField(widget=forms.HiddenInput)
answer = forms.ChoiceField(choices = [ ... ], widget=forms.RadioSel... | Set custom 'name' attribute for RadioSelect in Django | I'm trying to set custom 'name' attribute in django form.
I've been trying this kind of approach:
class BaseQuestionForm(forms.Form):
question_id = forms.CharField(widget=forms.HiddenInput)
answer = forms.ChoiceField(choices = [ ... ], widget=forms.RadioSelect)
and then setting the 'name'-attr on answer with:
form... | [
"First try:\nprint form.fields['answer'].widget.name\n\nI believe widget doesn't have a name (ok, I am even pretty sure ;-)).\nTo achieve what you want, you would have to:\nform.fields['new_name'] = form.fields['answer']\ndel form.fields['answer']\n\nThis however will move new_name field to the bottom of fields if ... | [
1
] | [] | [] | [
"django",
"django_forms",
"python"
] | stackoverflow_0003346373_django_django_forms_python.txt |
Q:
Geopy in Django: JSONDecodeError
I have followed the tutorials in http://code.google.com/p/geopy/wiki/GettingStarted
This works fine:
g = geocoders.Google(resource='maps')
I want to use json as the output format because I want to handle the results in javascript.
BUT everytime I use:
g = geocoders.Google(resourc... | Geopy in Django: JSONDecodeError | I have followed the tutorials in http://code.google.com/p/geopy/wiki/GettingStarted
This works fine:
g = geocoders.Google(resource='maps')
I want to use json as the output format because I want to handle the results in javascript.
BUT everytime I use:
g = geocoders.Google(resource='maps', output_format='json')
I get... | [
"Did you read the comments on the geopy page?\n\nComment by gregor.horvath, Sep 11,\n 2009\nBe aware that although there are\n different output_format parameters for\n the geocoders, the actual output\n format of the geocode function is\n always the same:\nlocation, (latttude, longitude)\nThe output_format re... | [
0
] | [] | [] | [
"django",
"geopy",
"python",
"simplejson"
] | stackoverflow_0003344747_django_geopy_python_simplejson.txt |
Q:
Can a process running a 32-bit compiled binary use more than 4GB of memory?
Is it possible for a single process running a 32-bit compiled version of python in Snow Leopard (64-bit machine) to appear to consume > 4GB (say 5.4GB) of virtual memory as seen by the top command?
I did a file ...python to see that the bi... | Can a process running a 32-bit compiled binary use more than 4GB of memory? | Is it possible for a single process running a 32-bit compiled version of python in Snow Leopard (64-bit machine) to appear to consume > 4GB (say 5.4GB) of virtual memory as seen by the top command?
I did a file ...python to see that the binary was not x86, yet it appeared to be consuming over 5GB of memory.
My guess i... | [
"No, it's physically impossible. That doesn't stop the OS assigning more than it can use due to alignment and fragmentation, say, it could have a whole page and not actually map in all of it. However it's impossible to actually use over 4GB for any process, and most likely substantially less than that for kernel sp... | [
2,
1
] | [] | [] | [
"i386",
"memory_management",
"osx_snow_leopard",
"python",
"x86_64"
] | stackoverflow_0003330643_i386_memory_management_osx_snow_leopard_python_x86_64.txt |
Q:
How can one use the logging module in python with the unittest module?
I would like to use the python logging module to log all of the output from unittest so that I can incorporate it into a testing framework I am trying to write. The goal of this is to run the tests with 2 sets of output, one with simple output... | How can one use the logging module in python with the unittest module? | I would like to use the python logging module to log all of the output from unittest so that I can incorporate it into a testing framework I am trying to write. The goal of this is to run the tests with 2 sets of output, one with simple output that tells the test case steps and a more debug level output so that when t... | [
"You could, but I'm not sure it's your best approach.\nFor this approach, you would:\n\nInstantiate an in-memory stream that can be used by TextTestRunner. This is the sort of thing io.StringIO would be nearly perfect for, except that it works with Unicode input only, and I'm not sure that TextTestRunner writes Uni... | [
1
] | [] | [] | [
"logging",
"python",
"unit_testing"
] | stackoverflow_0003347019_logging_python_unit_testing.txt |
Q:
python -- for with an if statement
I dont understand why, when i run my code the for each loop under the if statement isn't run. Even when the number of found is greater than 0!
def findpattern(commit_msg):
pattern = re.compile("\w\w*-\d\d*")
group = pattern.finditer(commit_msg)
found = getIterLength(... | python -- for with an if statement | I dont understand why, when i run my code the for each loop under the if statement isn't run. Even when the number of found is greater than 0!
def findpattern(commit_msg):
pattern = re.compile("\w\w*-\d\d*")
group = pattern.finditer(commit_msg)
found = getIterLength(group)
print found
if found > 0:... | [
"Your getIterLength() function is finding the length by exhausting the iterator returned by finditer(). You would then need a new iterator instance for the for loop. Instead, I would restructure your code like this:\ndef findpattern(commit_msg):\n pattern = re.compile(\"\\w\\w*-\\d\\d*\")\n group = pattern.... | [
8,
1
] | [] | [] | [
"jira",
"python"
] | stackoverflow_0003347693_jira_python.txt |
Q:
Using urllib2 for posting data, following redirects and maintaining cookies
I am using urllib2 in Python to post login data to a web site.
After successful login, the site redirects my request to another page. Can someone provide a simple code sample on how to do this in Python with urllib2? I guess I will need co... | Using urllib2 for posting data, following redirects and maintaining cookies | I am using urllib2 in Python to post login data to a web site.
After successful login, the site redirects my request to another page. Can someone provide a simple code sample on how to do this in Python with urllib2? I guess I will need cookies also to be logged in when I get redirected to another page. Right?
Thanks a... | [
"First, get mechanize: http://wwwsearch.sourceforge.net/mechanize/\nYou could do this kind of stuff with just urllib2, but you will be writing tons of boilerplate code, and it will be buggy.\nThen:\nimport mechanize\n\nbr = mechanize.Browser()\nbr.open('http://somesite.com/account/signin/')\n\nbr.select_form('login... | [
6
] | [] | [] | [
"python",
"urllib2"
] | stackoverflow_0003346960_python_urllib2.txt |
Q:
script as module and executable
I have a script in python that can be invoked from the command-line and uses optparse.
script -i arg1 -j arg2
In this case I use (options, args) = parser.parse_args() to create options then use options.arg1 to get arguments.
But I also want it to be importable as a module.
from scr... | script as module and executable |
I have a script in python that can be invoked from the command-line and uses optparse.
script -i arg1 -j arg2
In this case I use (options, args) = parser.parse_args() to create options then use options.arg1 to get arguments.
But I also want it to be importable as a module.
from script import *
function(arg1=arg1, arg... | [
"Separate the CLI from the workhorse class:\nclass Main(object):\n def __init__(self,arg1,arg2):\n ...\n def run(self):\n pass\n\nif __name__=='__main__':\n import optparse\n class CLI(object):\n def parse_options(self):\n usage = 'usage: %prog [options]'+__usage__\n ... | [
6,
2
] | [] | [] | [
"python"
] | stackoverflow_0003348041_python.txt |
Q:
Common pitfalls in Python
Today I was bitten again by mutable default arguments after many years. I usually don't use mutable default arguments unless needed, but I think with time I forgot about that. Today in the application I added tocElements=[] in a PDF generation function's argument list and now "Table of C... | Common pitfalls in Python | Today I was bitten again by mutable default arguments after many years. I usually don't use mutable default arguments unless needed, but I think with time I forgot about that. Today in the application I added tocElements=[] in a PDF generation function's argument list and now "Table of Contents" gets longer and longer... | [
"Don't use index to loop over a sequence\nDon't :\nfor i in range(len(tab)) :\n print tab[i]\n\nDo :\nfor elem in tab :\n print elem\n\nFor will automate most iteration operations for you.\nUse enumerate if you really need both the index and the element.\nfor i, elem in enumerate(tab):\n print i, elem\n\n... | [
73,
39,
28,
27,
22,
18,
15,
14,
14,
13,
10,
9,
8,
8,
7,
6,
6,
5,
5,
5,
4,
4,
3,
3,
3,
3,
3,
3,
1,
1,
0,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0001011431_python.txt |
Q:
py2exe on PIL ImageStat.Stat throws Exception: argument 2 must be ImagingCore, not ImagingCore
I'm trying to create a .exe from a python program using py2exe, but when I run the .exe I get a log file with
Exception in thread Thread-1:
Traceback (most recent call last):
File "threading.pyc", line 532, in __bootst... | py2exe on PIL ImageStat.Stat throws Exception: argument 2 must be ImagingCore, not ImagingCore | I'm trying to create a .exe from a python program using py2exe, but when I run the .exe I get a log file with
Exception in thread Thread-1:
Traceback (most recent call last):
File "threading.pyc", line 532, in __bootstrap_inner
File "threading.pyc", line 484, in run
File "webcam.py", line 66, in loop
File "Imag... | [
"Try importing PIL in your main thread before starting any worker threads. It looks like the same class has been imported twice, and type comparisons are acting wacky as a result.\n"
] | [
0
] | [] | [] | [
"py2exe",
"python",
"python_imaging_library"
] | stackoverflow_0003348079_py2exe_python_python_imaging_library.txt |
Q:
python: inserting a whole line into a list
import csv
with open('thefile.csv', 'rb') as f:
data = list(csv.reader(f))
import collections
counter = collections.defaultdict(int)
for row in data:
counter[row[10]] += 1
with open('/pythonwork/thefile_subset11.csv', 'w') as outfile:
writer = csv.w... | python: inserting a whole line into a list | import csv
with open('thefile.csv', 'rb') as f:
data = list(csv.reader(f))
import collections
counter = collections.defaultdict(int)
for row in data:
counter[row[10]] += 1
with open('/pythonwork/thefile_subset11.csv', 'w') as outfile:
writer = csv.writer(outfile)
sample_cutoff=500
b[]
... | [
"It's b.append(row), but otherwise yes. And instead of b[] you want b = []. Another way to do it would be to make the list first, and then just write each element of the list to the file:\nb = [row for row in data if counter[row[10]] >= sample_cutoff]\nmap(writer.writerow, b)\n\n",
"It's list.insert(index, item) ... | [
2,
1,
1
] | [] | [] | [
"csv",
"python"
] | stackoverflow_0003348577_csv_python.txt |
Q:
How to write a JIT library?
I've browsed through many JIT libraries. But I'd like to learn how to write one.
Softwire looked like nice. Though what the emitter interface should do? Can I do something better than existing libraries? How do I support inline caching?
A:
I would recommend you join an existing team i... | How to write a JIT library? | I've browsed through many JIT libraries. But I'd like to learn how to write one.
Softwire looked like nice. Though what the emitter interface should do? Can I do something better than existing libraries? How do I support inline caching?
| [
"I would recommend you join an existing team instead of starting from scratch. The PyPy team's work on this area is very interesting and is currently under development, so may be a good place to start and seek more information, and then perhaps help.\n\nhttp://codespeak.net/pypy/dist/pypy/doc/jit/overview.html\nhtt... | [
4
] | [] | [] | [
"c",
"compiler_construction",
"jit",
"python"
] | stackoverflow_0003292704_c_compiler_construction_jit_python.txt |
Q:
Cleanest way of choosing between two values in Python
Dicts in Python have a very nice method get:
# m is some dict
m.get(k,v) # if m[k] exists, returns that, otherwise returns v
Is there some way to do this for any value? For example, in Perl I could do this:
return $some_var or "some_var doesn't exist."
A:
T... | Cleanest way of choosing between two values in Python | Dicts in Python have a very nice method get:
# m is some dict
m.get(k,v) # if m[k] exists, returns that, otherwise returns v
Is there some way to do this for any value? For example, in Perl I could do this:
return $some_var or "some_var doesn't exist."
| [
"The or operator in Python is guaranteed to return one of its operands, in case the left expression evaluates to False, the right one is evaluated and returned.\nEdit:\nAfter re-reading your question, I noticed that I misunderstood it the first time. By using the locals() built-in function, you can use the get() me... | [
2,
2,
1,
1
] | [] | [] | [
"coding_style",
"perl",
"python"
] | stackoverflow_0003348594_coding_style_perl_python.txt |
Q:
How to make tkinter repond events while waiting socket data?
I'm trying to make the app read data from a socket, but it takes some time and locks the interface, how do I make it respond to tk events while waiting?
A:
Thats is easy! And you don’t even need threads! But you’ll have to restructure your I/O code a b... | How to make tkinter repond events while waiting socket data? | I'm trying to make the app read data from a socket, but it takes some time and locks the interface, how do I make it respond to tk events while waiting?
| [
"Thats is easy! And you don’t even need threads! But you’ll have to restructure your I/O code a bit. Tk has the equivalent of Xt’s XtAddInput() call, which allows you to register a callback function which will be called from the Tk mainloop when I/O is possible on a file descriptor. Here’s what you need:\nfrom Tkin... | [
9
] | [] | [] | [
"event_handling",
"python",
"tkinter"
] | stackoverflow_0003348757_event_handling_python_tkinter.txt |
Q:
Wrong ELF class - Python
I'm trying to install this library for LZJB compression. PyLZJB LINK
The library is a binding for a C library, the file is located here PyLZJB.so
Unfortunately by copying to the site-packages directory when import I get the "Wrong ELF class" error.
>>> import PyLZJB
Traceback (most recent... | Wrong ELF class - Python | I'm trying to install this library for LZJB compression. PyLZJB LINK
The library is a binding for a C library, the file is located here PyLZJB.so
Unfortunately by copying to the site-packages directory when import I get the "Wrong ELF class" error.
>>> import PyLZJB
Traceback (most recent call last):
File "<stdin>",... | [
"You are running a 64 bit Python interpreter and trying to load a 32 bit extension and that is not allowed.\nYou need to have both your Python interpreter and your extension compiled for the same architectures. While you could get a 32 bit Python interpreter, it would probably be better to get a 64 bit extension.\... | [
7,
4,
0
] | [] | [] | [
"compression",
"javascript",
"libraries",
"lzw",
"python"
] | stackoverflow_0003348538_compression_javascript_libraries_lzw_python.txt |
Q:
Efficient way of setting Logging across a Package Module
I have a package that has several components in it that would benefit greatly from using logging and outputting useful information.
What I do not want to do is to 'setup' proper logging for every single file with somewhere along these lines:
import logging
l... | Efficient way of setting Logging across a Package Module | I have a package that has several components in it that would benefit greatly from using logging and outputting useful information.
What I do not want to do is to 'setup' proper logging for every single file with somewhere along these lines:
import logging
logging.basicConfig(level=DEBUG)
my_function = logging.getLogge... | [
"If you want all the code in the various modules of your package to use the same logger object, you just need to (make that logger available -- see later -- and) call\nmylogger.warning(\"Attenzione!\")\n\nor the like, rather than logging.warning &c. So, the problem reduces to making one mylogger object for the who... | [
13,
1
] | [] | [] | [
"logging",
"module",
"package",
"python"
] | stackoverflow_0003348958_logging_module_package_python.txt |
Q:
persistant TCP connection in Django
I have a Django application which sometimes needs to send some data through TCP and I want this connection to be persistant.
The way I wanted to do it was to create a simple Twisted TCP server (I'm the one who will be waiting for the initial connection) and somehow call it from ... | persistant TCP connection in Django | I have a Django application which sometimes needs to send some data through TCP and I want this connection to be persistant.
The way I wanted to do it was to create a simple Twisted TCP server (I'm the one who will be waiting for the initial connection) and somehow call it from a Django view whenever I would be needing... | [
"Use the Twisted wsgi container to run Django. This container simply runs the WSGI application in multiple Twisted-threadpool threads, so you can simply call any Twisted API via blockingCallFromThread. There's really not that much to it!\n"
] | [
4
] | [] | [] | [
"django",
"python",
"tcp",
"twisted"
] | stackoverflow_0003348663_django_python_tcp_twisted.txt |
Q:
Importing Modules (SQLITE3) from Python Virtual Environment
I am using a Windows machine with python, django, and pinax installed.
I can import modules from any normal location (even if it's not in the actuall installed directory). However, I cannot import these same modules when I am in a virtual environment t... | Importing Modules (SQLITE3) from Python Virtual Environment | I am using a Windows machine with python, django, and pinax installed.
I can import modules from any normal location (even if it's not in the actuall installed directory). However, I cannot import these same modules when I am in a virtual environment that I built for Pinax.
What are possible causes of this? What are... | [
"To diagnose failure to import, try using the -v switch to python:\npython -v my_program.py\n\nIt will show its attempts to import your modules.\n",
"As the summary says,\n\n[[virtualenv]] creates an environment\n that has its own installation\n directories, that doesn't share\n libraries with other virtualenv... | [
2,
1
] | [] | [] | [
"django",
"pinax",
"python"
] | stackoverflow_0003349313_django_pinax_python.txt |
Q:
Python - PHP Shared MySQL server connection info?
I have some MySQL database server information that needs to be shared between a Python backend and a PHP frontend.
What is the best way to go about storing the information in a manner wherein it can be read easily by Python and PHP?
I can always brute force it with... | Python - PHP Shared MySQL server connection info? | I have some MySQL database server information that needs to be shared between a Python backend and a PHP frontend.
What is the best way to go about storing the information in a manner wherein it can be read easily by Python and PHP?
I can always brute force it with a bunch of str.replace() calls in Python and hope it w... | [
"Store the shared configuration in a plain text file, preferably in a standard format.\nYou might consider yaml, ini, or json. \nI'm pretty sure both PHP and python can very trivially read and parse all three of those formats.\n"
] | [
4
] | [] | [] | [
"mysql",
"php",
"python",
"share",
"variables"
] | stackoverflow_0003349445_mysql_php_python_share_variables.txt |
Q:
Error when trying make cleaned_data()! Django
Must be simple solution. But I do not see it. Please help me. Looks like 'gorod' is in request but when i trying cleaned_data() it gives me KeyError
KeyError at /ticket/
'gorod'
Request Method: POST
Request URL: http://localhost:8000/ticket/
Exception Type: ... | Error when trying make cleaned_data()! Django | Must be simple solution. But I do not see it. Please help me. Looks like 'gorod' is in request but when i trying cleaned_data() it gives me KeyError
KeyError at /ticket/
'gorod'
Request Method: POST
Request URL: http://localhost:8000/ticket/
Exception Type: KeyError
Exception Value:
'gorod'
Exception... | [
"Maybe your AddressForm class is missing the gorod field? The form populates the .cleaned_data attribute (no () after the latter!-) based on the fields in the form; for example, in the source for the current django.forms, you'll see on line 274\nfor name, field in self.fields.items():\n\nand it's in the body of th... | [
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003347680_django_python.txt |
Q:
How to run GUI2Exe from command line?
I'm using GUI2Exe to CX_freeze my python app, which is working great... if I want to build it manually.
My next step is to automate this build, so I can build in one step
Is there a way to use the exported setup.py to build?
or to call GUI2Exe with some command line parame... | How to run GUI2Exe from command line? | I'm using GUI2Exe to CX_freeze my python app, which is working great... if I want to build it manually.
My next step is to automate this build, so I can build in one step
Is there a way to use the exported setup.py to build?
or to call GUI2Exe with some command line parameters to build the project?
Thanks!
Update:... | [
"As its homepage says, GUI2Exe is just a GUI around different python exe builders, so I guess you should just use your tool of choice directly. As for cx_Freeze, you could find the description of its setup.py options in its manual http://cx-freeze.sourceforge.net/cx_Freeze.html#distutils-setup-script.\n",
"GUI2Ex... | [
1,
1,
0
] | [] | [] | [
"command_line",
"gui2exe",
"python",
"wxpython"
] | stackoverflow_0003315820_command_line_gui2exe_python_wxpython.txt |
Q:
Does the TCPServer + BaseRequestHandler in Python's SocketServer close the socket after each call to handle()?
I'm writing a client/server application in Python and I'm finding it necessary to get a new connection to the server for each request from the client. My server is just inheriting from TCPServer and I'm i... | Does the TCPServer + BaseRequestHandler in Python's SocketServer close the socket after each call to handle()? | I'm writing a client/server application in Python and I'm finding it necessary to get a new connection to the server for each request from the client. My server is just inheriting from TCPServer and I'm inheriting from BaseRequestHandler to do my processing. I'm not calling self.request.close() anywhere in the handler,... | [
"Okay, I read the code (on my Mac, SocketServer.py is at /System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/).\nIndeed, TCPServer is closing the connection. In BaseServer.handle_request, process_request is called, which calls close_request. In the TCPServer class, close_request calls self.reque... | [
9,
7,
6,
0
] | [] | [] | [
"python",
"sockets"
] | stackoverflow_0002066810_python_sockets.txt |
Q:
Duplicate key-value pairs returned by memcached
We are using a cluster of memcached servers for caching purpose, in a Django(Python) production, having tried both cmemcache and python-memcache as the API. The problem is under high concurrency, we started to have duplicate key-value pairs, that is to say we are hav... | Duplicate key-value pairs returned by memcached | We are using a cluster of memcached servers for caching purpose, in a Django(Python) production, having tried both cmemcache and python-memcache as the API. The problem is under high concurrency, we started to have duplicate key-value pairs, that is to say we are having multi values for a single key. Is there anyone ha... | [
"The client is supposed to figure out which memcache server a value lives on based on its key. If you're using two different clients (or two different configurations of the same client) they might be using different algorithms to map a key to a server, thereby sending values for the same key to two different serve... | [
1,
0
] | [] | [] | [
"concurrency",
"memcached",
"python"
] | stackoverflow_0003349614_concurrency_memcached_python.txt |
Q:
How can I replace a Python 2.65 UCS-2 build with one built using UCS-4 without losing everything in my site-packages?
I downloaded the Python 2.6.5 source, built it for OS 10.6.4 64-bit, and installed numerous dependencies. I opened a big project our team has been working on recently, ran the unit tests, and one o... | How can I replace a Python 2.65 UCS-2 build with one built using UCS-4 without losing everything in my site-packages? | I downloaded the Python 2.6.5 source, built it for OS 10.6.4 64-bit, and installed numerous dependencies. I opened a big project our team has been working on recently, ran the unit tests, and one of the tests failed because I had installed Python built using UCS-2 (I didn't know this was the default of OS X!)
In a nuts... | [
"You can save and restore /Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages (e.g. as a .tar.bz2), but the restored .sos will not work properly if any of their entry points deal with Python Unicode objects -- so, those packages (containing any such .so files) you'll have to rebuild/reinst... | [
1
] | [] | [] | [
"macos",
"python",
"python_2.6",
"unicode"
] | stackoverflow_0003349798_macos_python_python_2.6_unicode.txt |
Q:
Python variable assignment order of operations
Is there a way to do a variable assignment inside a function call in python? Something like
curr= []
curr.append(num = num/2)
A:
Nopey. Assignment is a statement. It is not an expression as it is in C derived languages.
A:
I'm pretty certain I remember one of the ... | Python variable assignment order of operations | Is there a way to do a variable assignment inside a function call in python? Something like
curr= []
curr.append(num = num/2)
| [
"Nopey. Assignment is a statement. It is not an expression as it is in C derived languages.\n",
"I'm pretty certain I remember one of the reasons Python was created was to avoid these abominations, instead preferring readability over supposed cleverness :-)\nWhat, pray tell, is wrong with the following?\ncurr= []... | [
8,
4,
0
] | [] | [] | [
"function",
"python",
"variable_assignment"
] | stackoverflow_0003349908_function_python_variable_assignment.txt |
Q:
Substring search in GAE using python?
I have a model which looks like this:
class Search (db.Model) :
word = db.StringProperty()
an example "word" can look like word = "thisisaword"
I want to search all entities in Search for substrings like "this" "isa" etc.
How can i do this in App engine using python?
Update... | Substring search in GAE using python? | I have a model which looks like this:
class Search (db.Model) :
word = db.StringProperty()
an example "word" can look like word = "thisisaword"
I want to search all entities in Search for substrings like "this" "isa" etc.
How can i do this in App engine using python?
Update:
The words here will be domain names. So ... | [
"With no word-separation, I don't think that the task you desire is feasible (it would be in many DB engines by implicitly using no index at all and destroying performance and scalability, but App Engine just doesn't implement \"features\" that inevitably destroy scalability and performance). If you had word separ... | [
6
] | [] | [] | [
"google_app_engine",
"python",
"search",
"string"
] | stackoverflow_0003349868_google_app_engine_python_search_string.txt |
Q:
Python Web Server - Getting it to do other tasks
Using the following example I can get a basic web server running but my problem is that the handle_request() blocks the do_something_else() until a request comes in. Is there any way around this to have the web server do other back ground tasks?
def run_while_true(s... | Python Web Server - Getting it to do other tasks | Using the following example I can get a basic web server running but my problem is that the handle_request() blocks the do_something_else() until a request comes in. Is there any way around this to have the web server do other back ground tasks?
def run_while_true(server_class=BaseHTTPServer.HTTPServer,
... | [
"You can use multiple threads of execution through the Python threading module. An example is below:\nimport threading\n\n# ... your code here...\n\ndef run_while_true(server_class=BaseHTTPServer.HTTPServer,\n handler_class=BaseHTTPServer.BaseHTTPRequestHandler):\n\n server_address = ('', 8000)\n ... | [
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0003346880_python.txt |
Q:
basic python server using spawn/threads
Got a problem that I'm facing. and it should be pretty simple.
I have an app that places data into a dir "A". The data will be a series of files.
I want to have a continually running server, that does a continual look at the dir, and on seeing a completed file in the dir, th... | basic python server using spawn/threads | Got a problem that I'm facing. and it should be pretty simple.
I have an app that places data into a dir "A". The data will be a series of files.
I want to have a continually running server, that does a continual look at the dir, and on seeing a completed file in the dir, the server spawns/forks/creates a thread (not s... | [
"In Python, you should consider using the multiprocessing module instead of threads, especially if you have a multicore machine:\n\nmultiprocessing is a package that supports spawning processes using an API similar to the threading module. The multiprocessing package offers both local and remote concurrency, effect... | [
1
] | [] | [] | [
"fork",
"multithreading",
"python",
"spawn"
] | stackoverflow_0003350286_fork_multithreading_python_spawn.txt |
Q:
On the google app engine, why do updates not reflect in a transaction?
I store groups of entities in the google app engine Data Store with the same ancestor/parent/entityGroup. This is so that the entities can be updated in one atomic datastore transaction.
The problem is as follows:
I start a db transaction
I up... | On the google app engine, why do updates not reflect in a transaction? | I store groups of entities in the google app engine Data Store with the same ancestor/parent/entityGroup. This is so that the entities can be updated in one atomic datastore transaction.
The problem is as follows:
I start a db transaction
I update entityX by setting entityX.flag = True
I save entityX
I query for entit... | [
"App Engine's transactions are designed that way, ie reads within a transaction see a snapshot as of the beginning of the transaction, so they don't see the result of earlier writes within the transaction:\nhttp://code.google.com/appengine/docs/python/datastore/transactions.html#Isolation_and_Consistency\n",
"Loo... | [
4,
0
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0003350068_google_app_engine_python.txt |
Q:
Variables with Subtypes (Struct?) Python
How would one do something like this in python
Mainstring:
Sub1
Sub2
Sub3
then call upon each of those values by defining a Mainstring StringNumberOne
and
StringNumberOne.Sub1 = ""
A:
There is also the named tuple approach:
from collections import namedtup... | Variables with Subtypes (Struct?) Python | How would one do something like this in python
Mainstring:
Sub1
Sub2
Sub3
then call upon each of those values by defining a Mainstring StringNumberOne
and
StringNumberOne.Sub1 = ""
| [
"There is also the named tuple approach:\nfrom collections import namedtuple\n\nMainstring = namedtuple('Mainstring', 'sub1 sub2 sub3')\n\nexample = Mainstring(\"a\", \"b\", \"c\")\nprint example.sub1 # \"a\"\n\n",
"I'm not sure if I understand your question. You can habe a class like this:\nclass ManySubs(objec... | [
4,
2,
2
] | [] | [] | [
"python",
"types"
] | stackoverflow_0003350251_python_types.txt |
Q:
Python string match
If a string contains *SUBJECT123, how do I determine that the string has subject in it in python?
A:
if "subject" in mystring.lower():
# do something
A:
If you want to have subject match SUBJECT, you could use re
import re
if re.search('subject', your_string, re.IGNORECASE)
Or you could... | Python string match | If a string contains *SUBJECT123, how do I determine that the string has subject in it in python?
| [
"if \"subject\" in mystring.lower():\n # do something\n\n",
"If you want to have subject match SUBJECT, you could use re\nimport re\nif re.search('subject', your_string, re.IGNORECASE)\n\nOr you could transform the string to lower case first and simply use:\nif \"subject\" in your_string.lower()\n\n",
"Just an... | [
34,
12,
7,
1
] | [] | [] | [
"python",
"regex",
"string"
] | stackoverflow_0003351218_python_regex_string.txt |
Q:
Iteration in python dictionary
I populate a python dictionary based on few conditions.
My question is:
can we retrieve the dictionary in the same order as it is populated?
questions_dict={}
data = str(header_arr[opt]) + str(row)
questions_dict.update({data : xl_data})
... | Iteration in python dictionary | I populate a python dictionary based on few conditions.
My question is:
can we retrieve the dictionary in the same order as it is populated?
questions_dict={}
data = str(header_arr[opt]) + str(row)
questions_dict.update({data : xl_data})
valid_xl_format = 7
... | [
"To keep track of the order in which a dictionary is populated, you need a type different than dict (commonly known as \"ordered dict\"), such as those from the third-party odict module, or, if you can upgrade to Python 2.7, collections.OrderedDict.\n",
"Dictionaries aren't ordered collections. You have to have s... | [
8,
2,
0
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0003350091_dictionary_python.txt |
Q:
how to create a dynamic sql statement w/ python and mysqldb
I have the following code:
def sql_exec(self, sql_stmt, args = tuple()):
"""
Executes an SQL statement and returns a cursor.
An SQL exception might be raised on error
@return: SQL cursor object
"""
cu... | how to create a dynamic sql statement w/ python and mysqldb | I have the following code:
def sql_exec(self, sql_stmt, args = tuple()):
"""
Executes an SQL statement and returns a cursor.
An SQL exception might be raised on error
@return: SQL cursor object
"""
cursor = self.conn.cursor()
if self.__debug_sql:
... | [
"First, don't.\nDo not build SQL \"on the fly\". It's a security nightmare. It will cause more problems than it appears to solve.\nSecond, read the MySQL page on LIMIT. They suggest using a large number.\nSELECT * FROM tbl LIMIT 18446744073709551615;\n\nSwitch your default from 0 to 18446744073709551615.\nIf you... | [
0
] | [] | [] | [
"mysql",
"python"
] | stackoverflow_0003351897_mysql_python.txt |
Q:
How to select rows from an SQL model for a QListView connected to it
I am trying the following in PyQt4, using SQLAlchemy as the backend for a model for a QListView.
My first version looked like this:
class Model(QAbstractListModel):
def __init__(self, parent=None, *args):
super(Model, self).__init... | How to select rows from an SQL model for a QListView connected to it | I am trying the following in PyQt4, using SQLAlchemy as the backend for a model for a QListView.
My first version looked like this:
class Model(QAbstractListModel):
def __init__(self, parent=None, *args):
super(Model, self).__init__(parent, *args)
def data(self, index, role):
if not ind... | [
"Store the row IDs in a list in the model and use that as an index to retrieve the database rows. If you want to implement sorting within the model-view system just sort the list as reqired.\nIf you delete a row from the database directly, the model won't know and so it won't update the views. They will display sta... | [
1
] | [] | [] | [
"pyqt4",
"python",
"qt",
"sqlalchemy"
] | stackoverflow_0003190705_pyqt4_python_qt_sqlalchemy.txt |
Q:
python win32api in cygwin-1.75
when i run fabric-0.9.1 in cygwin, it say following error:
$ fab test.py
Traceback (most recent call last):
File "/usr/bin/fab", line 8, in <module>
load_entry_point('Fabric==0.9.1', 'console_scripts', 'fab')()
File "/usr/lib/python2.6/site-packages/setuptools-0.6c11-py2.6.eg... | python win32api in cygwin-1.75 | when i run fabric-0.9.1 in cygwin, it say following error:
$ fab test.py
Traceback (most recent call last):
File "/usr/bin/fab", line 8, in <module>
load_entry_point('Fabric==0.9.1', 'console_scripts', 'fab')()
File "/usr/lib/python2.6/site-packages/setuptools-0.6c11-py2.6.egg/pkg_resources.py", line 318, in lo... | [
"i find the answer, it is a small bug of fabric. i solve it according the article:\nhttp://atbrox.com/tag/fabric/\n"
] | [
1
] | [] | [] | [
"cygwin",
"fabric",
"python",
"winapi"
] | stackoverflow_0003350853_cygwin_fabric_python_winapi.txt |
Q:
MySQL - inform program that a duplicate INSERT was attempted
Is there an easy way to return something to your code if a duplicate insert is attempted?
I want to do something like this (Obviously doesn't work because (ON DUPLICATE KEY INDEX UPDATE)-
query = "INSERT INTO quotes(symbol, date, open, high, low, close, ... | MySQL - inform program that a duplicate INSERT was attempted | Is there an easy way to return something to your code if a duplicate insert is attempted?
I want to do something like this (Obviously doesn't work because (ON DUPLICATE KEY INDEX UPDATE)-
query = "INSERT INTO quotes(symbol, date, open, high, low, close, volume, adj)"
query += "VALUES ('" + symbol + "', '" + Date + "','... | [
"Catch the exception raised by the DB-API adapter.\n"
] | [
0
] | [] | [] | [
"mysql",
"python",
"sql"
] | stackoverflow_0003352330_mysql_python_sql.txt |
Q:
Creating read only text files with python
Is it possible to create read only files in python which can not be changed later and in which users can not change its attribute from read-only to normal file?
Please suggest.
Thanks in advance.
A:
This is not python specific.
If the files are made by a different user t... | Creating read only text files with python | Is it possible to create read only files in python which can not be changed later and in which users can not change its attribute from read-only to normal file?
Please suggest.
Thanks in advance.
| [
"This is not python specific.\nIf the files are made by a different user that the one viewing it the script can make it read-only. As the file is owned by the python user, the viewing user cannot just change the attributes.\nSo it's very much an OS question, and not a Python question.\nOh, and there is no way to pr... | [
3,
1,
0
] | [] | [] | [
"file",
"python"
] | stackoverflow_0003351484_file_python.txt |
Q:
Fastest way to produce UDP packets
We're building a test harness to push binary messages out on a UDP multicast.
The prototype is using the Twisted reactor loop to push out messages, which is achieving just about the level of traffic we require - about 120000 messages per second.
We have a 16 cores on our test mac... | Fastest way to produce UDP packets | We're building a test harness to push binary messages out on a UDP multicast.
The prototype is using the Twisted reactor loop to push out messages, which is achieving just about the level of traffic we require - about 120000 messages per second.
We have a 16 cores on our test machine, and obviously I'd like to spread t... | [
"Multiple NICs, the hardware or the kernel interface is the limit. I can only reach 69,000 packets per second with a Broadcom Corporation NetXtreme BCM5704S Gigabit Ethernet adapter. Try a quad Intel Gigabit Server Adapter with all four NICs on the same subnet.\n",
"The obvious answer when the question of explo... | [
1,
1
] | [] | [] | [
"python",
"stackless",
"twisted"
] | stackoverflow_0003350282_python_stackless_twisted.txt |
Q:
Getting BeautifulSoup to catch tags in a non-case-sensitive way
I want to catch some tags with BeautifulSoup: Some <p> tags, the <title> tag, some <meta> tags. But I want to catch them regardless of their case; I know that some sites do meta like this: <META> and I want to be able to catch that.
I noticed that Bea... | Getting BeautifulSoup to catch tags in a non-case-sensitive way | I want to catch some tags with BeautifulSoup: Some <p> tags, the <title> tag, some <meta> tags. But I want to catch them regardless of their case; I know that some sites do meta like this: <META> and I want to be able to catch that.
I noticed that BeautifulSoup is case-sensitive by default. How do I catch these tags in... | [
"BeautifulSoup standardises the parse tree on input. It converts tags to lower-case. You don't have anything to worry about IMO.\n",
"You can use soup.findAll which should match case-insensitively:\nimport BeautifulSoup\n\nhtml = '''<html>\n<head>\n<meta name=\"description\" content=\"Free Web tutorials on HTML, ... | [
2,
0
] | [] | [] | [
"beautifulsoup",
"case_insensitive",
"html",
"parsing",
"python"
] | stackoverflow_0003352563_beautifulsoup_case_insensitive_html_parsing_python.txt |
Q:
Python fork-exec problem, child process output goes to same place as parent process
Try the code below with: python fork.py and with: python fork.py 1 to see what it does.
#!/usr/bin/env python2
import os
import sys
child_exit_status = 0
if len(sys.argv) > 1:
child_exit_status = int(sys.argv[1])
pid = os.fo... | Python fork-exec problem, child process output goes to same place as parent process | Try the code below with: python fork.py and with: python fork.py 1 to see what it does.
#!/usr/bin/env python2
import os
import sys
child_exit_status = 0
if len(sys.argv) > 1:
child_exit_status = int(sys.argv[1])
pid = os.fork()
if pid == 0:
print "This is the child"
if child_exit_status == 0:
os... | [
"Under linux, the child process inherits (almost) everything from the parent, including file descriptors. In your case, file descriptor 1 (stdout) and file descriptor 2 (stderr) are open to the same file as the parent.\nSee the man page for fork().\nIf you want the output of the child to go someplace else, you can ... | [
3,
0
] | [] | [] | [
"exec",
"fork",
"python"
] | stackoverflow_0003352185_exec_fork_python.txt |
Q:
Python nose framework: How to stop execution upon first failure
It seems that if a testcase fails, nose will attempt to execute the next testcases. How can I make nose to abort all execution upon the first error in any testcase? I tried sys.exit() but it gave me some ugly and lengthy messages about it
A:
There... | Python nose framework: How to stop execution upon first failure | It seems that if a testcase fails, nose will attempt to execute the next testcases. How can I make nose to abort all execution upon the first error in any testcase? I tried sys.exit() but it gave me some ugly and lengthy messages about it
| [
"There is an option for nose:\n-x, --stop\nStop running tests after the first error or failure\n\nIs this what you need?\nFollowing link can help you with all the options available for nosetests.\n http://nose.readthedocs.org/en/latest/usage.html\n"
] | [
87
] | [] | [] | [
"python",
"unit_testing"
] | stackoverflow_0003352862_python_unit_testing.txt |
Q:
Mixin class to trace attribute requests - __attribute__ recursion
I'm trying to create a class which must be superclass of others, tracing their attribute requests. I thought of using "getattribute" which gets all attribute requests, but it generates recursion:
class Mixin(object):
def __getattribute__ (self, att... | Mixin class to trace attribute requests - __attribute__ recursion | I'm trying to create a class which must be superclass of others, tracing their attribute requests. I thought of using "getattribute" which gets all attribute requests, but it generates recursion:
class Mixin(object):
def __getattribute__ (self, attr):
print self, "getting", attr
return self.__dict__[attr]
... | [
"Try this:\nclass Mixin(object):\n def __getattribute__ (self, attr):\n print self, \"getting\", attr\n return object.__getattribute__(self, attr)\n\nIf you are still getting recursion problems, it is caused by code you haven't shown us\n>>> class Mixin(object):\n... def __getattribute__ (self,... | [
5,
0
] | [] | [] | [
"python",
"recursion"
] | stackoverflow_0003352325_python_recursion.txt |
Q:
fuse utimensat problem
I am developing fuse fs at python (with fuse-python bindings). What method I need to implement that touch correctly work? At present I have next output:
$ touch m/My\ files/d3elete1.me
touch: setting times of `m/My files/d3elete1.me': Invalid argument
File exists "d3elete1.me":
$ ls -l m... | fuse utimensat problem | I am developing fuse fs at python (with fuse-python bindings). What method I need to implement that touch correctly work? At present I have next output:
$ touch m/My\ files/d3elete1.me
touch: setting times of `m/My files/d3elete1.me': Invalid argument
File exists "d3elete1.me":
$ ls -l m/My\ files/d3elete1.me
-r... | [
"Try launching fuse with the -f option. Fuse will stay in foreground and you can see errors in the console.\n",
"You must implement utimens and getattr. Not all the system calls necessarily map directly to the C calls you might be expecting. Many of them are used internally by FUSE to check and navigate your file... | [
2,
1
] | [] | [] | [
"filesystems",
"fuse",
"linux",
"python"
] | stackoverflow_0003352872_filesystems_fuse_linux_python.txt |
Q:
Good framework for live charting in Python?
I am working on a Python application that involves running regression analysis on live data, and charting both. That is, the application gets fed with live data, and the regression models re-calculates as the data updates. Please note that I want to plot both the input (... | Good framework for live charting in Python? | I am working on a Python application that involves running regression analysis on live data, and charting both. That is, the application gets fed with live data, and the regression models re-calculates as the data updates. Please note that I want to plot both the input (the data) and output (the regression analysis) in... | [
"I've done quite a bit of animated graphing with matplotlib - it always took me some wrangling to get it to work.\nHere's a nice example though:\nhttp://matplotlib.sourceforge.net/examples/animation/simple_anim_gtk.html\n",
"I havent worked with Matplotlib but I've always found gnuplot to be adequate for all my c... | [
4,
1,
1
] | [] | [] | [
"charts",
"live",
"python"
] | stackoverflow_0003351963_charts_live_python.txt |
Q:
Dynamic Class Instantiation in Python
I have a bunch of classes in a module. Let's say:
'''players.py'''
class Player1:
def __init__(self, name='Homer'):
self.name = name
class Player2:
def __init__(self, name='Barney'):
self.name = name
class Player3:
def __init__(self, name='Moe'):... | Dynamic Class Instantiation in Python | I have a bunch of classes in a module. Let's say:
'''players.py'''
class Player1:
def __init__(self, name='Homer'):
self.name = name
class Player2:
def __init__(self, name='Barney'):
self.name = name
class Player3:
def __init__(self, name='Moe'):
self.name = name
...
Now, in ano... | [
"I ran your test code and it worked fine for me.\nThat error is indicating that you are not actually setting the default \"name\" parameter on ALL of your classes.\nI'd double check.\nEdit:\nNote that issubclass() returns True if given the SAME class twice.\n>>> class Foo: pass\n>>> issubclass(Foo, Foo)\nTrue\n\nSo... | [
2,
1,
0
] | [] | [] | [
"introspection",
"python"
] | stackoverflow_0003352258_introspection_python.txt |
Q:
Accessing methods of nested widgets
Im working on optimizing my design in terms of mvc, intent on simplifying the api of the view which is quite nested even though Iv built composite widgets(with there own events and/ pubsub messages) in an attempt to simpify things.
For example I have a main top level gui class a... | Accessing methods of nested widgets | Im working on optimizing my design in terms of mvc, intent on simplifying the api of the view which is quite nested even though Iv built composite widgets(with there own events and/ pubsub messages) in an attempt to simpify things.
For example I have a main top level gui class a wxFrame which has a number of widgets in... | [
"Well that's definitely one way to handle the issue. I tend to use pubsub to call methods the old fashioned way though. Some people like pyDispatcher better than pubsub. The main problem with using multi-dot method calling is that it's hard to debug if you have to change a method name.\n"
] | [
1
] | [] | [] | [
"design_patterns",
"model_view_controller",
"oop",
"python",
"user_interface"
] | stackoverflow_0003352521_design_patterns_model_view_controller_oop_python_user_interface.txt |
Q:
pydev importerror: no module named thread, debugging no longer works after pydev upgrade
My Eclipse 3.6 /PyDev setup just did a pydev upgrade to 1.6.0.2010071813 and debugging no longer works. My default python interpreter is 3.1 although I doubt that matters. Until the Eclipse upgrade of pydev, it was working ver... | pydev importerror: no module named thread, debugging no longer works after pydev upgrade | My Eclipse 3.6 /PyDev setup just did a pydev upgrade to 1.6.0.2010071813 and debugging no longer works. My default python interpreter is 3.1 although I doubt that matters. Until the Eclipse upgrade of pydev, it was working very nicely.
| [
"This is already fixed in the current nightly (1.6.1). See: http://pydev.org/download.html for details on getting it.\nNote that you can just change that \"import thread\" locally (in org.python.pydev.debug/pysrc/pydevd.py) for:\ntry: \n import thread \nexcept ImportError:\n import _thread as thread #Py3K ... | [
8,
1,
0
] | [] | [] | [
"eclipse",
"pydev",
"python"
] | stackoverflow_0003326740_eclipse_pydev_python.txt |
Q:
Using Python Functions From the Clips Expert System
Using PyClips, I'm trying to build rules in Clips that dynamically retrieve data from the Python interpreter. To do this, I register an external function as outlined in the manual.
The code below is a toy example of the problem. I'm doing this because I have an a... | Using Python Functions From the Clips Expert System | Using PyClips, I'm trying to build rules in Clips that dynamically retrieve data from the Python interpreter. To do this, I register an external function as outlined in the manual.
The code below is a toy example of the problem. I'm doing this because I have an application with a large corpus of data, in the form of a ... | [
"I received some help on the PyClips support group. The solution is to ensure your Python function returns a clips.Symbol object and use (test ...) to evaluate functions in the LHS of rules. The use of Reset() also appears to be necessary to activate certain rules.\nimport clips\nclips.Reset()\n\nuser = True\n\ndef... | [
3,
1
] | [] | [] | [
"clips",
"expert_system",
"machine_learning",
"python"
] | stackoverflow_0003247952_clips_expert_system_machine_learning_python.txt |
Q:
python: proper usage of global variable
here's the code!
import csv
def do_work():
global data
global b
get_file()
samples_subset1()
return
def get_file():
start_file='thefile.csv'
with open(start_file, 'rb') as f:
data = list(csv.reader(f))
import coll... | python: proper usage of global variable | here's the code!
import csv
def do_work():
global data
global b
get_file()
samples_subset1()
return
def get_file():
start_file='thefile.csv'
with open(start_file, 'rb') as f:
data = list(csv.reader(f))
import collections
counter = collections.default... | [
"As a rule of thumb, avoid global variables.\nHere, it's easy: \nlet get_file return data\nthen you can say\ndata = get_file()\nsamples_subset1(data)\n\nAlso, I'd do all the imports on the top of the file\n",
"if you must use a global (and sometimes we must) you can define it in a Pythonic way and give only certa... | [
5,
3,
2
] | [] | [] | [
"csv",
"python"
] | stackoverflow_0003354218_csv_python.txt |
Q:
python newbie question: converting code to classes
i have this code:
import csv
import collections
def do_work():
(data,counter)=get_file('thefile.csv')
b=samples_subset1(data, counter,'/pythonwork/samples_subset3.csv',500)
return
def get_file(start_file):
with open(start_file, 'rb') a... | python newbie question: converting code to classes | i have this code:
import csv
import collections
def do_work():
(data,counter)=get_file('thefile.csv')
b=samples_subset1(data, counter,'/pythonwork/samples_subset3.csv',500)
return
def get_file(start_file):
with open(start_file, 'rb') as f:
data = list(csv.reader(f))
... | [
"Per my comment on the original post, I don't think a class is necessary here. Still, if other Python programmers will ever read this, I'd suggest getting it inline with PEP8, the Python style guide. Here's a quick rewrite:\nimport csv\nimport collections\n\ndef do_work():\n data, counter = get_file('thefile.csv... | [
4,
2
] | [] | [] | [
"class",
"csv",
"python"
] | stackoverflow_0003354593_class_csv_python.txt |
Q:
In Jinja2 whats the easiest way to set all the keys to be the values of a dictionary?
I've got a dashboard that namespaces the context for each dashboard item. Is there a quick way I can set all the values of a dictionary to the keys in a template?
I want to reuse templates and not always namespace my variables.... | In Jinja2 whats the easiest way to set all the keys to be the values of a dictionary? | I've got a dashboard that namespaces the context for each dashboard item. Is there a quick way I can set all the values of a dictionary to the keys in a template?
I want to reuse templates and not always namespace my variables.
My context can be simplified to look something like this:
{
"business": {"businesses": []... | [
"Long story short: you can't set arbitrary variables in the context. The {% set key = value %} is just setting the variable named key to the given value.\nThe reason is because Jinja2 compiles templates down to Python code. (If you want to see the code your template generates, download the script at http://ryshcate... | [
4,
1
] | [] | [] | [
"jinja2",
"python",
"templates"
] | stackoverflow_0003352724_jinja2_python_templates.txt |
Q:
html form submission
I'm looking at the html form of an external website (not maintained by myself) in the following format :
<form onsubmit="return check(this)" method=post action=address.aspx target=ttPOST>
....
</form>
I wish to post data to this external website without having to go through the form and press... | html form submission | I'm looking at the html form of an external website (not maintained by myself) in the following format :
<form onsubmit="return check(this)" method=post action=address.aspx target=ttPOST>
....
</form>
I wish to post data to this external website without having to go through the form and pressing submit.
Can I simply ... | [
"I should note that I'm unclear if you were wanting to automate the posting of data from outside a web browser or not. Others have answered doing it with script and such like from the web page so I thought I'd cover how it works when you are doing it from a standalone program.\nFor most languages you can get things... | [
1,
1,
0,
0,
0,
0
] | [] | [] | [
"automation",
"html",
"mechanize",
"python"
] | stackoverflow_0003354620_automation_html_mechanize_python.txt |
Q:
Can I use Google App Engine for processing data?
I would like to execute some long running JRuby scripts [ nothing to do with web requests and url fetch ] on Google App Engine. There is a 30 seconds limit on URL Fetch requests. Does the same apply for plain JRuby/Python scripts? If yes, is there a workaround?
A:
... | Can I use Google App Engine for processing data? | I would like to execute some long running JRuby scripts [ nothing to do with web requests and url fetch ] on Google App Engine. There is a 30 seconds limit on URL Fetch requests. Does the same apply for plain JRuby/Python scripts? If yes, is there a workaround?
| [
"The 30-second applies to everything that happens on AppEngine. It's really not an ideal platform for hosting long-running processes. There are some techniques that you can use to simulate what you want. Task Queues can be set up to perform work in the background, for example.\nStill, you might want to look into on... | [
4
] | [] | [] | [
"google_app_engine",
"jruby",
"python"
] | stackoverflow_0003355197_google_app_engine_jruby_python.txt |
Q:
issue running a program (R) in Python to perform an operation (execute a script)
I'm tying to execute an R script from python, ideally displaying and saving the results. Using rpy2 has been a bit of a struggle, so I thought I'd just call R directly. I have a feeling that I'll need to use something like "os.syste... | issue running a program (R) in Python to perform an operation (execute a script) | I'm tying to execute an R script from python, ideally displaying and saving the results. Using rpy2 has been a bit of a struggle, so I thought I'd just call R directly. I have a feeling that I'll need to use something like "os.system" or "subprocess.call," but I am having difficulty deciphering the module guides.
Her... | [
"If your R script only has side effects that's fine, but if you want to process further the results with Python, you'll still be better of using rpy2.\nimport rpy2.robjects\nf = file(\"C:/R/library/MantelScript.R\")\ncode = ''.join(f.readlines())\nresult = rpy2.robjects.r(code)\n# assume that MantelScript creates a... | [
5,
2,
2,
0
] | [] | [] | [
"os.system",
"python",
"r",
"rpy2",
"subprocess"
] | stackoverflow_0003339147_os.system_python_r_rpy2_subprocess.txt |
Q:
Provide Global Access Point to an Instance of an Object
Imagine a system (Python) where the different parts constantly interact with one instance of a given object. What is the best way to provide a global access point to this instance?
So far I can only think of building the (Singleton) instance in __init__.py an... | Provide Global Access Point to an Instance of an Object | Imagine a system (Python) where the different parts constantly interact with one instance of a given object. What is the best way to provide a global access point to this instance?
So far I can only think of building the (Singleton) instance in __init__.py and import the module as needed:
# __init__.py
class Thing(obje... | [
"Don't use singletons in python. Python modules are great singletons (they are initialized only once and are available everywhere) and you can have a global variable in one, if you need it.\nHere is explanation: Is there a simple, elegant way to define singletons?\n"
] | [
6
] | [] | [] | [
"global_variables",
"python"
] | stackoverflow_0003355458_global_variables_python.txt |
Q:
Python MySQLdb cursor truncating values
I ran into an interesting problem. I have a MySQL database that contains some doubles with very precise decimal values (for example, 0.00895406607247756, 17 decimal places). This is scientific data so this high level of precision is very important.
I'm using MySQLdb in Pytho... | Python MySQLdb cursor truncating values | I ran into an interesting problem. I have a MySQL database that contains some doubles with very precise decimal values (for example, 0.00895406607247756, 17 decimal places). This is scientific data so this high level of precision is very important.
I'm using MySQLdb in Python to select data from the database:
cursor.ex... | [
"What MySQL datatype are you using to store the data? Is it DECIMAL(18,17)? DECIMALs have up to 65 digits of precision.\nIf you set the MySQL data type to use DECIMAL(...), then MySQLdb will convert the data to a Python decimal.Decimal object, which should preserve the precision.\n"
] | [
3
] | [] | [] | [
"decimal",
"floating_point",
"mysql",
"python"
] | stackoverflow_0003355353_decimal_floating_point_mysql_python.txt |
Q:
Creating a C wrapper with Cython - Python
I've been trying to figure out how to wrap the following C functions = compress.c , compress.h.
I tried following the tutorials, but after creating the .pxd file I don't know what to do :|
From what I have understood this is the pxd file that I should have
cdef extern from... | Creating a C wrapper with Cython - Python | I've been trying to figure out how to wrap the following C functions = compress.c , compress.h.
I tried following the tutorials, but after creating the .pxd file I don't know what to do :|
From what I have understood this is the pxd file that I should have
cdef extern from "compress.h":
size_t compress(void *s_sta... | [
"write a .pyx file that implements a wrapper calling the C functions?\nI think the toughest part might be buffer handling...\npylzjb.pyx could look as follows (note that your .pxd is inlined): \ncdef extern from \"compress.h\":\n size_t compress(void *s_start, void *d_start, size_t s_len)\n\nfrom stdlib cimport ... | [
3,
1
] | [] | [] | [
"boost_python",
"c",
"cython",
"python",
"ubuntu"
] | stackoverflow_0003352285_boost_python_c_cython_python_ubuntu.txt |
Q:
FTP upload file works manually, but fails using Python ftplib
I installed vsFTP in a Debian box. When manually upload file using ftp command, it's ok. i.e, the following session works:
john@myhost:~$ ftp xxx.xxx.xxx.xxx 5111
Connected to xxx.xxx.xxx.xxx.
220 Hello,Welcom to my FTP server.
Name (xxx.xxx.xxx.xxx:jo... | FTP upload file works manually, but fails using Python ftplib | I installed vsFTP in a Debian box. When manually upload file using ftp command, it's ok. i.e, the following session works:
john@myhost:~$ ftp xxx.xxx.xxx.xxx 5111
Connected to xxx.xxx.xxx.xxx.
220 Hello,Welcom to my FTP server.
Name (xxx.xxx.xxx.xxx:john): ftpuser
331 Please specify the password.
Password:
230 Login s... | [
"The timeout doesn't happen until you try to send the data, so you were able to connect to the server successfully. The only difference I see is that ftplib uses passive mode by default, whereas your command-line client does not appear to. Try doing \nftp.set_pasv(False)\n\nbefore initiating the transfer and see ... | [
7
] | [] | [] | [
"ftp",
"python"
] | stackoverflow_0003349722_ftp_python.txt |
Q:
How to extend pretty print module to tables?
I have the pretty print module, which I prepared because I was not happy the pprint module produced zillion lines for list of numbers which had one list of list. Here is example use of my module.
>>> a=range(10)
>>> a.insert(5,[range(i) for i in range(10)])
... | How to extend pretty print module to tables? | I have the pretty print module, which I prepared because I was not happy the pprint module produced zillion lines for list of numbers which had one list of list. Here is example use of my module.
>>> a=range(10)
>>> a.insert(5,[range(i) for i in range(10)])
>>> a
[0, 1, 2, 3, 4, [[], [0], [0, 1], [0, 1,... | [
"If you're looking for nice formatting for matrices, numpy's output looks great right out of the box:\nfrom numpy import *\nprint array([[i + j for i in range(10)] for j in range(10)])\n\nOutput:\n[[ 0 1 2 3 4 5 6 7 8 9]\n [ 1 2 3 4 5 6 7 8 9 10]\n [ 2 3 4 5 6 7 8 9 10 11]\n [ 3 4 5 6 7 ... | [
7,
3,
1,
1
] | [] | [] | [
"formatting",
"generator",
"python"
] | stackoverflow_0003319540_formatting_generator_python.txt |
Q:
python: getting element in a list
def do_work():
medications_subset2(b,['HYDROCODONE','MORPHINE','OXYCODONE'])
def medications_subset2(b,drugs_needed):
MORPHINE=['ASTRAMORPH','AVINZA','CONTIN','DURAMORPH','INFUMORPH',
'KADIAN','MS CONTIN','MSER','MSIR','ORAMORPH',
'ORAMORPH SR','ROXANO... | python: getting element in a list | def do_work():
medications_subset2(b,['HYDROCODONE','MORPHINE','OXYCODONE'])
def medications_subset2(b,drugs_needed):
MORPHINE=['ASTRAMORPH','AVINZA','CONTIN','DURAMORPH','INFUMORPH',
'KADIAN','MS CONTIN','MSER','MSIR','ORAMORPH',
'ORAMORPH SR','ROXANOL','ROXANOL 100']
print drugs_needed[... | [
"Can you define MORPHINE this way?\ndrugs = {\n 'MORPHINE': ['ASTRAMORPH',...],\n 'HYDROCODONE': [...],\n ...\n}\n\nthen you can refer to it by\nprint ( drugs[drugs_needed[1]][0] )\n\n"
] | [
4
] | [] | [] | [
"python"
] | stackoverflow_0003355745_python.txt |
Q:
Automatically passing extra attributes to Widget
I have a custom model fields, that can have 'chain' argument.
from django.db import models
class ChainField(object):
def __init__(self, *args, **kwargs):
chain = kwargs.get('chain', False)
if chain:
self.chain = chain
de... | Automatically passing extra attributes to Widget | I have a custom model fields, that can have 'chain' argument.
from django.db import models
class ChainField(object):
def __init__(self, *args, **kwargs):
chain = kwargs.get('chain', False)
if chain:
self.chain = chain
del kwargs['chain']
super(self.__class__.__mro_... | [
"Override __init__ of the ModelForm like this:\nclass MyClass(ModelForm):\n def __init__(self, *args, **kwargs):\n super(MyClass, self).__init__(*args, **kwargs)\n\n chain_value = self.fields['name_of_the_field'].chain\n self.fields['name_of_the_field'].widget = CustomWidget(chain=chain_valu... | [
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003350958_django_python.txt |
Q:
Module "mymodule" does not define a "MyBackend" authentication backend
I'm trying to use a custom authentication backend for a Django project I'm working on. My backend is based on the LDAPBackend found in the article LDAP Authentication in Django with Backends.
I'm getting the floowing error when I attempt to log... | Module "mymodule" does not define a "MyBackend" authentication backend | I'm trying to use a custom authentication backend for a Django project I'm working on. My backend is based on the LDAPBackend found in the article LDAP Authentication in Django with Backends.
I'm getting the floowing error when I attempt to log in:
ImproperlyConfigured at /admin/
Module "challenge.backends" does not d... | [
"You are importing it in wrong way. You are importing a module, rather than a class. That's why shell allows you to import it, but django complains.\nYou should use challenge.backends.LDAPBackend.LDAPBackend.\nAlso, it's a good idea to stick with PEP8 when naming modules, this way you won't be confused that way aga... | [
6
] | [] | [] | [
"authentication",
"django",
"python"
] | stackoverflow_0003355492_authentication_django_python.txt |
Q:
Fork and exit in Python
This code is supposed to try and start a server process and return.
If the port was taken, it should say "couldn't bind to that port" and return. If the server started, it should print "Bound to port 51231" and return. But it does not return.
import socket
from multiprocessing import Proces... | Fork and exit in Python | This code is supposed to try and start a server process and return.
If the port was taken, it should say "couldn't bind to that port" and return. If the server started, it should print "Bound to port 51231" and return. But it does not return.
import socket
from multiprocessing import Process
def serverMainLoop(s,t):
... | [
"Check this page, it describes how to use os.fork() and os._exit(1) to build a daemon which forks to background.\nA prototype of what you perhaps want would be:\npid = os.fork()\nif (pid == 0): # The first child.\n os.chdir(\"/\")\n os.setsid()\n os.umask(0) \n pid2 = os.fork() \n if (pid2 == 0): # Secon... | [
4,
1,
0
] | [] | [] | [
"fork",
"python"
] | stackoverflow_0003355995_fork_python.txt |
Q:
Positionally matching substrings in Python
How would you parse the ['i386', 'x86_64'] out of a string like '-foo 23 -bar -arch ppc -arch i386 -isysroot / -fno-strict-aliasing -fPIC'?
>>> my_arch_parse_function('-foo 23 -bar -arch i386 -arch x86_64 -isysroot / -fno-strict-aliasing -fPIC')
>>> ['i386', 'x86_64']
... | Positionally matching substrings in Python | How would you parse the ['i386', 'x86_64'] out of a string like '-foo 23 -bar -arch ppc -arch i386 -isysroot / -fno-strict-aliasing -fPIC'?
>>> my_arch_parse_function('-foo 23 -bar -arch i386 -arch x86_64 -isysroot / -fno-strict-aliasing -fPIC')
>>> ['i386', 'x86_64']
Can this be done using regex, or only using modu... | [
"Why not use the argument parsing modules? optparse in Python 2.6 (and 3.1) and argparse in Python 2.7 (and 3.2).\nEDIT: On second thought, that's not as simple as it sounds, because you may have to define all the arguments you are likely to see (not sure if these modules have a catchall mechanism). I'll leave the ... | [
4,
3,
2,
0,
0,
0
] | [] | [] | [
"parsing",
"python",
"regex"
] | stackoverflow_0003356038_parsing_python_regex.txt |
Q:
python: complicated loop through list
import csv
import collections
def do_work():
(data,counter)=get_file('thefile.csv')
b=samples_subset1(data,counter,'/pythonwork/samples_subset4.csv',500)
medications_subset2(b,['HYDROCODONE','MORPHINE','OXYCODONE'])
def get_file(start_file):
with open(start_file,'rb'... | python: complicated loop through list | import csv
import collections
def do_work():
(data,counter)=get_file('thefile.csv')
b=samples_subset1(data,counter,'/pythonwork/samples_subset4.csv',500)
medications_subset2(b,['HYDROCODONE','MORPHINE','OXYCODONE'])
def get_file(start_file):
with open(start_file,'rb') as f:
data=list(csv.reader(f))
co... | [
"I didn't really read your code paragraph, but from the problem you described afterwards it sounds like you want:\nneeded = set(['ALGIDON','ALGOLYSIN','AMIDON','DEPRIDOL','DOLOPHINE','FENADONE', 'METHADOSE','MIADONE','PHENADONE'])\nb = filter(lambda s: len(set(s.upper().split(',')) & needed) > 0, b)\n\n"
] | [
1
] | [] | [] | [
"csv",
"list",
"python"
] | stackoverflow_0003356209_csv_list_python.txt |
Q:
Python: Regex to extract part of URL found between parentheses
I have this weirdly formatted URL. I have to extract the contents in '()'.
Sample URL : http://sampleurl.com/(K(ThinkCode))/profile/view.aspx
If I can extract ThinkCode out of it, I will be a happy man! I am having a tough time with regexing special ch... | Python: Regex to extract part of URL found between parentheses | I have this weirdly formatted URL. I have to extract the contents in '()'.
Sample URL : http://sampleurl.com/(K(ThinkCode))/profile/view.aspx
If I can extract ThinkCode out of it, I will be a happy man! I am having a tough time with regexing special chars like '(' and '/'.
| [
">>> foo = re.compile( r\"(?<=\\(K\\()[^\\)]*\" )\n>>> foo.findall( r\"http://sampleurl.com/(K(ThinkCode))/profile/view.aspx\" )\n['ThinkCode']\n\nExplanation\nIn regex-world, a lookbehind is a way of saying \"I want to match ham, but only if it's preceded by spam. We write this as (?<=spam)ham. So in this case, we... | [
4,
1,
0,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0003356300_python_regex.txt |
Q:
Solving jumbled word puzzles with python?
I have an interesting programming puzzle for you:
You will be given two things:
A word containing a list of English words put together, e.g:
word = "iamtiredareyou"
Possible subsets:
subsets = [
'i', 'a', 'am', 'amt', 'm', 't', 'ti', 'tire', 'tired', 'i',
'ire', ... | Solving jumbled word puzzles with python? | I have an interesting programming puzzle for you:
You will be given two things:
A word containing a list of English words put together, e.g:
word = "iamtiredareyou"
Possible subsets:
subsets = [
'i', 'a', 'am', 'amt', 'm', 't', 'ti', 'tire', 'tired', 'i',
'ire', 'r', 're', 'red', 'redare', 'e', 'd', 'da', 'da... | [
"Generally, a recursive algorithm would do.\nStart with checking all subsets against start of a given word, if found — add (append) to found values and recurse with remaining part of the word and current found values.\nOr if it's an end of the string — print found values.\nsomething like that:\nall=[]\ndef frec(wor... | [
3,
2,
1,
1,
0,
0
] | [] | [] | [
"algorithm",
"python"
] | stackoverflow_0003350951_algorithm_python.txt |
Q:
Is there a Python ORM framework for interacting with data via XML-RPC?
I am working on a webapp that interacts with data via XML-RPC rather than with a direct connection to a database. I can execute SQL queries via an XML-RPC methods.
I would like to interact with the data in an ORM framework fashion that has laz... | Is there a Python ORM framework for interacting with data via XML-RPC? | I am working on a webapp that interacts with data via XML-RPC rather than with a direct connection to a database. I can execute SQL queries via an XML-RPC methods.
I would like to interact with the data in an ORM framework fashion that has lazy/eager fetching, etc., although I can't seem to figure out how that would b... | [
"You would have to write your own database backend. Take a look at existing backends for how to do this.\n",
"Check out XML Models. It's REST rather than XML-RPC, but much of it is probably reusable.\n"
] | [
0,
0
] | [] | [] | [
"django",
"orm",
"python",
"xml_rpc"
] | stackoverflow_0003356428_django_orm_python_xml_rpc.txt |
Q:
How to modify django cms multilingual middleware
hey guys, im trying to internationalize my site, so i have the django cms multilingual middleware class in my settings.py , when viewed from brasil, the url changes to
www.ashtangayogavideo.com/pt/ash/homepage/ resulting in a 404, because my site is in www.ashtangay... | How to modify django cms multilingual middleware | hey guys, im trying to internationalize my site, so i have the django cms multilingual middleware class in my settings.py , when viewed from brasil, the url changes to
www.ashtangayogavideo.com/pt/ash/homepage/ resulting in a 404, because my site is in www.ashtangayogavideo.com/ash/en/homepage, how can i configure the ... | [
"Sounds like you need to modify your urls.py, not your settings or middleware.\n"
] | [
2
] | [] | [] | [
"django",
"django_cms",
"python"
] | stackoverflow_0003327590_django_django_cms_python.txt |
Q:
Finding the architectures that Python was built for, but from within Python itself
Essentially I am looking for a way to find the following, but from within Python without having to run system commands:
$ file `which python2.7`
/Library/.../2.7/bin/python2.7: Mach-O universal binary with 2 architectures
/Library/.... | Finding the architectures that Python was built for, but from within Python itself | Essentially I am looking for a way to find the following, but from within Python without having to run system commands:
$ file `which python2.7`
/Library/.../2.7/bin/python2.7: Mach-O universal binary with 2 architectures
/Library/.../2.7/bin/python2.7 (for architecture i386): Mach-O executable i386
/Library/.../2.7... | [
"As far as I know, there is no truly reliable way other than to examine the executable files themselves to see which architectures have been lipo-ed together, in other words, what file does. While the distutils.util.get_platform() noted elsewhere probably comes the closest, it is based on configuration information ... | [
1,
0
] | [] | [] | [
"architecture",
"macos",
"python"
] | stackoverflow_0003355846_architecture_macos_python.txt |
Q:
How do I access data programatically (load a pickled file) that is stored as a static file?
how is this solution I am using now:
I have a 1MB .dbf file in the same directory of all my .py modules. In main.py I have
import tools
In tool.py code is :
the_list_that_never_changes = loadDbf(file).variables['CNTYIDFP... | How do I access data programatically (load a pickled file) that is stored as a static file? | how is this solution I am using now:
I have a 1MB .dbf file in the same directory of all my .py modules. In main.py I have
import tools
In tool.py code is :
the_list_that_never_changes = loadDbf(file).variables['CNTYIDFP'].
So the_list_that_never_changes is only loaded once and is always in memory ready to be used.... | [
"Static files are stored apart from application files. If you need to load data.pkl from main.py, then don't mark it as a static file and it will be accessible by main.py like any other application file.\nReference: Application Configuration's Handlers For Static Files.\n\nAlternative: Why not define the informati... | [
2,
0
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0003340015_google_app_engine_python.txt |
Q:
Suggestions for passing large table between Python and C#
I have a C# application that needs to be run several thousand times. Currently it precomputes a large table of constant values at the start of the run for reference. As these values will be the same from run to run I would like to compute them independent... | Suggestions for passing large table between Python and C# | I have a C# application that needs to be run several thousand times. Currently it precomputes a large table of constant values at the start of the run for reference. As these values will be the same from run to run I would like to compute them independently in a simple python script and then just have the C# app impo... | [
"I would go for a simplified csv file.\nGiven that all your values are numbers, you can read them in C# using\nFile.ReadAllText(filename).Split(',')\n\nYou can find more C# options for csv here\nOn Python you can use the csv module to read and write them. Better explanation here, but the short of it is\nimport csv\... | [
2,
2,
2,
1,
1,
1
] | [] | [] | [
"c#",
"file",
"python"
] | stackoverflow_0003355832_c#_file_python.txt |
Q:
is it bad convention to call sys.argv from somewhere besides main function in python
I am writing a script and I have a function, call it f(), that needs one of the command line arguments (a filename it needs to open). However, f() is not called directly in the main function.
I was wondering if it was bad coding ... | is it bad convention to call sys.argv from somewhere besides main function in python | I am writing a script and I have a function, call it f(), that needs one of the command line arguments (a filename it needs to open). However, f() is not called directly in the main function.
I was wondering if it was bad coding convention to call sys.argv[1] straight from f()? If I don't I would have to pass it as an... | [
"It would be a bad practice to always assume that the arguments that your function needs are available on the command-line - what if this code was invoked in some other manner?\nA function should declare input parameters for the data it needs to access.\nAt the very least, passing the necessary argument into f() ra... | [
6,
4,
3,
1,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0003356262_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.