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:
python sort a two-level defaultdict and return defaultdict or dict
I have a question about sort defaultdict in python
Assume I have the following codes:
a = defaultdict(defaultdict)
a['c']['C'] = 1
a['b']['B'] = 2
a['a']['A'] = 3
a['a']['AA'] = 4
I'd like to sort it by the first key and then get another sorted de... | python sort a two-level defaultdict and return defaultdict or dict | I have a question about sort defaultdict in python
Assume I have the following codes:
a = defaultdict(defaultdict)
a['c']['C'] = 1
a['b']['B'] = 2
a['a']['A'] = 3
a['a']['AA'] = 4
I'd like to sort it by the first key and then get another sorted defaultdict like
a['a']['A'] = 3
a['a']['AA'] = 4
a['b']['B'] = 2
a['c']['... | [
"for k1 in sorted(a.keys()):\n sub = a[k1]\n for k2 in sorted(sub.keys()):\n print k1, k2, sub[k2] # or do whatever else\n\nThis prints the keys and values sorted as you want.\n",
"Looks like you just miss-using dictionaries. Do you need to access values by key?\nIf True use OrderedDict else you don't nee... | [
3,
1,
0
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0004584697_dictionary_python.txt |
Q:
how to run two django projects with different python versions
Possible Duplicate:
How to run multiple python version on Windows
i want to run two django projects at the same time on a single os (windows) simultaneously.
both projects has different python versions.
here i want to run two django projects simultane... | how to run two django projects with different python versions |
Possible Duplicate:
How to run multiple python version on Windows
i want to run two django projects at the same time on a single os (windows) simultaneously.
both projects has different python versions.
here i want to run two django projects simultaneously on the machine. i don't know how it is possible because both... | [
"Ok, so I'll answer the question again.\nTo use two versions, you install both alongside each other in different directories, as the installer on Windows will do, by default. To run one project with Python 2.5, you install and run it by using the Python.exe installed in the Python 2.5 directory. And to run the othe... | [
2
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004584287_django_python.txt |
Q:
Django Unhandled Exception
It is running under DEBUG = True mode. Sometimes it can throw out an error message with traceback information when encounter an error but sometimes it just display the following lines:
Unhandled Exception
An unhandled exception was thrown by the application.
I have to switch to develop... | Django Unhandled Exception | It is running under DEBUG = True mode. Sometimes it can throw out an error message with traceback information when encounter an error but sometimes it just display the following lines:
Unhandled Exception
An unhandled exception was thrown by the application.
I have to switch to development server to see detail messag... | [
"Just connect to the got_request_exception signal and log the exception:\nfrom django.core.signals import got_request_exception\nimport logging \n\ndef log(*args, **kwargs):\n logging.exception('error')\n\ngot_request_exception.connect(log)\n\nThis will log the whole trace. In the dev server, it logs in the c... | [
10,
6,
4,
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0001925898_django_python.txt |
Q:
Google App Engine as Authentication Server for Mobile Application
I am attempting to utilize Google App Engine as an Authentication Server for a mobile application that runs on android natively. User names and passwords will be stored in GAE and my goal is to be able to both store and verify credentials from the m... | Google App Engine as Authentication Server for Mobile Application | I am attempting to utilize Google App Engine as an Authentication Server for a mobile application that runs on android natively. User names and passwords will be stored in GAE and my goal is to be able to both store and verify credentials from the mobile application using GAE. Is this possible? I've looked into OAuth a... | [
"If you are interested in having a more API-like implementation in your GAE instance, I would definitely look more into OAuth. But if you are only interested in validating credentials for this one mobile application then you need not go that far.\nFortunately you can call your GAE instance over SSL, that means that... | [
1,
0
] | [] | [] | [
"google_app_engine",
"oauth",
"python",
"titanium"
] | stackoverflow_0004582255_google_app_engine_oauth_python_titanium.txt |
Q:
python os.stat return always the same mtime/size
With the following code I always get the same size and mtime:
# -*- coding: utf-8 -*-
import gtk
import pygtk
import os
class LocalFileTreeView(gtk.TreeView):
def __init__(self, model = None):
super(LocalFileTreeView, self).__init__(model)
se... | python os.stat return always the same mtime/size | With the following code I always get the same size and mtime:
# -*- coding: utf-8 -*-
import gtk
import pygtk
import os
class LocalFileTreeView(gtk.TreeView):
def __init__(self, model = None):
super(LocalFileTreeView, self).__init__(model)
self.model = gtk.TreeStore(gtk.gdk.Pixbuf, str, str, str... | [
"Change os.stat(path) to os.stat(complete_path), it's re-stating the same path passed in for every file.\nAnd you can get that epoch timestamp into a time object using time.localtime() (or time.gmtime())\n"
] | [
6
] | [] | [] | [
"pygtk",
"python",
"size",
"stat",
"time"
] | stackoverflow_0004585506_pygtk_python_size_stat_time.txt |
Q:
More than one profile in Django?
Is it possible to use Django's user authentication features with more than one profile?
Currently I have a settings.py file that has this in it:
AUTH_PROFILE_MODULE = 'auth.UserProfileA'
and a models.py file that has this in it:
from django.db import models
from django.contrib.aut... | More than one profile in Django? | Is it possible to use Django's user authentication features with more than one profile?
Currently I have a settings.py file that has this in it:
AUTH_PROFILE_MODULE = 'auth.UserProfileA'
and a models.py file that has this in it:
from django.db import models
from django.contrib.auth.models import User
class UserProfil... | [
"So the issue you're going to have is that whatever you want for your profile, you need to persist it in a database of some sort. Basically all of the back-ends for django are relational, and thus every field in a persisted object is present in every row of the table. there are a few ways for getting what you wan... | [
4,
1,
0,
0
] | [] | [] | [
"django",
"django_authentication",
"python"
] | stackoverflow_0004581370_django_django_authentication_python.txt |
Q:
problems in Python Sched
I have created the number of schedulers using python in windows which are running in background.
Can anyone tell me any command to check how many schedulers running on windows and also how can I remove them?
A:
If you are using sched.scheduler, you can query sched.scheduler.queue.
sched... | problems in Python Sched | I have created the number of schedulers using python in windows which are running in background.
Can anyone tell me any command to check how many schedulers running on windows and also how can I remove them?
| [
"If you are using sched.scheduler, you can query sched.scheduler.queue.\n\nscheduler.queue\nRead-only attribute returning a list of upcoming events in the order they will be run. Each event is shown as a named tuple with the following fields: time, priority, action, argument.\n\nIn the very docs there is also this ... | [
3,
0
] | [] | [] | [
"python"
] | stackoverflow_0004585237_python.txt |
Q:
python: nonblocking subprocess, check stdout
Ok so the problem I'm trying to solve is this:
I need to run a program with some flags set, check on its progress and report back to a server. So I need my script to avoid blocking while the program executes, but I also need to be able to read the output. Unfortunatel... | python: nonblocking subprocess, check stdout | Ok so the problem I'm trying to solve is this:
I need to run a program with some flags set, check on its progress and report back to a server. So I need my script to avoid blocking while the program executes, but I also need to be able to read the output. Unfortunately, I don't think any of the methods available from... | [
"Basically you have 3 options: \n\nUse threading to read in another thread without blocking the main thread.\nselect on stdout, stderr instead of communicate. This way you can read just when data is available and avoid blocking.\nLet a library solve this, twisted is a obvious choice.\n\n",
"You can use twisted li... | [
7,
2
] | [] | [] | [
"nonblocking",
"popen",
"python",
"stdout",
"subprocess"
] | stackoverflow_0004585692_nonblocking_popen_python_stdout_subprocess.txt |
Q:
How to filter all words, which contain N or more characters?
I would like to process a textual file to find all words which contain more than N characters. Any solution in Bash (grep,awk) or Python (re) is welcomed! However, the shortest one is prefered.
A:
egrep -o '[^ ]{N,}' <filename>
Find all non-space cons... | How to filter all words, which contain N or more characters? | I would like to process a textual file to find all words which contain more than N characters. Any solution in Bash (grep,awk) or Python (re) is welcomed! However, the shortest one is prefered.
| [
"egrep -o '[^ ]{N,}' <filename>\n\nFind all non-space constructs at least N characters long. If you're concerned about \"words\" you might try [a-zA-Z].\n",
"#!/usr/bin/env python\n\nimport sys, re\n\ndef morethan(n, file_or_string):\n try:\n content = open(file_or_string, 'r').read()\n except:\n ... | [
13,
2,
2,
2,
2,
1,
1,
1,
0,
0,
0,
0
] | [] | [] | [
"bash",
"linux",
"python",
"regex"
] | stackoverflow_0004585255_bash_linux_python_regex.txt |
Q:
Webscraping Techniques using PHP or Python
I need to scrape about 100 websites that are very similar in the content that they provide.
My first doubt. Should be possible to write a generic script to scrape all the 100 websites or in scraping techniques is only possible to write scripts for particular websites. (Du... | Webscraping Techniques using PHP or Python | I need to scrape about 100 websites that are very similar in the content that they provide.
My first doubt. Should be possible to write a generic script to scrape all the 100 websites or in scraping techniques is only possible to write scripts for particular websites. (Dumb question.). I think I should ask what possibi... | [
"1.) One scraper for 100 sites? It depends on your requirements. If you only need specific information, you'll need to consider 100 different websites, and their layouts. Some generic functionality could be shared, though.\n2.) BeautifulSoup is an HTML/XML parser, not a screen scraper per se. It would be a top choi... | [
2,
2,
0,
0
] | [] | [] | [
"php",
"python",
"screen_scraping"
] | stackoverflow_0004585490_php_python_screen_scraping.txt |
Q:
How to manage authentication across handler classes in google app engine /w python
Taking into account that I barely know python and am simply following the "hello-world" example here: http://code.google.com/appengine/docs/python/gettingstarted/
I'm unclear as to how I would: use a "MainHandler" class mapped to '/... | How to manage authentication across handler classes in google app engine /w python | Taking into account that I barely know python and am simply following the "hello-world" example here: http://code.google.com/appengine/docs/python/gettingstarted/
I'm unclear as to how I would: use a "MainHandler" class mapped to '/' as a welcome page, ask the user to login and then only allow logged-in users to access... | [
"You've asked a very broad question, and provided no details about what (if any) framework you're planning to use to implement your app. I guess you are probably using webapp? \nThe basic idea would be to create a login url that you redirect the user to, or you provide to them. If you want them redirected to an e... | [
2,
1
] | [] | [] | [
"authentication",
"google_app_engine",
"python"
] | stackoverflow_0004586830_authentication_google_app_engine_python.txt |
Q:
Abstraction layer between iphone and database
I've built a backend in python that posts data to the database. I want a layer of abstraction, so I thought that the best thing to do was to call a python function from objective-c. The python function would then post to the database. How can this be done?
A:
You'... | Abstraction layer between iphone and database | I've built a backend in python that posts data to the database. I want a layer of abstraction, so I thought that the best thing to do was to call a python function from objective-c. The python function would then post to the database. How can this be done?
| [
"You'll need to access the Python function via a web server (potentially using an intermediate scripting language to call the Python script). You can read more about this via http://docs.python.org/howto/webservers.html\nBeing honest, it may prove to be less hassle to simply use a more common web scripting language... | [
1
] | [] | [] | [
"abstraction",
"iphone",
"python"
] | stackoverflow_0004587068_abstraction_iphone_python.txt |
Q:
"<<<<<<" symbol in source code
I'm reading Python code of someone else and see these symbols appear on top of the file:
<<<<<< .mine
There are also
>>>>>>
and
=======
I'm not sure what that is. When compiling, the interpreter throws a syntax error at that line.
Does anyone know the meaning of this line?
A:
T... | "<<<<<<" symbol in source code | I'm reading Python code of someone else and see these symbols appear on top of the file:
<<<<<< .mine
There are also
>>>>>>
and
=======
I'm not sure what that is. When compiling, the interpreter throws a syntax error at that line.
Does anyone know the meaning of this line?
| [
"Those are markers for conflicts from your source control - they're marking which changes are yours, and which changes are from whatever you tried to merge in.\n",
"This is caused by an incomplete SVN merge. SVN attempted to modify the file to show you a diff of the conflict, but someone committed or left the fil... | [
8,
4,
0,
0,
0
] | [] | [] | [
"diff",
"python"
] | stackoverflow_0004587160_diff_python.txt |
Q:
unexplainable python dict problem
hey all,
i been trying to make a class that uses a dictionary to construct a kind of table but something extremely weird is happening.. heres my code
class dbase:
def __init__(self):
self.rows = {}
self.cols = {}
def addrow(self, name):
self.rows[na... | unexplainable python dict problem | hey all,
i been trying to make a class that uses a dictionary to construct a kind of table but something extremely weird is happening.. heres my code
class dbase:
def __init__(self):
self.rows = {}
self.cols = {}
def addrow(self, name):
self.rows[name] = self.cols
def addcol(self, na... | [
"Wow. This is the messiest code I've seen in a while. You realize that when you add a row, you're just adding the same dictionary that every other column has.\ndef __init__(self):\n self.rows = {}\n self.cols = {}\ndef addrow(self, name):\n self.rows[name] = self.cols\n\nI think you meant\ndef addrow(self,... | [
4,
3,
1,
0,
0,
0
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0004587553_dictionary_python.txt |
Q:
Post HTML data via XMLRPC in Python?
I am writing a small script by Python to connect and post content to my WordPress blog. It's pretty straightforward with https://github.com/maxcutler/python-wordpress-xmlrpc
However, when i tried to input a HTML data, for example:
<b>Hello</b>
It appears exactly in the WordPre... | Post HTML data via XMLRPC in Python? | I am writing a small script by Python to connect and post content to my WordPress blog. It's pretty straightforward with https://github.com/maxcutler/python-wordpress-xmlrpc
However, when i tried to input a HTML data, for example:
<b>Hello</b>
It appears exactly in the WordPress post (I watch it from the visual editor... | [
"Could the HTML data you are uploading already have its angle brackets escaped into HTML entities? I.e. < becomes < while > becomes > \nThis would lead to the behavior you describe. The visual editor would show what looks like raw HTML, not the result of rendering HTML. \nTo fix, either (i) prevent that encod... | [
1
] | [] | [] | [
"php",
"python",
"wordpress",
"xml_rpc"
] | stackoverflow_0004578216_php_python_wordpress_xml_rpc.txt |
Q:
registration 0.8 alpha activation problem
Got the following error:
Exception Type: TypeError at /accounts/account/activate/success/
Exception Value: activate() takes at least 2 non-keyword arguments (1 given)
My view:
def activate(request, backend,
template_name='registration/activation_complete.html... | registration 0.8 alpha activation problem | Got the following error:
Exception Type: TypeError at /accounts/account/activate/success/
Exception Value: activate() takes at least 2 non-keyword arguments (1 given)
My view:
def activate(request, backend,
template_name='registration/activation_complete.html',
success_url=None, extra_context... | [
"The URL /accounts/account/activate/success/ matches the URLconf for 'registration.views.activate' (second from the end), because success matches \\w+. Move the real success URL (the final one) above this one, so that it is matched first.\n",
"Okay, this is working now, but when activation_complete.html is coming... | [
1,
0
] | [] | [] | [
"django",
"python",
"registration",
"web"
] | stackoverflow_0004580219_django_python_registration_web.txt |
Q:
Automatically create valid links
I'm new to python, so please bear with me :)
I was wondering if there's any built-in way in python to append variables to URL's regardless of it's structure.
I would like to have a URL variable (test=1) added to an URL which could have any of the following structures
http://www.aa... | Automatically create valid links | I'm new to python, so please bear with me :)
I was wondering if there's any built-in way in python to append variables to URL's regardless of it's structure.
I would like to have a URL variable (test=1) added to an URL which could have any of the following structures
http://www.aaa.com (would simply add
"/?test=1") ... | [
"Using both Lennart Regebro's and Adam Vendenberg's suggestions, you could do something like this:\nimport urllib\nimport urlparse\n\nquery=urllib.urlencode({\"test\":1})\nurls=['http://www.aaa.com',\n 'http://www.aaa.com/home',\n 'http://www.aaa.com/?location=home',\n 'http://www.aaa.com/?location=h... | [
3,
1,
1
] | [] | [] | [
"python",
"url"
] | stackoverflow_0004587627_python_url.txt |
Q:
Django install on a shared host, .htaccess help
I am trying to install Django on a shared host using the following instructions:
docs.google.com/View?docid=dhhpr5xs_463522g
My problem is with the following line on my root .htaccess:
RewriteRule ^(.*)$ /cgi-bin/wcgi.py/$1 [QSA,L]
When I include this line I get a 5... | Django install on a shared host, .htaccess help | I am trying to install Django on a shared host using the following instructions:
docs.google.com/View?docid=dhhpr5xs_463522g
My problem is with the following line on my root .htaccess:
RewriteRule ^(.*)$ /cgi-bin/wcgi.py/$1 [QSA,L]
When I include this line I get a 500 error with almost all of my domains on this accoun... | [
"Looks like I should be using fastcgi with my hosting service:\nAddHandler fcgid-script .fcgi\nRewriteEngine On\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteRule ^(.*)$ index.fcgi/$1 [QSA,L]\n\n"
] | [
0
] | [] | [] | [
".htaccess",
"python"
] | stackoverflow_0004581385_.htaccess_python.txt |
Q:
PyQt & Python2.3
Is there a PyQt3 (Or 4) Windows binary installer for Python 2.3? I've googled around for an hour now but to no avail. Why am I using version 2.3? With my project file size is paramount. Without the interface, un-needed modules and compressing using UPX the resulting .exe size is a mear 750KB's. Ju... | PyQt & Python2.3 | Is there a PyQt3 (Or 4) Windows binary installer for Python 2.3? I've googled around for an hour now but to no avail. Why am I using version 2.3? With my project file size is paramount. Without the interface, un-needed modules and compressing using UPX the resulting .exe size is a mear 750KB's. Just need to add the int... | [
"Python 2.3 is extremely old. You really shouldn't be using it at all. I seriously doubt there's any qt bindings for it that would even compile. Why do you think using python 2.3 will save you so much file size?\nAdding pyqt will probably increase your file size by 10s of megabytes at least. Just use python at leas... | [
3,
0
] | [] | [] | [
"pyqt",
"python",
"python_2.3"
] | stackoverflow_0004588045_pyqt_python_python_2.3.txt |
Q:
Python classes in Java GUI
I am working on Java project with a lot off mathematics. I wonder is possible to put Python classes into Java GUI ( simple part is JTextField to be Python so I don't need parsing string, just call interpreter Python ) ?
A:
You can try out Jython but I've never used it so I can't say if... | Python classes in Java GUI | I am working on Java project with a lot off mathematics. I wonder is possible to put Python classes into Java GUI ( simple part is JTextField to be Python so I don't need parsing string, just call interpreter Python ) ?
| [
"You can try out Jython but I've never used it so I can't say if it works with the java gui stuff. What is it that you're trying to do? Why do you want to use python instead of java? Why can't you just write the entire thing in java?\n"
] | [
1
] | [] | [] | [
"java",
"jython",
"python"
] | stackoverflow_0004588197_java_jython_python.txt |
Q:
Inserting values into a dictionary without just creating a reference
is there a way to insert a dictionary into another dictionary without just creating a reference to the dictionary.e.g
dict_a = {}
dict_b = {}
dict_a.insert(key, value)
this would prevent the problems that come with
dict_a["somekey"] = dict_b
A... | Inserting values into a dictionary without just creating a reference | is there a way to insert a dictionary into another dictionary without just creating a reference to the dictionary.e.g
dict_a = {}
dict_b = {}
dict_a.insert(key, value)
this would prevent the problems that come with
dict_a["somekey"] = dict_b
| [
"You could use copy.deepcopy on b:\n>>> a = {'a':[1,2,3]}\n>>> b = {'b':[4,5,6]}\n>>> a['c'] = copy.deepcopy(b)\n>>> a\n{'a': [1, 2, 3], 'c': {'b': [4, 5, 6]}}\n>>> b\n{'b': [4, 5, 6]}\n>>> b['b'].append(7)\n>>> b\n{'b': [4, 5, 6, 7]}\n>>> a\n{'a': [1, 2, 3], 'c': {'b': [4, 5, 6]}}\n\nUsing update or copy as above ... | [
4,
2,
1,
1,
1
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0004588255_dictionary_python.txt |
Q:
How can/should I break an html document into parts using Python? (Techno- and logically)
I've an HTML document I'm trying to break into separate, smaller chunks. Say, take each < h3 > header and turn into its own separate file, using only the HTML encoded within that chunk (along with html, head, body, tags).
I a... | How can/should I break an html document into parts using Python? (Techno- and logically) | I've an HTML document I'm trying to break into separate, smaller chunks. Say, take each < h3 > header and turn into its own separate file, using only the HTML encoded within that chunk (along with html, head, body, tags).
I am using Python's Beautiful Soup which I am new to, but seems easy to use for easy tasks such a... | [
"Yes, you use BeautifulSoup or lxml. Both have methods to find the nodes you want to extract. You can then also recreate HTML from the node objects, and hence save that HTML to new files.\n"
] | [
2
] | [] | [] | [
"beautifulsoup",
"html",
"python"
] | stackoverflow_0004588345_beautifulsoup_html_python.txt |
Q:
Download files from ASP forms with Python
I am attempting to download a lot of files from http://www.sl.universalservice.org/funding/opendatasearch/Search1.asp using the Python library mechanize. On the site, the user must fill out 2 ASP forms, and then when the user clicks the second submit button, a file downloa... | Download files from ASP forms with Python | I am attempting to download a lot of files from http://www.sl.universalservice.org/funding/opendatasearch/Search1.asp using the Python library mechanize. On the site, the user must fill out 2 ASP forms, and then when the user clicks the second submit button, a file download starts. I was able to get the Python program ... | [
"With b as your browser object:\nb.submit() # The second of the two forms\nc = csv.DictReader(b.response(), dialect='excel-tab')\n\nb.response() gives you access to a file-like object, which can be processed by the csv module.\n"
] | [
1
] | [] | [] | [
"python",
"web_scraping"
] | stackoverflow_0004588011_python_web_scraping.txt |
Q:
ipython from emacs on windows XP, no prompt and no print output
I want to integrate ipython to emacs 23, on windows XP.
I could find quite some information online, but nothing did the trick.
The following is required in my ~/.emacs.d/init.el:
python-mode
pymacs
ipython
pyreadline is also installed.
I launch ipyt... | ipython from emacs on windows XP, no prompt and no print output | I want to integrate ipython to emacs 23, on windows XP.
I could find quite some information online, but nothing did the trick.
The following is required in my ~/.emacs.d/init.el:
python-mode
pymacs
ipython
pyreadline is also installed.
I launch ipython with a bat file (in my system path), with the flags -i and -u.
Th... | [
"Make sure you're using pyreadline 1.6. Version 1.5 writes to the stream using the console API even when run via Emacs. That causes many problems similar to the ones you are seeing.\n",
"I believe that it is the Python interpreter itself and not the ipython script which is to receive the -u parameter, i.e. your f... | [
0,
0
] | [] | [] | [
"emacs",
"ipython",
"python"
] | stackoverflow_0004468935_emacs_ipython_python.txt |
Q:
How do I write a float list of lists to file in Python
I need to write a series of matrices out to a plain text file from python. All my matricies are in float format so the simple
file.write() and file.writelines()
do not work. Is there a conversion method I can employ that doesn't have me looping through all ... | How do I write a float list of lists to file in Python | I need to write a series of matrices out to a plain text file from python. All my matricies are in float format so the simple
file.write() and file.writelines()
do not work. Is there a conversion method I can employ that doesn't have me looping through all the lists (matrix = list of lists in my case) converting the... | [
"m = [[1.1, 2.1, 3.1], [4.1, 5.1, 6.1], [7.1, 8.1, 9.1]]\nfile.write(str(m))\n\nIf you want more control over the format of each value:\ndef format(value):\n return \"%.3f\" % value\n\nformatted = [[format(v) for v in r] for r in m]\nfile.write(str(formatted))\n\n",
"the following works for me:\nwith open(fnam... | [
17,
11,
5,
2,
1
] | [] | [] | [
"file_io",
"python"
] | stackoverflow_0000864883_file_io_python.txt |
Q:
Python objects confusion: a=b, modify b and a changes!
I thought i knew Python until tonight. What is the correct way to do something like this? Here's my code:
a = ["one", "two", "three"]
b = a # here I want a complete copy that when b is changed, has absolutely no effect on a
b.append["four"]
print a # a now h... | Python objects confusion: a=b, modify b and a changes! | I thought i knew Python until tonight. What is the correct way to do something like this? Here's my code:
a = ["one", "two", "three"]
b = a # here I want a complete copy that when b is changed, has absolutely no effect on a
b.append["four"]
print a # a now has "four" in it
Basically i want to know, instead of the b ... | [
"What you are experiencing is the concept of references. All objects in Python have a reference and when you assign one to two names a and b, this results in both a and b pointing to the same object.\n>>> a = range(3)\n>>> b = a # same object\n>>> b.append(3)\n>>> a, b # sam... | [
17,
1,
1
] | [] | [] | [
"python",
"reference",
"variables"
] | stackoverflow_0004588100_python_reference_variables.txt |
Q:
evaluating buffer in emacs python-mode on remote host
I'm using emacs23 with tramp to modify python scripts on a remote host.
I found that when I start the python shell within emacs it starts up
python on the remote host.
My problem is that when I then try to call python-send-buffer via C-c C-c it comes up with ... | evaluating buffer in emacs python-mode on remote host | I'm using emacs23 with tramp to modify python scripts on a remote host.
I found that when I start the python shell within emacs it starts up
python on the remote host.
My problem is that when I then try to call python-send-buffer via C-c C-c it comes up with the error
Traceback (most recent call last):
File "", ... | [
"I'm currently trying to to get my unregistered question merged with this account, after which I'll be able to accept eichin's answer and edit my post to include my solution.\nI followed eichin's suggestion and copied the emacs2.py emacs3.py and emacs.py files to the remote host and added their directory to PYTHONP... | [
3,
2
] | [] | [] | [
"emacs",
"python"
] | stackoverflow_0004465615_emacs_python.txt |
Q:
Windows XP , Python 2.7 and Pygame
How can I make pygame work with Python 2.7 under Windows XP?
I think I need to compile it, but I'm not sure.
Thank you.
A:
Try the pygame-1.9.2pre.win32-py2.7 installer from http://www.lfd.uci.edu/~gohlke/pythonlibs/#pygame
| Windows XP , Python 2.7 and Pygame | How can I make pygame work with Python 2.7 under Windows XP?
I think I need to compile it, but I'm not sure.
Thank you.
| [
"Try the pygame-1.9.2pre.win32-py2.7 installer from http://www.lfd.uci.edu/~gohlke/pythonlibs/#pygame\n"
] | [
7
] | [] | [] | [
"pygame",
"python",
"python_2.7",
"windows_xp"
] | stackoverflow_0004587018_pygame_python_python_2.7_windows_xp.txt |
Q:
Obfuscating Strings with ASCII and base 128
Suppose a string is a number system where each thing, it can be a char, DEL or any ASCII thing, has a corresponding number according to this ASCII table. How can you convert arbitrary string of the property to number in Python?
An example
#car = 35*128**3+99*128**2+97*12... | Obfuscating Strings with ASCII and base 128 | Suppose a string is a number system where each thing, it can be a char, DEL or any ASCII thing, has a corresponding number according to this ASCII table. How can you convert arbitrary string of the property to number in Python?
An example
#car = 35*128**3+99*128**2+97*128**1+114*128**0=75034866
| [
"Try this:\ntotal = 0\nfor c in \"#car\":\n total <<= 7\n total += ord(c)\nprint total\n\nResult:\n\n75034866\n\nTo get back the original string:\nresult = []\nwhile total:\n result.append(chr(total % 128))\n total >>= 7\nprint ''.join(reversed(result))\n\nResult:\n\n#car\n\n",
"For arbitrarily long n... | [
7,
0,
0
] | [] | [] | [
"ascii",
"encoding",
"obfuscation",
"python"
] | stackoverflow_0004588612_ascii_encoding_obfuscation_python.txt |
Q:
For anyone with free time: Trying to learn how to replace PHP with Python, failing terribly
Possible Duplicate:
Python noob here: On a Python enabled web server, how do I use Python?
I want give web development using Python a shot, but I'm failing hard. I don't even know if I CAN run Python. The webpage for my w... | For anyone with free time: Trying to learn how to replace PHP with Python, failing terribly |
Possible Duplicate:
Python noob here: On a Python enabled web server, how do I use Python?
I want give web development using Python a shot, but I'm failing hard. I don't even know if I CAN run Python. The webpage for my web host says it supports all kinds of stuff, including Python. I've never touched anything CGI r... | [
"Alright, I'm not going to hold your hand, but let me suggest:\n\nStart off by installing and running it on your own computer, if at all possible. This lets you see what you can do with Python before you have to worry about the complexities of setting it up with a webserver.\nIf you've never used Python before, the... | [
4,
0
] | [] | [] | [
"cgi",
"python"
] | stackoverflow_0004588428_cgi_python.txt |
Q:
iPhone calling python functions from server
I have a back end set up with python functions. I want python to do a lot of location based work instead of have objective-c do the computations and everything else. There are reasons for this.
However, I have no idea how to connect to the server and call the python fu... | iPhone calling python functions from server | I have a back end set up with python functions. I want python to do a lot of location based work instead of have objective-c do the computations and everything else. There are reasons for this.
However, I have no idea how to connect to the server and call the python functions from objective-c. Does anyone have any k... | [
"I, too, am using Python on a server (Google App Engine) for one of my projects. I have an endpoint that returns a bunch of data in JSON format. (parseJSON is my own method)\n@interface GSData : NSObject {\nNSMutableData *responseData;\n}\n\n/////////////////////////\n\n// in my .m file\n\n- (void)getData {\n re... | [
3,
2
] | [] | [] | [
"iphone",
"python"
] | stackoverflow_0004586906_iphone_python.txt |
Q:
Django, unobtrusive JavaScript and cross-site scripting
am wondering if there is a manual/tutorial that talks about advance use of JavaScripting and django, using existing frameworks such as JQuery or Prototype, generating unobtrusive JavaScripting with no inline Javascripting.
Another question, is there a place ... | Django, unobtrusive JavaScript and cross-site scripting | am wondering if there is a manual/tutorial that talks about advance use of JavaScripting and django, using existing frameworks such as JQuery or Prototype, generating unobtrusive JavaScripting with no inline Javascripting.
Another question, is there a place where I can read about cross-site scripting and how I can pro... | [
"I think the Security section of The Django Book will get you started.\n"
] | [
1
] | [] | [] | [
"ajax",
"django",
"python"
] | stackoverflow_0004588476_ajax_django_python.txt |
Q:
Python class that inherits from itself? How does this work?
Relatively new to Python, and I saw the following construct in the PyFacebook library (source here: http://github.com/sciyoshi/pyfacebook/blob/master/facebook/init.py#L660). I'm curious what this does because it appears to be a class that inherits from i... | Python class that inherits from itself? How does this work? | Relatively new to Python, and I saw the following construct in the PyFacebook library (source here: http://github.com/sciyoshi/pyfacebook/blob/master/facebook/init.py#L660). I'm curious what this does because it appears to be a class that inherits from itself.
class AuthProxy(AuthProxy):
"""Special proxy for faceb... | [
"The class statement there doesn't make the class inherit from itself, it creates a class object with the current value of AuthProxy as a superclass, and then assigns the class object to the variable 'AuthProxy', presumably overwriting the previously assigned AuthProxy that it inherited from.\nEssentially, it's abo... | [
17,
3,
3,
1
] | [] | [] | [
"eclipse",
"facebook",
"python"
] | stackoverflow_0002078634_eclipse_facebook_python.txt |
Q:
SQLAlchemy equivalent to Django's x.objects.extra()?
I just learned of django's (model).objects.extra() function, as documented:
http://docs.djangoproject.com/en/1.2/ref/models/querysets/#extra
I'm hoping that there is something similar in sqlalchemy. I would like to be able to have the flexibility of raw sql thr... | SQLAlchemy equivalent to Django's x.objects.extra()? | I just learned of django's (model).objects.extra() function, as documented:
http://docs.djangoproject.com/en/1.2/ref/models/querysets/#extra
I'm hoping that there is something similar in sqlalchemy. I would like to be able to have the flexibility of raw sql through the cursor, but still have my results come back throu... | [
"I think you're looking for Query.from_statement: http://www.sqlalchemy.org/docs/orm/query.html#sqlalchemy.orm.query.Query.from_statement\n"
] | [
3
] | [] | [] | [
"django",
"python",
"sql",
"sqlalchemy"
] | stackoverflow_0004588155_django_python_sql_sqlalchemy.txt |
Q:
list comprehension selected indexes
Let's say I have a file like this (pretend it were a matrix):
abcde
fghik
lmnop
I want to put this in a 2d list but with only columns up to index 3:
# 0 1 2 3
[['a','b','c','d'],
['f','g','h','i'],
['l','m','n','o']]
How does one do this using a list comprehension... | list comprehension selected indexes | Let's say I have a file like this (pretend it were a matrix):
abcde
fghik
lmnop
I want to put this in a 2d list but with only columns up to index 3:
# 0 1 2 3
[['a','b','c','d'],
['f','g','h','i'],
['l','m','n','o']]
How does one do this using a list comprehension? I know I could loop, but I'm looking fo... | [
"If I understand the question correctly, this should work (but perhaps I'm over simplifying). Note the [:4] in the inner comprehension:\nf = open('file.txt')\nlines = f.readlines()\nmatrix = [[a for a in b[:4]] for b in lines] # this gets all columns, up to 4\n\n",
"Slice each line up to the 3th column: matrix = ... | [
7,
3,
2
] | [] | [] | [
"list_comprehension",
"matrix",
"python"
] | stackoverflow_0004589310_list_comprehension_matrix_python.txt |
Q:
Partial Upload With storbinary in python
I've written some python code to download an image using
urllib.urlopen().read()
and then upload it to an FTP site using
ftplib.FTP().storbinary()
but I'm having a problem. Sometimes the image file is only partially uploaded, so I get images with the bottom 20% or so cu... | Partial Upload With storbinary in python | I've written some python code to download an image using
urllib.urlopen().read()
and then upload it to an FTP site using
ftplib.FTP().storbinary()
but I'm having a problem. Sometimes the image file is only partially uploaded, so I get images with the bottom 20% or so cut off. I've checked the locally downloaded ver... | [
"It turns out I was not closing the downloaded file correctly. Let's all pretend this never happened.\n",
"It's been a while since I looked at this code, but I remember the crux of it was that I was not closing the downloaded file correctly. I have the working code though, so just in case it was a problem with th... | [
0,
0
] | [] | [] | [
"ftp",
"ftplib",
"python"
] | stackoverflow_0000670084_ftp_ftplib_python.txt |
Q:
Passing variables to template based on db
I am trying to add a feature to my app that would allow me to enable/disable the "Call Me" button based on whether or not I am at [home|the office]. I created a model in the database called setting, it looks like this:
class setting(models.Model):
key = models.CharFie... | Passing variables to template based on db | I am trying to add a feature to my app that would allow me to enable/disable the "Call Me" button based on whether or not I am at [home|the office]. I created a model in the database called setting, it looks like this:
class setting(models.Model):
key = models.CharField(max_length=200)
value = models.CharField... | [
"Write a custom context processor.\n"
] | [
4
] | [] | [] | [
"django",
"django_templates",
"python"
] | stackoverflow_0004589499_django_django_templates_python.txt |
Q:
Is there a way to use readability (text extraction algorithm) and a custom algorithm in python to extract links from text?
Is there a way to use readability (text extraction algorithm) and a custom algorithm in python to extract links from text?
I'd like to figure out a way of extracting links that are in the body... | Is there a way to use readability (text extraction algorithm) and a custom algorithm in python to extract links from text? | Is there a way to use readability (text extraction algorithm) and a custom algorithm in python to extract links from text?
I'd like to figure out a way of extracting links that are in the body of text.
1.) I use readability in python https://github.com/gfxmonk/python-readability
2.) I'd like to somehow compare the extr... | [
"Well, it looks like it returns a BeautifulSoup tree. So you should be able to do something like:\narticle = page.summary() # Extract article using readability\narticle.findAll(\"a\") # Return a list of all links in the article\n\n"
] | [
2
] | [] | [] | [
"html_content_extraction",
"python",
"text_extraction"
] | stackoverflow_0004589323_html_content_extraction_python_text_extraction.txt |
Q:
Python - urllib2 & cookielib
I am trying to open the following website and retrieve the initial cookie and use it for the second url-open BUT if you run the following code it outputs 2 different cookies. How do I use the initial cookie for the second url-open?
import cookielib, urllib2
cj = cookielib.CookieJar()
... | Python - urllib2 & cookielib | I am trying to open the following website and retrieve the initial cookie and use it for the second url-open BUT if you run the following code it outputs 2 different cookies. How do I use the initial cookie for the second url-open?
import cookielib, urllib2
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urll... | [
"This is not a problem with urllib. That site does some funky stuff. You need to request a couple of stylesheets for it to validate your session id:\nimport cookielib, urllib2\n\ncj = cookielib.CookieJar()\nopener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))\n# default User-Agent ('Python-urllib/2.6') wi... | [
21,
7,
0
] | [] | [] | [
"cookielib",
"python",
"urllib2"
] | stackoverflow_0004582964_cookielib_python_urllib2.txt |
Q:
How Do I Create a Python / Django Egg?
I have a Python program (with Django - does this matter?) that I want to 'bundle', if you like. How do I do this, in the same way one can create a .jar for Java?
A:
You want to use the Python SetupTools. You create a description file (setup.py) and then building and creat... | How Do I Create a Python / Django Egg? | I have a Python program (with Django - does this matter?) that I want to 'bundle', if you like. How do I do this, in the same way one can create a .jar for Java?
| [
"You want to use the Python SetupTools. You create a description file (setup.py) and then building and creating the egg is a one-line command (similar to Make). \nThere was a nice presentation that would walk you through the details -- it's gone now. So here's another discussion.\n",
"DjangoSkel is the way to ... | [
5,
2
] | [] | [] | [
"django",
"egg",
"python"
] | stackoverflow_0001650314_django_egg_python.txt |
Q:
Amazon Book API for Python or Ruby?
Possible Duplicate:
Amazon API library for Python?
I'm looking for an Amazon API that will allow me to:
Find books by title or author
Show book covers
Get information about each book (price, rating, number of reviews, format, number of pages, etc.)
Either a Python or Ruby li... | Amazon Book API for Python or Ruby? |
Possible Duplicate:
Amazon API library for Python?
I'm looking for an Amazon API that will allow me to:
Find books by title or author
Show book covers
Get information about each book (price, rating, number of reviews, format, number of pages, etc.)
Either a Python or Ruby library would be fine (I just want the lib... | [
"I think I found a couple of options for you. \nThe Ruby option:\nThe library provides support for the vast majority of the AWS v3.1 API. For example, all forms of product search are implemented, along with the transaction details API and the remote shopping-cart API. Furthermore, advanced features such as threaded... | [
8,
4
] | [] | [] | [
"amazon",
"amazon_product_api",
"python",
"ruby"
] | stackoverflow_0004589813_amazon_amazon_product_api_python_ruby.txt |
Q:
Python: how to input python-code part like \input in Tex?
I want to input code in Python like \input{Sources/file.tex}. How can I do it in Python?
[added]
Suppose I want to input data to: print("My data is here"+<input data here>).
Data
1, 3, 5, 5, 6
A:
The built-in execfile function does what you ask, for examp... | Python: how to input python-code part like \input in Tex? | I want to input code in Python like \input{Sources/file.tex}. How can I do it in Python?
[added]
Suppose I want to input data to: print("My data is here"+<input data here>).
Data
1, 3, 5, 5, 6
| [
"The built-in execfile function does what you ask, for example:\nfilename = \"Sources/file.py\"\nexecfile( filename )\n\nThis will execute the code from Sources/file.py almost as if that code were embedded in the current file, and is thus very similar to #include in C or \\input in LaTeX.\nNote that execfile also p... | [
4,
2,
0,
0
] | [] | [] | [
"input",
"python"
] | stackoverflow_0002682799_input_python.txt |
Q:
Recursive expressions with pyparsing
I'm trying to figure out how to do a left-associative expression where recursive (not-enclosed in anything) expressions are possible. For example, I'd like to do:
expr + OP + expr
that parses 2 operations like 1 x 2 x 3 into (expr OP expr) OP expr result.
If I try to prevent e... | Recursive expressions with pyparsing | I'm trying to figure out how to do a left-associative expression where recursive (not-enclosed in anything) expressions are possible. For example, I'd like to do:
expr + OP + expr
that parses 2 operations like 1 x 2 x 3 into (expr OP expr) OP expr result.
If I try to prevent expr parsing from infinite recursion, i can... | [
"Here is an example parse action that will take the flat lists of tokens and nest them as if parsed left-recursively:\nfrom pyparsing import *\n\n# parse action -maker\ndef makeLRlike(numterms):\n if numterms is None:\n # None operator can only by binary op\n initlen = 2\n incr = 1\n else... | [
8,
1
] | [] | [] | [
"associativity",
"parsing",
"pyparsing",
"python"
] | stackoverflow_0004571441_associativity_parsing_pyparsing_python.txt |
Q:
Python noob here: On a Python enabled web server, how do I use Python?
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# enable debugging
import cgitb
cgitb.enable()
print "Content-Type: text/plain;charset=utf-8"
print
print "Hello World!"
My goal is to replace PHP with Python. I'm pretty good with PHP and I ca... | Python noob here: On a Python enabled web server, how do I use Python? | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
# enable debugging
import cgitb
cgitb.enable()
print "Content-Type: text/plain;charset=utf-8"
print
print "Hello World!"
My goal is to replace PHP with Python. I'm pretty good with PHP and I can use Python on my own local machine, but I can't get it to work on my web s... | [
"That's a perfectly acceptable CGI script. If you are using Apache, it will need to go into your cgi-bin, need to be executable (I may be wrong on this), and you should name it with the common extension for the language .py, or with .cgi.\nIf you can control what files your webserver will consider CGI, you can plac... | [
7,
2,
0
] | [] | [] | [
"cgi",
"python"
] | stackoverflow_0004587416_cgi_python.txt |
Q:
How do you handle extremely large values in python?
How would I get python to work with values of the order of magnitude of 1099511627776 bits large (yeah. 137 gb)? I some what need to implement this (or if you can suggest a better way to do it, will change methods). apparently, pgp's new length types have 3 secti... | How do you handle extremely large values in python? | How would I get python to work with values of the order of magnitude of 1099511627776 bits large (yeah. 137 gb)? I some what need to implement this (or if you can suggest a better way to do it, will change methods). apparently, pgp's new length types have 3 sections instead of 2. now they are: length type, value-of-len... | [
"It's not only to big to fit in a long, it's too big to fit in the memory of any computer. I think you misunderstood something.\nAs I understand it, the largest key value is 4,294,967,295 bytes. That's 4GB, not 137 GB. You hold that key in memory not as one number, but as a string of bytes. So I don't know where yo... | [
2,
1,
1,
0
] | [] | [] | [
"int",
"long_integer",
"math",
"openpgp",
"python"
] | stackoverflow_0004582567_int_long_integer_math_openpgp_python.txt |
Q:
tipfy on Google App Engine (GAE) installing extensions
I'm trying to get tipfy working on Google App Engine (GAE). I'm using Windows XP.
The "hello world" example is working fine. What I'm don't understand is how to correctly install extensions.
I'm trying to use the "multi-auth" example without much success.
I'm... | tipfy on Google App Engine (GAE) installing extensions | I'm trying to get tipfy working on Google App Engine (GAE). I'm using Windows XP.
The "hello world" example is working fine. What I'm don't understand is how to correctly install extensions.
I'm trying to use the "multi-auth" example without much success.
I'm receiving the following error:
ImportError: No module named... | [
"You should run bin/buildout from the dir where buildout.cfg is sitting, not from the bin dir.\nDo something like this\ncd D:\\downloads\\tipfy.0.6.3.build\\project\nstart bin/buildout\n\n",
"bootstrap and buildout problems are caused by broken distribution in version 0.6.3 IMHO. It is better to use all-in-one pa... | [
4,
1
] | [] | [] | [
"google_app_engine",
"python",
"tipfy"
] | stackoverflow_0003684493_google_app_engine_python_tipfy.txt |
Q:
Problem with validating ModelForm
I use ModelForm to create my form. All works fine except 1 thing - validating the unique field.
Code:
class Article(models.Model):
...
title = models.CharField(max_length=255, unique=True, error_messages={'max_length' : 'max translation',
... | Problem with validating ModelForm | I use ModelForm to create my form. All works fine except 1 thing - validating the unique field.
Code:
class Article(models.Model):
...
title = models.CharField(max_length=255, unique=True, error_messages={'max_length' : 'max translation',
... | [
"There's no unique key for customizing validation messages. I'd say it's not worth it to customize, but if you must, following approach should help:\nimport re\nclass ArticleForm(ModelForm):\n def clean(self, *args, **kwargs):\n result = super(ArticleForm, self).clean(*args, **kwargs)\n if self.non_... | [
1
] | [] | [] | [
"django",
"forms",
"modelform",
"python"
] | stackoverflow_0004587431_django_forms_modelform_python.txt |
Q:
use Python to call ImageMagick's "import"
I want to capture a screenshot of an application's window from a Python script using ImageMagick, as I would with ImageMagick's "import" command from a shell. An API call or a system call from Python (as in "subprocess.Popen(["import"...") will suffice, but I don't want to... | use Python to call ImageMagick's "import" | I want to capture a screenshot of an application's window from a Python script using ImageMagick, as I would with ImageMagick's "import" command from a shell. An API call or a system call from Python (as in "subprocess.Popen(["import"...") will suffice, but I don't want to create a file on the hard drive. My OS is Linu... | [
"Execute the command:\nimport png:-\n\nThis will cause import to output to stdout.\nYou can also change png to one of the type tags shown here.\n"
] | [
2
] | [] | [] | [
"imagemagick",
"python"
] | stackoverflow_0004590088_imagemagick_python.txt |
Q:
Hadoop Streaming: Mapper 'wrapping' a binary executable
I have a pipeline that I currently run on a large university computer cluster. For publication purposes I'd like to convert it into mapreduce format such that it could be run by anyone on using a hadoop cluster such as amazon webservices (AWS). The pipeline... | Hadoop Streaming: Mapper 'wrapping' a binary executable | I have a pipeline that I currently run on a large university computer cluster. For publication purposes I'd like to convert it into mapreduce format such that it could be run by anyone on using a hadoop cluster such as amazon webservices (AWS). The pipeline currently consists of as series of python scripts that wrap ... | [
"After much googling (etc.) I figured out how to include executable binaries/scripts/modules that are accessible to your mappers/reducers. The trick is to upload all you files to hadoop first. \n$ bin/hadoop dfs -copyFromLocal /local/file/system/module.py module.py\n\nThen you need to format you streaming command l... | [
4,
2
] | [] | [] | [
"binary",
"hadoop",
"mapreduce",
"python",
"streaming"
] | stackoverflow_0004113798_binary_hadoop_mapreduce_python_streaming.txt |
Q:
What is the equivalent of ruby's string inspect() in python
I apologize up front for the dumbness of this question, but I can't figure it out and its driving me crazy.
In ruby I can do:
irb(main):001:0> s = "\t\t\n"
=> "\t\t\n"
irb(main):003:0> puts s
=> nil
irb(main):004:0> puts s.inspect
"\t\t\n"
I... | What is the equivalent of ruby's string inspect() in python | I apologize up front for the dumbness of this question, but I can't figure it out and its driving me crazy.
In ruby I can do:
irb(main):001:0> s = "\t\t\n"
=> "\t\t\n"
irb(main):003:0> puts s
=> nil
irb(main):004:0> puts s.inspect
"\t\t\n"
Is there an equivalent of ruby's inspect function in python?
| [
"repr():\n>>> print repr('\\t\\t\\n')\n'\\t\\t\\n'\n\n",
"You can use repr or (backticks), I am doing the exactly the same things as you did above.\n>>> s = \"\\t\\t\\n\"\n>>> s\n'\\t\\t\\n'\n>>> print s\n\n\n>>> repr(s)\n\"'\\\\t\\\\t\\\\n'\"\n>>> print repr(s)\n'\\t\\t\\n'\n>>> print `s`\n'\\t\\t\\n'\n\n"
] | [
12,
4
] | [] | [] | [
"python",
"ruby",
"string"
] | stackoverflow_0004589696_python_ruby_string.txt |
Q:
Transferring files from user's computer to different server without going through GAE
I'm writing a GAE app in Python that adds user accounts and other services to a third-party data processing service that communicates by SOAP. While using my app, the user sets some parameters, which I want to store in the app's ... | Transferring files from user's computer to different server without going through GAE | I'm writing a GAE app in Python that adds user accounts and other services to a third-party data processing service that communicates by SOAP. While using my app, the user sets some parameters, which I want to store in the app's database. The user may also upload large data files, which I don't want to store, since it ... | [
"You can upload form data to a third-party server, but you'll need to use HTML5 APIs that aren't widely available in yet since the standards aren't finalized.\nThe APIs you'll want to look at are:\n\nXHR2, to do the actual upload. This is an extension of the widely-available XHR API. You'll probably want the Form... | [
0
] | [] | [] | [
"file_upload",
"google_app_engine",
"python"
] | stackoverflow_0004589915_file_upload_google_app_engine_python.txt |
Q:
Pass errors in Django using HttpResponseRedirect
I know that HttpResponseRedirect only takes one parameter, a URL. But there are cases when I want to redirect with an error message to display.
I was reading this post: How to pass information using an HTTP redirect (in Django) and there were a lot of good suggesti... | Pass errors in Django using HttpResponseRedirect | I know that HttpResponseRedirect only takes one parameter, a URL. But there are cases when I want to redirect with an error message to display.
I was reading this post: How to pass information using an HTTP redirect (in Django) and there were a lot of good suggestions. I don't really want to use a library that I don'... | [
"You are right about the auth messages. They are deprecated but as the docs suggest you should use the django messages framework instead, which I think is the exact soultion for your case.\n"
] | [
10
] | [] | [] | [
"django",
"django_sessions",
"python"
] | stackoverflow_0004590149_django_django_sessions_python.txt |
Q:
_sha import in python hashlib
Well, today I was checking the hashlib module in python, but then I found something that I still can't figure out.
Inside this python module, there is an import that I can't follow. I goes like this:
def __get_builtin_constructor(name):
if name in ('SHA1', 'sha1'):
import ... | _sha import in python hashlib | Well, today I was checking the hashlib module in python, but then I found something that I still can't figure out.
Inside this python module, there is an import that I can't follow. I goes like this:
def __get_builtin_constructor(name):
if name in ('SHA1', 'sha1'):
import _sha
return _sha.new
I tri... | [
"Actually, the _sha module is provided by shamodule.c and _md5 is provided by md5module.c and md5.c and both will be built only when your Python is not compiled with OpenSSL by default.\nYou can find the details in setup.py in your Python Source tarball.\n if COMPILED_WITH_PYDEBUG or not have_usable_openssl:\n ... | [
9,
5
] | [] | [] | [
"hashlib",
"python"
] | stackoverflow_0004590242_hashlib_python.txt |
Q:
running python script with cron
hey guys, im trying to run a python script after every 5 minutes using cron, inside the script is a django import
import django
when running the crontab i get mailed the following error
ImportError: No module named django
this is what the crontab file looks like:
MAILTO=commonzen... | running python script with cron | hey guys, im trying to run a python script after every 5 minutes using cron, inside the script is a django import
import django
when running the crontab i get mailed the following error
ImportError: No module named django
this is what the crontab file looks like:
MAILTO=commonzenpython@gmail.com
*/5 * * * * /usr/b... | [
"I want to addd one point to @Hank's answer.\ncron doesn't have all the environment variables set as in the shell you use. Only LOGNAME, HOME, and SHELL are defined. (You can refer to \"man 5 crontab\" for more info.)\nYou can define PYTHONPATH environment variable in cron just as the way you defined MAILTO. So no ... | [
5,
2,
1,
1
] | [] | [] | [
"cron",
"crontab",
"django",
"linux",
"python"
] | stackoverflow_0004581768_cron_crontab_django_linux_python.txt |
Q:
Valid SOAP call not working in Python SUDS
Trying to place SOAP calls to Cisco AXL interface using Python with SUDS.
Have the following test code:
from suds.client import Client
from suds.sax.element import Element
wsdl = 'file:///C://Cisco//axlsqltoolkit//schema//8.0//AXLAPI.wsdl'
client = Client(wsdl,username='a... | Valid SOAP call not working in Python SUDS | Trying to place SOAP calls to Cisco AXL interface using Python with SUDS.
Have the following test code:
from suds.client import Client
from suds.sax.element import Element
wsdl = 'file:///C://Cisco//axlsqltoolkit//schema//8.0//AXLAPI.wsdl'
client = Client(wsdl,username='administrator',password='ABC123')
regionName = El... | [
"Your CUCM's publisher IP/hostname is not in the WSDL, so you will need to specify it in your client.\nfrom suds.client import Client\nfrom suds.sax.element import Element\nwsdl = 'file:///C://Cisco//axlsqltoolkit//schema//8.0//AXLAPI.wsdl'\nclient = Client(wsdl, location=\"https://yourpublisher:8443/axl/\",\n ... | [
0
] | [] | [] | [
"python",
"soap",
"suds"
] | stackoverflow_0004578802_python_soap_suds.txt |
Q:
Intersect a list of dicts based on a common key
Let's say I have two list of dicts:
dates = [{'created':'2010-12-01'},{'created':'2010-12-02'},....]
elts = [{'created':'2010-12-01', 'key1':'val1', 'key2':'val2'}, {'created':'2010-12-05','key1':'val1'}]
The dates list is a bunch of contiguous dates.
The elts list ... | Intersect a list of dicts based on a common key | Let's say I have two list of dicts:
dates = [{'created':'2010-12-01'},{'created':'2010-12-02'},....]
elts = [{'created':'2010-12-01', 'key1':'val1', 'key2':'val2'}, {'created':'2010-12-05','key1':'val1'}]
The dates list is a bunch of contiguous dates.
The elts list can be anywhere from 1 to len(dates), and what I want... | [
"Your question is a little off, I think, since your solution doesn't seem to actually address your question, but if you wanted to create an entry in elts for every date in dates that does not already appear in elts, you could use this:\nall_dates = set(e['created'] for e in dates) # gets a list of all dates that ex... | [
3,
2,
1,
0
] | [] | [] | [
"intersection",
"list",
"python"
] | stackoverflow_0004588952_intersection_list_python.txt |
Q:
Export a jQuery div as a picture
I found a very nice jQuery polaroid running in a div.
Is it possible to save the result in a single image? What library should I use? I am using Java, JavaScript and Python. Is there a library for those languages?
A:
It's not quite clear how you want to use this. A couple of use ... | Export a jQuery div as a picture | I found a very nice jQuery polaroid running in a div.
Is it possible to save the result in a single image? What library should I use? I am using Java, JavaScript and Python. Is there a library for those languages?
| [
"It's not quite clear how you want to use this. A couple of use cases come to mind:\n\nOccasionally, in your own browser. Use Windows screen capture (Alt-printscreen), paste into a graphics editor (Paint.NET), and crop.\nOften, in your own browser. Install a browser plugin like IECapt http://iecapt.sourceforge.net/... | [
1
] | [] | [] | [
"java",
"javascript",
"python"
] | stackoverflow_0004588704_java_javascript_python.txt |
Q:
Creating an edit form from model containing Foreignkey?
I am creating an app, where I am storing employee's complete information, now the problem with my development is that I am entering dependents of the employee in a manner that the Person which he adds as a dependent gets a entry in the Person model.
Dependent... | Creating an edit form from model containing Foreignkey? | I am creating an app, where I am storing employee's complete information, now the problem with my development is that I am entering dependents of the employee in a manner that the Person which he adds as a dependent gets a entry in the Person model.
Dependent and DependentRelationship Model Look Like:
class Dependent(P... | [
"@login_required\ndef edit_dependents(request, id):\nemployee = request.user.get_profile() \ntry:\n dependent = employee.dependent.get(id=id)\nexcept Dependent.DoesNotExist:\n messages.error(request, \"You can't edit this dependent(id: %s).\" %id)\n return HttpResponseRedirect(reverse('core_show_dependent_... | [
0
] | [] | [] | [
"django",
"django_forms",
"python"
] | stackoverflow_0004570065_django_django_forms_python.txt |
Q:
How do I create a M2Crypto DSA object given parameters and key values?
Using M2Crypto I'd like to create a DSA_pub object for verifying a DSA signature. I know q, p, g, and the public key, but the only way I know to instantiate a DSA object is using:
dsa = DSA.set_params(q,p,g)
dsa.gen_key()
How do I assign the ... | How do I create a M2Crypto DSA object given parameters and key values? | Using M2Crypto I'd like to create a DSA_pub object for verifying a DSA signature. I know q, p, g, and the public key, but the only way I know to instantiate a DSA object is using:
dsa = DSA.set_params(q,p,g)
dsa.gen_key()
How do I assign the known public key?
| [
"I just ran across exactly this challenge, where I have the P, Q, G and Y parameters (in my case from an XML document), but M2Crypto does not have a way for me to create a valid public key from them.\nI resorted to using pyasn1 to produce a PEM public key string, then loading that PEM public key using the M2Crypto.... | [
2,
1,
0
] | [] | [] | [
"m2crypto",
"python"
] | stackoverflow_0003027196_m2crypto_python.txt |
Q:
Establishing bluetooth connection between a J2ME application and a desktop application written with Python (preferably using pybluez)?
I am trying to establish a bluetooth connection between my J2ME application (using JSR-082 API) and my desktop application written with Python (using pybluez bluetooth API). Howeve... | Establishing bluetooth connection between a J2ME application and a desktop application written with Python (preferably using pybluez)? | I am trying to establish a bluetooth connection between my J2ME application (using JSR-082 API) and my desktop application written with Python (using pybluez bluetooth API). However, I could not find a suitable bluetooth communication protocols to pair them.
In pybluez, the way you connect to a server is as follows:
ad... | [
"Using JSR-82, you create a server based on a UUID. You need to perform an SDP search to determine the \"port\" (actually, channel number for RFCOMM or PSM for L2CAP) of the remote service. So, in pybluez, you'd call bluetooth.find_service() (as shown here), examine each of the services returned, and pick the one... | [
1
] | [] | [] | [
"bluetooth",
"java",
"java_me",
"jsr82",
"python"
] | stackoverflow_0003573571_bluetooth_java_java_me_jsr82_python.txt |
Q:
How do I get the ID of an object after persisting it in PyMongo?
I have a PyMongo newbie question: If collection is a PyMongo Collection and I use it to save an object with
obj = {'foo': 'bar'}
collection.insert(obj)
then MongoDB automatically generates an _id field for obj; once can confirm this with
print obj
... | How do I get the ID of an object after persisting it in PyMongo? | I have a PyMongo newbie question: If collection is a PyMongo Collection and I use it to save an object with
obj = {'foo': 'bar'}
collection.insert(obj)
then MongoDB automatically generates an _id field for obj; once can confirm this with
print obj
which yields something like
{'foo': 'bar', '_id': ObjectId('4c2fea1d28... | [
"You just need to pass remove a dict, just like you did insert. So, to remove a document based on its _id value, do something like:\ncollection.remove({'_id': ObjectId('4c2fea1d289c7d837e000000')})\n\n",
"insert returns the _id of the inserted document.\nand remove will remove based on _id, so try something like... | [
12,
3,
1
] | [
"for removing a object from document you have to mention condition \nAs you can specify \"_id\" for a document ........ \n_id = db.test.insert({\"foo\": \"test\"})\ndb.test.remove({\"_id\":_id})\n\n"
] | [
-1
] | [
"mongodb",
"pymongo",
"python"
] | stackoverflow_0003089067_mongodb_pymongo_python.txt |
Q:
question about managing values with multiple subvalues in python 3k
I have a question reguarding how I would perform the following task in python.
(I use python 3k)
what I have are several variables which can yield further variables on top of those
and each of those have even more variables
for example:
a generic ... | question about managing values with multiple subvalues in python 3k | I have a question reguarding how I would perform the following task in python.
(I use python 3k)
what I have are several variables which can yield further variables on top of those
and each of those have even more variables
for example:
a generic name would be
item_version_type =
where each part (item, version, and ty... | [
"Grouping of data like this can be done in three ways in Python.\nFirst way is tuples:\nmyvariable = ('Sammalamma', 1, 'Text')\n\nThe second way is a dictionary:\nmyvariable = {'value': 'Sammalamma', 'version': 1, 'type': 'Text'}\n\nAnd the third way is a class:\n class MyClass(object):\n def __init__(self, val... | [
3,
1,
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0004591157_python_python_3.x.txt |
Q:
google app engine python download file
I am trying to figure out a way where I can create a tab-delimited file containing data from user-defined fields and allow the user to download that file on google app engine.
The sandbox environment that the app runs in does not allow the application to write to disk. Is th... | google app engine python download file | I am trying to figure out a way where I can create a tab-delimited file containing data from user-defined fields and allow the user to download that file on google app engine.
The sandbox environment that the app runs in does not allow the application to write to disk. Is there another way where I can create a downloa... | [
"Sure there is! You can output your data as csv, for instance. All you need to do is to change the Content-Type header.\nIt's something like this:\nclass Test(webapp.RequestHandler):\n def get(self, upload_type):\n self.response.headers['Content-Type'] = 'text/csv'\n self.response.out.write(','.joi... | [
27,
20
] | [] | [] | [
"download",
"google_app_engine",
"python"
] | stackoverflow_0002767910_download_google_app_engine_python.txt |
Q:
Piped commands in paramiko
How do I run piped commands in paramiko? I'm doing this:
statement = 'grep thing file | grep thing2 | tail -1'
last_msg = conn.execute(statement)
and I get the output of grep thing file only.
A:
Because grep doesn't know how to handle |. Get ready for some nasty escaping:
statement = ... | Piped commands in paramiko | How do I run piped commands in paramiko? I'm doing this:
statement = 'grep thing file | grep thing2 | tail -1'
last_msg = conn.execute(statement)
and I get the output of grep thing file only.
| [
"Because grep doesn't know how to handle |. Get ready for some nasty escaping:\nstatement = \"\"\"sh -c 'grep thing file | grep thing2 | tail -1'\"\"\"\n\nThis creates a shell on the other side, and asks it to interpret the string grep thing file | grep thing2 | tail -1. The single quotes are necessary since sh -c ... | [
9
] | [] | [] | [
"grep",
"paramiko",
"pipe",
"python"
] | stackoverflow_0004592020_grep_paramiko_pipe_python.txt |
Q:
Versions of Python
I need to write Python compliant with 2.5.1. I currently have Python 3.1 on my machine. If I make a PyDev project and set the grammar to "2.5", will the code I write be compatible (both syntactically and semantically)? Or must I go download an older version of Python?
A:
Python 3 is not backwa... | Versions of Python | I need to write Python compliant with 2.5.1. I currently have Python 3.1 on my machine. If I make a PyDev project and set the grammar to "2.5", will the code I write be compatible (both syntactically and semantically)? Or must I go download an older version of Python?
| [
"Python 3 is not backwards-compatible with Python 2, so you do need to download and install Python 2.5 if you want to write compatible code.\n",
"PyDev's grammar setting only changes the syntax highlighting. To know if your code works you must run it with Python 2.5, so yes you must download it.\n",
"I think it... | [
3,
3,
1
] | [] | [] | [
"pydev",
"python",
"python_3.x"
] | stackoverflow_0004591996_pydev_python_python_3.x.txt |
Q:
How to launch another program in GUI (python tkinter)
i wrote a simple GUI using Python Tkinter. When i click a button it launches another program. But the GUI window stays there waiting for the the program to exit. I want the GUI to launch the program on Button1 and I can click on Button2 to run the test. I used ... | How to launch another program in GUI (python tkinter) | i wrote a simple GUI using Python Tkinter. When i click a button it launches another program. But the GUI window stays there waiting for the the program to exit. I want the GUI to launch the program on Button1 and I can click on Button2 to run the test. I used os.system() to launch the program. Pls advise.
thanks
maxim... | [
"Yes, os.system() will wait.\nAs the documentation for os.system() points out, you might want to replace it by using the subprocess module, where there are many different ways to start commands and where you can choose if you want to wait for it to finish or not.\n"
] | [
1
] | [] | [] | [
"background",
"process",
"python",
"user_interface"
] | stackoverflow_0004591941_background_process_python_user_interface.txt |
Q:
How can I capture all of the python log records generated during the execution of a series of Celery tasks?
I want to convert my homegrown task queue system into a Celery-based task queue, but one feature I currently have is causing me some distress.
Right now, my task queue operates very coarsely; I run the job (... | How can I capture all of the python log records generated during the execution of a series of Celery tasks? | I want to convert my homegrown task queue system into a Celery-based task queue, but one feature I currently have is causing me some distress.
Right now, my task queue operates very coarsely; I run the job (which generates data and uploads it to another server), collect the logging using a variant on Nose's log capture... | [
"I assume you are using logging module. You can use separate named logger per task set to do the job. They will inherit all configuration from upper level.\nin task.py:\nimport logging\n\n@task\nstep1(*args, **kwargs):\n # `key` is some unique identifier common for a piece of data in all steps of processing\n ... | [
1,
0,
0
] | [] | [] | [
"celery",
"logging",
"message_queue",
"python",
"task"
] | stackoverflow_0004158758_celery_logging_message_queue_python_task.txt |
Q:
django need help in writing custom field
I'm aware that Django do not have a built in model field for postgresql 's custom type "text[]".
After looking at the docs, I'm have a question.
I realized I need to override the db_type method to reflect the 'text[]' data type, but is that all? What do I need to write for ... | django need help in writing custom field | I'm aware that Django do not have a built in model field for postgresql 's custom type "text[]".
After looking at the docs, I'm have a question.
I realized I need to override the db_type method to reflect the 'text[]' data type, but is that all? What do I need to write for the to_python method? I mean, the default valu... | [
"to_python should mapp the database values to a python objects. For example for DateTimeFieldto_pythonturns databasetimestampinto pythonsdatatetime` objects.\n"
] | [
0
] | [] | [] | [
"django",
"psycopg2",
"python"
] | stackoverflow_0004592666_django_psycopg2_python.txt |
Q:
Where is a good source of documentation for Pylons web framework?
The documentation at http://pylonshq.com/docs/ seems quite out of date (as of January 2nd, 2011) and does not seem to be updated with any frequency. Are there other good resources for where to find information about best practices with Pylons, examp... | Where is a good source of documentation for Pylons web framework? | The documentation at http://pylonshq.com/docs/ seems quite out of date (as of January 2nd, 2011) and does not seem to be updated with any frequency. Are there other good resources for where to find information about best practices with Pylons, examples with Pylons, etc?
| [
"Are you just starting to use Pylons? In that case you might want to switch to Pyramid, which is \"Pylons 2\", so to speak. It's very well documented. (Although the site is currently down.) http://docs.pylonshq.com/pyramid/ But if you are not, then this doesn't exactly help, so sorry about this almost answer.\nEdit... | [
4,
1,
0
] | [] | [] | [
"pylons",
"python"
] | stackoverflow_0004579713_pylons_python.txt |
Q:
how to query by just giving genre information
I want to get movies according to genre information by using imdbpy. I found IMDb.get_keyword function but it did not work for me. Any idea?
Example:
from imdb import IMDb
ia = IMDb()
print ia.get_keyword(u'ring', results = 5)
A:
Are you behind any proxy?
In that cas... | how to query by just giving genre information | I want to get movies according to genre information by using imdbpy. I found IMDb.get_keyword function but it did not work for me. Any idea?
Example:
from imdb import IMDb
ia = IMDb()
print ia.get_keyword(u'ring', results = 5)
| [
"Are you behind any proxy?\nIn that case, you might need to set_proxy.\ni.set_proxy('http://yourhttproxyurl:proxyport/')\n\nAnd then just use search_keyword to search for movies which might match a particular keyword for genre\nimport imdb\nia = imdb.IMDb()\nt_result = ia.search_keyword(u'comedy')\n// process your ... | [
0
] | [] | [] | [
"imdbpy",
"movie",
"python"
] | stackoverflow_0004592653_imdbpy_movie_python.txt |
Q:
pymongo.errors.OperationFailure: error
I started 3 mongod process each on different port with different dbpath.
./bin/mongod --replSet foo/tauquir:27018,tauquir:27019 --rest
./bin/mongod --port 27018 --dbpath /data/db1 --replSet foo/tauquir:27017 --rest
./bin/mongod --port 27019 --dbpath /data/db2 --replSet foo/ta... | pymongo.errors.OperationFailure: error | I started 3 mongod process each on different port with different dbpath.
./bin/mongod --replSet foo/tauquir:27018,tauquir:27019 --rest
./bin/mongod --port 27018 --dbpath /data/db1 --replSet foo/tauquir:27017 --rest
./bin/mongod --port 27019 --dbpath /data/db2 --replSet foo/tauquir:27017 --rest
Started the connection a... | [
"replSetInitiate is a one time command so you probably don't want that coded with your connection init, but after that line you need to instantiate your python client with connection information for all 3 mongod servers. \nIn your example you are replacing your CONN variable with a connection only to 27018 and 2701... | [
1
] | [] | [] | [
"mongodb",
"pymongo",
"python"
] | stackoverflow_0004591705_mongodb_pymongo_python.txt |
Q:
RabbitVCS does not work because of python error
Hello
I cannot start running rabbitvcs on openSUSE 11.3 64bit.
I tried to run test.py file which is located in rabbitvcs folder.
It returns the following errors:
jenea@linux-nguv:/usr/lib/python2.6/site-packages/rabbitvcs> python test.py
Traceback (most recent call l... | RabbitVCS does not work because of python error | Hello
I cannot start running rabbitvcs on openSUSE 11.3 64bit.
I tried to run test.py file which is located in rabbitvcs folder.
It returns the following errors:
jenea@linux-nguv:/usr/lib/python2.6/site-packages/rabbitvcs> python test.py
Traceback (most recent call last):
File "test.py", line 26, in <module>
impo... | [
"Although stupid the answer is the following:\nThere were two folders where rabbitvcs was intalled. The first was in /usr/lib/rabbitvcs and the second was in /usr/lib64/rabbitvcs. I'm not sure why there was described issue but after I deleted rabbitvcs folder in /usr/lib64 it started to work normally.\n"
] | [
0
] | [] | [] | [
"opensuse",
"python"
] | stackoverflow_0004557215_opensuse_python.txt |
Q:
PyQt4.QtCore doesn't contain many of its classes and attributes
I have built PyQt4 from source and everything went smoothly until I tried to use some of the classes and attributes located in QtCore. For some reason QtCore is missing a lot of functionality and data that should be there. For example from PyQt4.QtCor... | PyQt4.QtCore doesn't contain many of its classes and attributes | I have built PyQt4 from source and everything went smoothly until I tried to use some of the classes and attributes located in QtCore. For some reason QtCore is missing a lot of functionality and data that should be there. For example from PyQt4.QtCore import QT_VERSION_STR is an import error. There were no errors or w... | [
"If it's really an ImportError, that suggests that it's failing to import the library altogether. Check that it's definitely somewhere that's in your sys.path, and that from PyQt4 import QtCore works.\nIf the library exists, and QT_VERSION_STR doesn't exist, it will give you a NameError rather than an ImportError.\... | [
0,
0
] | [] | [] | [
"linux",
"pyqt",
"python",
"qt4"
] | stackoverflow_0004499204_linux_pyqt_python_qt4.txt |
Q:
Is it possible to make an option in optparse a mandatory?
Is it possible to make an option in optparse a mandatory?
A:
I posted a comment earlier, but given that many other answers say No, not possible, here is how to do it:
parser = OptionParser(usage='usage: %prog [options] arguments')
parser.add_option('-f', ... | Is it possible to make an option in optparse a mandatory? | Is it possible to make an option in optparse a mandatory?
| [
"I posted a comment earlier, but given that many other answers say No, not possible, here is how to do it:\nparser = OptionParser(usage='usage: %prog [options] arguments')\nparser.add_option('-f', '--file', \n dest='filename',\n help='foo help')\n(options, args) = parse... | [
20,
8,
2
] | [] | [] | [
"optparse",
"python"
] | stackoverflow_0004592922_optparse_python.txt |
Q:
using special characters in functions: Python
I am writing an xmlrpc client which uses a server written in ruby. One of the functions is framework.busy?(). Let me show the ruby version:
server.call( "framework.busy?" )
So lets assume I create an instance of the ServerProxy class say server. So while using pytho... | using special characters in functions: Python | I am writing an xmlrpc client which uses a server written in ruby. One of the functions is framework.busy?(). Let me show the ruby version:
server.call( "framework.busy?" )
So lets assume I create an instance of the ServerProxy class say server. So while using python to call the function busy? I need to use:
server.... | [
"I've never had to call XML methods with a question mark in (and I strongly suspect it might actually be outside XML-RPC specs), but try this:\nserver.framework.getattr('busy?')()\n\nI have no idea of that works, and you would need to post a code example and have a working server I could test against. :)\nIn any ca... | [
6
] | [] | [] | [
"python",
"ruby",
"xmlrpclib"
] | stackoverflow_0004593198_python_ruby_xmlrpclib.txt |
Q:
Django query with contains and keywords
I have some keywords in one string splitted with " ". I have also table with column name. How can I get all records which will have in name part of one keyword?
Example:
keywords = 'test split el'
And if I have in records 'test2' 'element' and 'show' the query should return ... | Django query with contains and keywords | I have some keywords in one string splitted with " ". I have also table with column name. How can I get all records which will have in name part of one keyword?
Example:
keywords = 'test split el'
And if I have in records 'test2' 'element' and 'show' the query should return 'test2' and 'element'.
| [
"Table.objects.filter(name__in=keyword.split(' '))\n\nOK, that was wrong. I don't know, if this can be accomplished in a one liner or single sql query. The more obvious way is like this, but I don't know, if this is optimal:\nresult = []\nfor keyword in keywords.split(' '):\n result += list(Table.objects.filter(... | [
7
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004593268_django_python.txt |
Q:
python local variable bizarre behavior
Could python experts explain the following output to me?
def modify_dict(exclude_params):
exclude_params["domain_url"] = set()
def g(exclude_params={}):
print id(exclude_params)
print exclude_params
modify_dict(exclude_params)
print exclude_params
ret... | python local variable bizarre behavior | Could python experts explain the following output to me?
def modify_dict(exclude_params):
exclude_params["domain_url"] = set()
def g(exclude_params={}):
print id(exclude_params)
print exclude_params
modify_dict(exclude_params)
print exclude_params
return None
>>> g()
23191104
{}
{'domain_url':... | [
"It doesn't work that way. When the function is defined, the default argument is set once and for all and shared between all function calls. Proper idiom for this is:\ndef foo(some_dict=None):\n if some_dict is None:\n some_dict = {}\n\nThat's because:\ndef foo(arg={})\n\nis an instruction just like any other, ... | [
12,
0
] | [] | [] | [
"garbage_collection",
"namespaces",
"python"
] | stackoverflow_0004592717_garbage_collection_namespaces_python.txt |
Q:
reading a non-standard size binary long
I have a very specific binary file structure that I would like to read into python. I've used the struct module successfully in the past to do so. Recently, I created a large number of these files on a 64bit architecture (my usual one is 32). I used C++ and write an unsigned... | reading a non-standard size binary long | I have a very specific binary file structure that I would like to read into python. I've used the struct module successfully in the past to do so. Recently, I created a large number of these files on a 64bit architecture (my usual one is 32). I used C++ and write an unsigned long to a binary stream (which is 8 byte on ... | [
"Check out http://docs.python.org/library/struct.html#format-characters\nThis basically shows you that you'll have to say it's a long long and it will work.\n"
] | [
4
] | [] | [] | [
"python",
"struct"
] | stackoverflow_0004593370_python_struct.txt |
Q:
How would I use django.forms to prepopulate a choice field with rows from a model?
I have a ChoiceField in my form class, presumably a list of users. How do I prepopulate this with a list of users from my User model?
What I have now is:
class MatchForm(forms.Form):
choices = []
user1_auto = forms.CharField()... | How would I use django.forms to prepopulate a choice field with rows from a model? | I have a ChoiceField in my form class, presumably a list of users. How do I prepopulate this with a list of users from my User model?
What I have now is:
class MatchForm(forms.Form):
choices = []
user1_auto = forms.CharField()
user1 = forms.ChoiceField(choices=choices)
user2_auto = forms.CharField()
user2 =... | [
"It looks like you may be looking for ModelChoiceField.\nuser2 = forms.ModelChoiceField(queryset=User.objects.all())\n\nThis won't show fullnames, though, it'll just call __unicode__ on each object to get the displayed value.\nWhere you don't just want to display __unicode__, I do something like this:\nclass MatchF... | [
42
] | [
"class MatchForm(forms.Form):\n choices = tuple(User.objects.all().values_list())\n\n user1_auto = forms.CharField()\n user1 = forms.ChoiceField(choices=choices)\n user2_auto = forms.CharField()\n user2 = forms.ChoiceField(choices=choices)\n\nThis should work.\n"
] | [
-1
] | [
"django",
"django_forms",
"django_models",
"python"
] | stackoverflow_0004593292_django_django_forms_django_models_python.txt |
Q:
Python: How to quit CLI when stuck in blocking raw_input?
I have a GUI program which should also be controllable via CLI (for monitoring). The CLI is implemented in a while loop using raw_input.
If I quit the program via a GUI close button, it hangs in raw_input and does not quit until it gets an input.
How can I ... | Python: How to quit CLI when stuck in blocking raw_input? | I have a GUI program which should also be controllable via CLI (for monitoring). The CLI is implemented in a while loop using raw_input.
If I quit the program via a GUI close button, it hangs in raw_input and does not quit until it gets an input.
How can I immediately abort raw_input without entering an input?
I run it... | [
"That's not maybe the best solution but you could use the thread module which has a function thread.interrupt_main(). So can run two thread : one with your raw_input method and one which can give the interruption signal. The upper level thread raise a KeyboardInterrupt exception.\nimport thread\nimport time\n\ndef ... | [
2,
1
] | [] | [] | [
"blocking",
"command_line_interface",
"python",
"raw_input",
"windows"
] | stackoverflow_0004591917_blocking_command_line_interface_python_raw_input_windows.txt |
Q:
List of all words matching regular expression
Let assume that I have some string: "Lorem ipsum dolor sit amet"
I need a list of all words with lenght more than 3. Can I do it with regular expressions?
e.g.
pattern = re.compile(r'some pattern')
result = pattern.search('Lorem ipsum dolor sit amet').groups()
result ... | List of all words matching regular expression | Let assume that I have some string: "Lorem ipsum dolor sit amet"
I need a list of all words with lenght more than 3. Can I do it with regular expressions?
e.g.
pattern = re.compile(r'some pattern')
result = pattern.search('Lorem ipsum dolor sit amet').groups()
result contains 'Lorem', 'ipsum', 'dolor' and 'amet'.
EDIT... | [
">>> import re\n>>> myre = re.compile(r\"\\w{4,}\")\n>>> myre.findall('Lorem, ipsum! dolor sit? amet...')\n['Lorem', 'ipsum', 'dolor', 'amet']\n\nTake note that in Python 3, where all strings are Unicode, this will also find words that use non-ASCII letters:\n>>> import re\n>>> myre = re.compile(r\"\\w{4,}\")\n>>> ... | [
19,
2,
2,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0004594161_python_regex.txt |
Q:
File Locking in Python?
I want to lock the file whenever I perform read/write operation on that file. No other program or function can access file until I do not release the file. How do you do this in Python?
A:
You can try this:
http://docs.python.org/library/fcntl.html#fcntl.flock
or this:
http://docs.python.... | File Locking in Python? | I want to lock the file whenever I perform read/write operation on that file. No other program or function can access file until I do not release the file. How do you do this in Python?
| [
"You can try this:\nhttp://docs.python.org/library/fcntl.html#fcntl.flock\nor this:\nhttp://docs.python.org/library/fcntl.html#fcntl.lockf\nTo get file descriptor from a file-like object, you just need to call fileno method.\n",
"Google up zc.lockfile or portalocker.py. Both libraries can lock a file in a portabl... | [
2,
0
] | [] | [] | [
"file",
"locking",
"python"
] | stackoverflow_0004593235_file_locking_python.txt |
Q:
How to decrypt string data in C++ with Crypto++ where the original string encrypted in Python with pyCrypto
I've just encrypted a data string with pyCrypto easily, but don't know how to decrypt it in crypto++. Anybody can help with a sample decryption code in C++ with crypto++?
Here is my python code:
key = '01234... | How to decrypt string data in C++ with Crypto++ where the original string encrypted in Python with pyCrypto | I've just encrypted a data string with pyCrypto easily, but don't know how to decrypt it in crypto++. Anybody can help with a sample decryption code in C++ with crypto++?
Here is my python code:
key = '0123456789abcdef'
data = "aaaaaaaaaaaaaaaa"
iv = ''.join(chr(random.randint(0, 0xFF)) for i in range(16))
encryptor... | [
"same approach as @Jon, a bit simplified\nstd::string ciphertext = \"...\"; // what Python encryption produces\nstd::string decryptedtext;\n\nbyte key[ CryptoPP::AES::DEFAULT_KEYLENGTH ], iv[ CryptoPP::AES::BLOCKSIZE ];\n\n// populate key and iv with the correct values\n\nCryptoPP::CBC_Mode< CryptoPP::AES >::Decryp... | [
2,
1
] | [] | [] | [
"c++",
"crypto++",
"pycrypto",
"python"
] | stackoverflow_0004593793_c++_crypto++_pycrypto_python.txt |
Q:
show lyrics on ubuntu
I'm writing a little script for Ubuntu.
My intention is to call rhythmbox lyrics plug-in with a global short-cut (configuring gnome) .
I can call it from rhythmbox python console, but I don't know how to import rhythmbox built-in modules (eg. rhythmdb).
Any ideas?
A:
You can't import rhyt... | show lyrics on ubuntu | I'm writing a little script for Ubuntu.
My intention is to call rhythmbox lyrics plug-in with a global short-cut (configuring gnome) .
I can call it from rhythmbox python console, but I don't know how to import rhythmbox built-in modules (eg. rhythmdb).
Any ideas?
| [
"You can't import rhythmbox \"built-in\" modules from a standard python console. \nAs far as I know they aren't real modules, they are just objects from the rhythmbox process exposed to plugins. So you can access them only if you are running your script from the rhythmbox process.\n",
"in this case i guess you'll... | [
2,
0
] | [] | [] | [
"gnome",
"plugins",
"python",
"rhythmbox"
] | stackoverflow_0000906509_gnome_plugins_python_rhythmbox.txt |
Q:
Scraping user reviews from imdb in python
I am deeply in need of an api or a piece of code that can extract the "user reviews" of a certain movie from imdb page.
can someone help me please?
thanks
A:
I'm afraid IMDB doesnt allow that:
Robots and Screen Scraping: You may not use data mining, robots, screen scra... | Scraping user reviews from imdb in python | I am deeply in need of an api or a piece of code that can extract the "user reviews" of a certain movie from imdb page.
can someone help me please?
thanks
| [
"I'm afraid IMDB doesnt allow that:\n\nRobots and Screen Scraping: You may not use data mining, robots, screen scraping, or similar data gathering and extraction tools on this site, except with our express written consent as noted below.\n\nhttp://www.imdb.com/help/show_article?conditions\n",
"As pointed out abov... | [
3,
1
] | [] | [] | [
"imdb",
"python",
"screen_scraping"
] | stackoverflow_0004594317_imdb_python_screen_scraping.txt |
Q:
How do I make a normal HTTP request with a suds transport?
My suds transport is configured to perform authentication against a service. I would like to reuse the transport to make GET and POST requests against the same server with the same authentication. Is there a way to make a normal HTTP request with the suds ... | How do I make a normal HTTP request with a suds transport? | My suds transport is configured to perform authentication against a service. I would like to reuse the transport to make GET and POST requests against the same server with the same authentication. Is there a way to make a normal HTTP request with the suds transport?
| [
"It's easy and very similar to using urllib, but you must use suds.transport.Request(). Given a suds client client:\nfrom suds.transport import Request\n\ntransport = client.options.transport\nrequest = Request('http://www.example.org/document.html')\ndocument = transport.open(request).read()\n\nA better way is pro... | [
2
] | [] | [] | [
"python",
"suds"
] | stackoverflow_0004522608_python_suds.txt |
Q:
How to reformat URLs to be more restful (from .../?id=123 to .../123)?
Currently I have pages accessed via:
www.foo.com/details.html?id=123
I'd like to make them more restful-like, such as by the following:
www.foo.com/details/123
I'm using Google App Engine. Currently the URL's are mapped in the html-mappings ... | How to reformat URLs to be more restful (from .../?id=123 to .../123)? | Currently I have pages accessed via:
www.foo.com/details.html?id=123
I'd like to make them more restful-like, such as by the following:
www.foo.com/details/123
I'm using Google App Engine. Currently the URL's are mapped in the html-mappings file:
('/details.html*', DetailsPage),
And then on the DetailsPage handler... | [
"Rewrite your URL mapping like this:\n('/details/(\\d+)', DetailsPage),\n\n(this requires that there be a trailing part of the URL that contains one or more digits and nothing else).\nThen modify your DetailsPage::get() method to accept that id parameter, like:\nclass DetailsPage(webapp.RequestHandler):\n def ge... | [
13
] | [] | [] | [
"google_app_engine",
"python",
"restful_url",
"url"
] | stackoverflow_0004594602_google_app_engine_python_restful_url_url.txt |
Q:
writing optimization function
I'm trying to write a tennis reservation system and I got stucked with this problem.
Let's say you have players with their prefs regarding court number, day and hour.
Also every player is ranked so if there is day/hour slot and there are several players
with preferences for this slot ... | writing optimization function | I'm trying to write a tennis reservation system and I got stucked with this problem.
Let's say you have players with their prefs regarding court number, day and hour.
Also every player is ranked so if there is day/hour slot and there are several players
with preferences for this slot the one with top priority should be... | [
"The basic Algorithm\nI'd sort the players by their rank, as the high ranked ones always push away the low ranked ones. Then you start with the player with the highest rank, give him what he asked for (if he really is the highest, he will always win, thus you can as well give him whatever he requested). Then I woul... | [
3,
2,
2,
1,
1,
0,
0
] | [
"Money. Allocate time slots based on who pays the most. In case of a draw don't let any of them have the slot.\n"
] | [
-2
] | [
"algorithm",
"python"
] | stackoverflow_0000175544_algorithm_python.txt |
Q:
Is it possible to configure logging to output to standard output as well?
Is it possible to configure logging to output to standard output as well?
A:
Handlers should help you with that:
http://docs.python.org/library/logging.html#handlers
| Is it possible to configure logging to output to standard output as well? | Is it possible to configure logging to output to standard output as well?
| [
"Handlers should help you with that:\nhttp://docs.python.org/library/logging.html#handlers\n"
] | [
3
] | [] | [] | [
"logging",
"python"
] | stackoverflow_0004594895_logging_python.txt |
Q:
List of dicts from unique values across multiple fields in Django
I have a queryset 'elements' containing instances of the model Element. Elements have a foreign key 'series', and each series has fields:
subtopic_1_name
subtopic_1_slug
subtopic_2_name
subtopic_2_slug
subtopic_3_name
subtopic_3_slug
I need to gene... | List of dicts from unique values across multiple fields in Django | I have a queryset 'elements' containing instances of the model Element. Elements have a foreign key 'series', and each series has fields:
subtopic_1_name
subtopic_1_slug
subtopic_2_name
subtopic_2_slug
subtopic_3_name
subtopic_3_slug
I need to generate a "flattened" list of dicts of the form
[{'name': 'somename', 'slu... | [
"What about filtering the empty names in the db query using 'exclude'?\nones = elements.exclude('series__subtopic1_name'='').\\\n values_list('series__subtopic1_name','series__subtopic1_slug').distinct()\n\ntwos = elements.exclude('series__subtopic2_name'='').\\\n values_list('series__subtopic2_name', 'series__... | [
0
] | [] | [] | [
"django",
"django_queryset",
"python"
] | stackoverflow_0004593695_django_django_queryset_python.txt |
Q:
How to load a page on server with variables following a hashmark in the URL?
Currently, when a user goes to the following URL:
www.foo.com/details.hmtl#id=123
The server returns 'details.html' and then performs a client-side Ajax call once the page is returned to load the data for the item with id=123. It uses t... | How to load a page on server with variables following a hashmark in the URL? | Currently, when a user goes to the following URL:
www.foo.com/details.hmtl#id=123
The server returns 'details.html' and then performs a client-side Ajax call once the page is returned to load the data for the item with id=123. It uses the BBQ Plugin for JQuery
Is there any way to retrieve the parameters following th... | [
"You cannot do that because the browser sends just the /details.html for request.\nif you need to you can use parameters \nfor example : for the first time you can send the user to this page /details.hmtl?id=123 then save the user's request in the session value and redirect the user to the real page without params ... | [
3,
0
] | [
"Why are you using # for this? The first part of NiL's answer is to use an actual query ? instead, and I'd second that. But don't bother redirecting to generic pages etc. You want a page with the information about id 123 on it, so return that from the server! You're actively choosing to turn a single request for a ... | [
-1
] | [
"google_app_engine",
"jquery",
"jquery_bbq",
"python"
] | stackoverflow_0004594077_google_app_engine_jquery_jquery_bbq_python.txt |
Q:
Can't make an exact match of a string in a txt file
i solved a lot of questions by reading your posts but now i'm stuck at the following.
My problem is that i can't make an absolute match of a given word in my txt file.
I wrote the following:
for word in listtweet:
#print word,
pattern=re.compile(r'\b%s\b'... | Can't make an exact match of a string in a txt file | i solved a lot of questions by reading your posts but now i'm stuck at the following.
My problem is that i can't make an absolute match of a given word in my txt file.
I wrote the following:
for word in listtweet:
#print word,
pattern=re.compile(r'\b%s\b' %(word))
with open('testsentiwords_fullTotal_clean17... | [
"Try with this pattern :\npattern=re.compile(r'[^-a-zA-Z]%s[^-a-zA-Z]' %(word))\n\nThe problem with your pattern is that the '-' character is in \\b.\nIf you need numbers in your word, you can add 0-9 to this pattern.\npattern=re.compile(r'[^-a-zA-Z0-9]%s[^-a-zA-Z0-9]' %(word))\n\n",
"If the print output you prov... | [
2,
0,
0,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0004593946_python_regex.txt |
Q:
Pydoc webserver does not work on ubuntu
I did pydoc -p 5555 and I get - : [Errno 2] No such file or directory: '-p' for one of my modules. Is this because of corrupt python installation or am I missing something?
I am running Python 2.6.6. Thanks.
A:
Try this:
$ python -m pydoc -p 5555
If this does not work, it... | Pydoc webserver does not work on ubuntu | I did pydoc -p 5555 and I get - : [Errno 2] No such file or directory: '-p' for one of my modules. Is this because of corrupt python installation or am I missing something?
I am running Python 2.6.6. Thanks.
| [
"Try this:\n$ python -m pydoc -p 5555\n\nIf this does not work, it may be a corrupt Python Installation\n"
] | [
1
] | [] | [] | [
"pydoc",
"python",
"ubuntu"
] | stackoverflow_0004595138_pydoc_python_ubuntu.txt |
Q:
How do I find out how big is a community for example a web framework.
Are there tools which can do that for me? For example I want to compare how big a community is for a web framework in Python. And for my dimploma thesis is interesting to know, how big a community is and trends for the future.
A:
I guess you ... | How do I find out how big is a community for example a web framework. | Are there tools which can do that for me? For example I want to compare how big a community is for a web framework in Python. And for my dimploma thesis is interesting to know, how big a community is and trends for the future.
| [
"I guess you won't find any \"magic tools\" for this purpose. Personally I would browse the web for a couple of hours and ask myself things such as:\n\nAre there any \"official\" communities/forums out there? Do they contain lots of documentation, references, videos, tutorials etc?\nIs the SDK recently updated? Are... | [
6,
1,
1
] | [] | [] | [
"python",
"web_frameworks"
] | stackoverflow_0004595268_python_web_frameworks.txt |
Q:
Bytes and integers and concatenation and python
I have 2 32bit unsigned integers..
777007543
and
114997259
and the string of bytes..
0x47 0x30 0x22 0x2D 0x5A 0x3F 0x47 0x58
How do I get python to give me the concatenation of these 3 such that I have...
0x2E 0x50 0x31 0xB7 0x06 0xDA 0xB8 0x0B 0x47 0x30 0x22 0x2D 0x... | Bytes and integers and concatenation and python | I have 2 32bit unsigned integers..
777007543
and
114997259
and the string of bytes..
0x47 0x30 0x22 0x2D 0x5A 0x3F 0x47 0x58
How do I get python to give me the concatenation of these 3 such that I have...
0x2E 0x50 0x31 0xB7 0x06 0xDA 0xB8 0x0B 0x47 0x30 0x22 0x2D 0x5A 0x3F 0x47 0x58
I would then run that through an md... | [
"import struct\nimport hashlib\n\nx = struct.pack('>II8B', 777007543, 114997259, 0x47, 0x30, 0x22, 0x2D, 0x5A, 0x3F, 0x47, 0x58)\nhash = hashlib.md5(x).digest()\n\nprint [hex(ord(d)) for d in x]\n(output) ['0x2e', '0x50', '0x31', '0xb7', '0x6', '0xda', '0xb8', '0xb', '0x47', '0x30', '0x22', '0x2d', '0x5a', '0x3f', ... | [
6,
2,
1
] | [] | [] | [
"byte",
"md5",
"python"
] | stackoverflow_0004595161_byte_md5_python.txt |
Q:
How can I evaluate variable to another variable before assigning?
This question broken into subquestions:
Pointers in Python suggested by one reply to look at, more here
"why not to modify locals?" -question here.
Original Question
#!/usr/bin/python
#
# Description: trying to evaluate array -value to variable be... | How can I evaluate variable to another variable before assigning? | This question broken into subquestions:
Pointers in Python suggested by one reply to look at, more here
"why not to modify locals?" -question here.
Original Question
#!/usr/bin/python
#
# Description: trying to evaluate array -value to variable before assignment
# but it overwrites the variable
#
# How can I evaluate... | [
"I would use a dictionary with a bit of indirection thrown in. When you want to use dynamic variable names that's a hint that you should not be using actual variables but instead some sort of data structure like a list or a dict.\nTry using two data structures: a list called variables which stores the names of the ... | [
2,
1,
1,
1,
0,
0,
0
] | [] | [] | [
"python",
"variable_assignment"
] | stackoverflow_0004590407_python_variable_assignment.txt |
Q:
openoffice: duplicating rows of a table in writer
I need to programmatically duplicate rows of a Table in openoffice writer.
It's not difficult to add rows via table.Rows.insertByIndex(idx, count), that adds empty rows and it's easy to add text in that row assigning DataArray to the CellRange. Doing this way you ... | openoffice: duplicating rows of a table in writer | I need to programmatically duplicate rows of a Table in openoffice writer.
It's not difficult to add rows via table.Rows.insertByIndex(idx, count), that adds empty rows and it's easy to add text in that row assigning DataArray to the CellRange. Doing this way you loose control on the style of the cells and specificall... | [
"The solution is to use controller's method .getTrasferable() to get data from the ViewCursor. that in turn requires that you control your view cursor and position it in every single cell (I was not able to make the ViewCursor span multiple cells). Once you have acquired the transferable you place the cursor in th... | [
5
] | [] | [] | [
"odt",
"openoffice.org",
"openoffice_writer",
"python",
"templates"
] | stackoverflow_0004541081_odt_openoffice.org_openoffice_writer_python_templates.txt |
Q:
What is the syntax for evaluating string matches on regular expressions?
How do I determine if a string matches a regular expression?
I want to find True if a string matches a regular expression.
Regular expression:
r".*apps\.facebook\.com.*"
I tried:
if string == r".*apps\.facebook\.com.*":
But that doesn't se... | What is the syntax for evaluating string matches on regular expressions? | How do I determine if a string matches a regular expression?
I want to find True if a string matches a regular expression.
Regular expression:
r".*apps\.facebook\.com.*"
I tried:
if string == r".*apps\.facebook\.com.*":
But that doesn't seem to work.
| [
"From the Python docs: on re module, regex\nimport re \nif re.search(r'.*apps\\.facebook\\.com.*', stringName):\n print('Yay, it matches!')\n\nSince re.search returns a MatchObject if it finds it, or None if it is not found.\n",
"You have to import the re module and test it that way:\nimport re\n\nif re.match... | [
3,
2,
1,
0
] | [] | [] | [
"python",
"regex",
"string"
] | stackoverflow_0004596286_python_regex_string.txt |
Q:
Canonical embedded interactive Python interpreter example?
I would like to create an embedded Python interpreter in my C/C++ application. Ideally this interpreter would behave exactly like the real Python interpreter, but yield after processing each line of input. The standard Python module code looks from the out... | Canonical embedded interactive Python interpreter example? | I would like to create an embedded Python interpreter in my C/C++ application. Ideally this interpreter would behave exactly like the real Python interpreter, but yield after processing each line of input. The standard Python module code looks from the outside exactly like what I want, except that it is written in Pyth... | [
"Take a look at boost.python. It's a fantastic integretaion of Python in C++ and vice versa.\nBut you are able to use the C API anyway. The PyRun_InteractiveLoopFlags() function offer a interactive console in your C++ application.\n"
] | [
2
] | [] | [] | [
"c",
"python"
] | stackoverflow_0004596370_c_python.txt |
Q:
Renaming a set of file in separate folder in python
Hi guys have a problem with renaming a set of files in separate folder in python. i have a folder structure like
images/p_0/aaa.jpg,bbb.jpg
images/p_1/aaa.jpg,bbb.jpg
images/p_2/aaa.jpg,bbb.jpg
I need to rename these jpg to like
images/p_0/A-1.jpg,B-1.jpg
image... | Renaming a set of file in separate folder in python | Hi guys have a problem with renaming a set of files in separate folder in python. i have a folder structure like
images/p_0/aaa.jpg,bbb.jpg
images/p_1/aaa.jpg,bbb.jpg
images/p_2/aaa.jpg,bbb.jpg
I need to rename these jpg to like
images/p_0/A-1.jpg,B-1.jpg
images/p_1/A-2.jpg,B-2.jpg
images/p_2/A-3.jpg,B-3.jpg
and i a... | [
"Use os.walk and os.rename.\nimport os\nfor root, dirs, files in os.walk(top, topdown=False):\n for name in files:\n #Rename your files and use os.path.join(root, name)\n\n",
"Take a look at os.listdir or os.walk, if you have a nested directory structure.\n#!/usr/bin/env python\n\nimport os\n\n# list al... | [
3,
0,
0,
0
] | [] | [] | [
"path",
"python"
] | stackoverflow_0004596347_path_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.