text
stringlengths
226
34.5k
closing files properly opened with urllib2.urlopen() Question: I have following code in a python script try: # send the query request sf = urllib2.urlopen(search_query) search_soup = BeautifulSoup.BeautifulStoneSoup(sf.read()) sf.close() except Exception, err: ...
Python 2.6 to 2.5 cheat sheet Question: I've written my code to target Python 2.6.5, but I now need to run it on a cluster that only has 2.5.4, something that wasn't on the horizon when I wrote the code. Backporting the code to 2.5 shouldn't be too hard, but I was wondering if there was either a cheat-sheet or an autom...
Google App Engine Python: sys.path.append not working online Question: I have this import sys sys.path.append('extra_dir') import extra_module It work perfectly under Windows XP App Engine SDK (offline) But when deploy online, it give me `<type 'exceptions.ImportError'>`, what am I missing...
python - strtotime equivalent? Question: I'm using this to convert date time strings to a unix timestamp: str(int(time.mktime(time.strptime(date,"%d %b %Y %H:%M:%S %Z")))) However often the date structure isn't the same so I keep getting the following error message: > time data did not match forma...
Why the connect failed for ipv6 at python? Question: Why the connect failed for ipv6 ?? # python >>> import socket >>> s = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM) >>> sa = ('2000::1',2000,0,0) >>> s.connect(sa) >>> sa = ('fe80::21b:78ff:fe3...
Python threads and global vars Question: Say I have the following function in a module called "firstModule.py": def calculate(): # addCount value here should be used from the mainModule a=random.randint(0,5) + addCount Now I have a different module called "secondModule.py": ...
Can't import comtypes.gen Question: I have comtypes 0.6.2 installed on Python 2.6. If I try this: import comtypes.gen I get: Traceback (most recent call last): File "<pyshell#2>", line 1, in <module> import comtypes.gen ImportError: No module named gen Other i...
access to google with python Question: how i can access to google !! i had try that code urllib.urlopen('http://www.google.com') but it's show message `prove you are human` or some think like dat some people say try user agent !! i dunno ! Answer: You should use the [Google API](http://code.goo...
Apache Can't Access Django Applications Question: so here's the setting: The whole site is working fine if I remove the application (whose name is myapp) in the INSTALLED_APPS section in the settings file I added WSGIPythonHome in apache2.conf I can successfully access the apps via the the interactive python shell in...
about textarea \r\n or \n in python Question: i have tested code in firefox under ubuntu: the frontend is a textarea,in textarea press the key ENTER,then submit to the server, on the backend you'll get find \r\n string r=request.POST.get("t") r.find("\r\n")>-1: print "has \r\n" my que...
bash/fish command to print absolute path to a file Question: Question: is there a simple sh/bash/zsh/fish/... command to print the absolute path of whichever file I feed it? Usage case: I'm in directory `/a/b` and I'd like to print the full path to file `c` on the command-line so that I can easily paste it into anothe...
using python module in java with jython Question: I have a couple of python modules in an existing Python project that I wish to make use of in my Java app. I found an [article](http://wiki.python.org/jython/JythonMonthly/Articles/October2006/3) and followed the steps mentioned there. In particular, I need to import t...
"import numpy" results in error in one eclipse workspace, but not in another Question: Whenever I try importing numpy in my new installation of Eclipse and Pydev, I get the following error: Traceback (most recent call last): File "Q:\temp\test.py", line 1, in <module> import numpy Fil...
translating arrays from c to python ctypes Question: I have the below arrays on C how can i interpert them to ctypes datatypes inside structre struct a { BYTE a[30]; CHAR b[256]; }; should i interpert a fixed array as the datatype * the size i want like the below and if yes h...
500 Error when sending file from python to django Question: I've found a nice python module for sending data to remote servers via HTTP POST called [**poster**](http://atlee.ca/software/poster/). So I've wrote a simple view on my django app to receive and store data and then tried to send some file. Unfortunately even ...
Python Method Placement Question: Can someone give me a solution to this dosomething() def dosomething(): print 'do something' I don't want my method defines up at the top of the file, is there a way around this? Answer: The "standard" way is to do things inside a `main` function...
Python filter / max combo - checking for empty iterator Question: (Using Python 3.1) I know this question has been asked many times for the general question of testing if iterator is empty; obviously, there's no neat solution to that (I guess for a reason - an iterator doesn't really know if it's empty until it's aske...
Searching a normal query in an inverted index Question: I have a full inverted index in form of nested python dictionary. Its structure is : **{word : { doc_name : [location_list] } }** For example let the dictionary be called index, then for a word " spam ", entry would look like : { spam : { doc1.txt : [102,300,39...
Eclipse PyDev now shows all references to Tkinter as errors Question: I've been using Eclipse with PyDev (on Windows, mind you) for my Python Tkinter project for about a month now, and up until recently I've had no complaints. I start the source for one module (my GUI) like so: from Tkinter import * ...
Does python urllib2 automatically uncompress gzip data fetched from webpage? Question: I'm using data=urllib2.urlopen(url).read() I want to know: 1. How can I tell if the data at a URL is gzipped? 2. Does urllib2 automatically uncompress the data if it is gzipped? Will the data always be a s...
Is there a more Pythonic approach to this? Question: This is my first python script, be ye warned. I pieced this together from Dive Into Python, and it works great. However since it is my first Python script I would appreciate any tips on how it can be made better or approaches that may better embrace the Python way o...
C++\IronPython integration example code? Question: I'm looking for a **simple** example code for **C++\IronPython integration** , i.e. embedding python code inside a C++, or better yet, Visual C++ program. The example code should include: how to share objects between the languages, how to call functions\methods back a...
Is it possible to use Python to measure response time? Question: I'm running some experiments and I need to precisely measure participants' response time to questions. I know there are some commercial software, but I was wondering if I can do this with Python. Does python provides suitable functionality to measure the ...
python circular imports once again (aka what's wrong with this design) Question: Let's consider python (3.x) scripts: main.py: from test.team import team from test.user import user if __name__ == '__main__': u = user() t = team() u.setTeam(t) t.setLeader(u) ...
Python codes runs using idle but fails on command line? Question: I am learning Python, and I have written a script per an example in the book I am reading where it imports the urllib library. This works fine when I run it from IDLE, but if I go to the folder where the file is and run "python test.py" I get an error wh...
What are important languages to learn to understand different approaches and concepts? Question: When all you have is a pair of bolt cutters and a bottle of vodka, everything looks like the lock on the door of Wolf Blitzer's boathouse. (Replace that with a hammer and a nail if you don't read xkcd) I currently program ...
How to migrate a CSV file to Sqlite3 (or MySQL)? - Python Question: I'm using Python in order to save the data row by row... but this is extremely slow! **The CSV contains _70million lines_ , and with my script _I can just store 1thousand a second_.** * * * This is what my script looks like reader = c...
missing messages when reading with non-blocking udp Question: I have problem with missing messages when using nonblocking read in udp between two hosts. The sender is on linux and the reader is on winxp. This example in python shows the problem. Here are three scripts used to show the problem. **send.py** : ...
How to display an image from web? Question: I have written this simple script in python: import gtk window = gtk.Window() window.set_size_request(800, 700) window.show() gtk.main() now I want to load in this window an image from web ( and not from my PC ) like this: <http...
Mark File For Removal from Python? Question: In one of my scripts, I need to delete a file that could be in use at the time. I know that I can't remove the file that is in use until it isn't anymore, but I also know that I can mark the file for removal by the Operating System (Windows XP). How would I do this in Python...
NetworkX (Python): how to change edges' weight by designated rule Question: I have a weighted graph: F=nx.path_graph(10) G=nx.Graph() for (u, v) in F.edges(): G.add_edge(u,v,weight=1) get the nodes list: [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7), (7, 8),...
Showing the Foreign Key value in Django template Question: Here is my issue. I am new to python/django (about 2 months in). I have 2 tables, Project and Status. I have a foreign key pointing from status to project, and I am looking to try to display the value of the foreign key (status) on my project template, instead ...
How do I return a list as a variable in Python and use in Jinja2? Question: I am a very young programmer and I am trying to do something in Python but I'm stuck. I have a list of users in Couchdb (using python couchdb library & Flask framework) who have a username (which is the _id) and email. I want to use the list of...
How do you generate xml from non string data types using minidom? Question: How do you generate xml from non string data types using minidom? I have a feeling someone is going to tell me to generate strings before hand, but this is not what I'm after. from datetime import datetime from xml.dom.minido...
I have a text file of a paragraph of writing, and want to iterate through each word in Python Question: How would I do this? I want to iterate through each word and see if it fits certain parameters (for example is it longer than 4 letters..etc. not really important though). The text file is literally a rambling of te...
Python 2.7: Themed "common dialog" tkinter interfaces via Ttk? Question: Python 2.7 (32-bit) Windows: We're experimenting with Python 2.7's support for themed Tkinter (`ttk`) for simple GUI's and have come away very impressed!! The one area where the new theme support seems to have come up short is how OS specific comm...
how to create file names from a number plus a suffix in python Question: how to create file names from a number plus a suffix??. for example I am using two programs in python script for work in a server, the first creates a file x and the second uses the x file, the problem is that this file can not overwrite. no mat...
Help me understand my mod_wsgi Django config file Question: I was wondering why this works: sys.path.append('/home/user/django') sys.path.append('/home/user/django/mysite') os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings' but this doesn't? sys.path.append('/home/...
Class has method that shows in intellisense, but gives an error when running it Question: I'm tring to set the default encoding of my console to UTF-8 so it can display cyrillic letters and accented letters. Here is my code: from Parser import parser import sys print sys.getdefaultencoding(...
extract a sentence using python Question: I would like to extract the exact sentence if a particular word is present in that sentence. Could anyone let me know how to do it with python. I used concordance() but it only prints lines where the word matches. Answer: If you have each sentence in a string you can use find...
Handling dates prior to 1970 in a repeatable way in MySQL and Python Question: In my MySQL database I have dates going back to the mid 1700s which I need to convert somehow to ints in a format similar to Unix time. The value of the int isn't important, so long as I can take a date from either my database or from user i...
python popularity cloud not working Question: I built a popularity cloud but it doesn't work properly. The txt file is; 1 Top Gear 3 Scrubs 3 The Office (US) 5 Heroes 5 How I Met Your Mother 5 Legend of the Seeker 5 Scrubs ..... In my popularity cloud, names are written ...
Find System Hard Disk Drive from Python? Question: I am working on a software installer for my current application. It needs to be installed to the System HDD. How owuld I detect the system drive and return the letter from Python? Would the win32 extensions be useful? How about the os module pre packaged with Pyth...
how to iterate from a specific point in a sequence (Python) Question: **[Edit]** From the feedback/answers I have received, I gather there is some confusion regarding the original question. Consequently, I have reduced the problem to its most rudimentary form Here are the relevant facts of the problem: 1. I have a...
Monitor ZIP File Extraction Python Question: I need to unzip a .ZIP archive. I already know how to unzip it, but it is a huge file and takes some time to extract. How would I print the percentage complete for the extraction? I would like something like this: Extracting File 1% Complete 2% Complet...
What will a Python programmer gain by learning Ruby? Question: I am going to be learning **Ruby** , **Haskell** and **Prolog** at university. Now, I'm wondering what should get most of my attention. I have half a year to do all three, which means I need to decide on one language to get my extracurricular time. The othe...
Dynamic image creation using Python over a web page Question: I'm new to learning Python and I've been trying to implement a text to image converter that runs on a web page. 1. I have succeeded in making the functional code that converts the text into image in Python, using the PIL module (i.e., user enters input te...
Bash Script for MythTV which requires Python Dependencies Question: I wrote a bash script which renames MythTV files based upon data it receives. I wrote it in bash because bash has the strong points of textual data manipulation and ease of use. You can see the script itself here: <http://code.google.com/p/mythicalli...
how do I generate a cartesian product of several variables using python iterators? Question: Dear all, Given a variable that takes on, say, three values, I'm trying to generate all possible combinations of, say, triplets of these variables. While this code does the trick, site_range=[0,1,2] states =...
catching a broken socket in python Question: I'm having problems detecting a broken socket when a broken pipe exception occurs. See the below code for an example: The Server: import errno, select, socket, time, SocketServer class MetaServer(object): def __init__(self): self....
convert string to datetime object Question: I'd like to convert this string into a datetime object: Wed Oct 20 16:35:44 +0000 2010 Is there a simple way to do this? Or do I have to write a RE to parse the elements, convert Oct to 10 and so forth? EDIT: strptime is great. However, with ...
python pty.fork - how does it work Question: <http://docs.python.org/library/pty.html> says - > pty.fork()¶ Fork. Connect the child’s controlling terminal to a pseudo- > terminal. Return value is (pid, fd). Note that the child gets pid 0, and the > fd is invalid. The parent’s return value is the pid of the child, and ...
Python differences between running as script and running via interactive shell Question: I am attempting to debug a problem with a ctypes wrapper of a windows DLL and have noticed differences when I run tests via an interactive shell (python or ipython) and when I run the scripts non-interactively. I was wondering if ...
Python 2.7/Windows resizable ttk progressbar? Question: I'm experimenting with Python 2.7's new Tkinter Tile support (ttk). Is there a way to make the ttk.Progressbar() control auto-resize in proportion to its parent container? In reading the documentation on this control, it appears that one must explicitly set this w...
Can't tell if a file exists on a samba share Question: I know that the file name is `file001.txt` or `FILE001.TXT`, but I don't know which. The file is located on a Windows machine that I'm accessing via samba mount point. The functions in `os.path` seem to be acting as though they were case- insensitive, but the `ope...
Is it possible for my Mercurial hook to call code from another file? Question: I have a hook function named `precommit_bad_branch` which imports `hook_utils`. When invoking `precommit_bad_branch` via a commit I get the following error message: error: precommit.branch_check hook raised an exception: No mo...
Python: 'import node.py' raises "No module named py"-error Question: I have a file main.py like this: import node.py [my code...] and a node.py like this: [more of my code] When executing main.py, I get this error: File "/home/loldrup/repo/trunk/src/src/mai...
Python/Tkinter window events and properties Question: I've been searching for information on the following Tkinter window features without success. Platform is Windows, Python 2.7. At the end of this post is code that can be used to explore Tkinter window events. 1. How can one detect window minimize/maximize events...
Convert xml to pdf in Python Question: I have a problem when I try to convert a XML file in a PDF file, here I’m going to explain briefly how I try to generate a PDF file. We suppose I get the information from a database, then the code source is the following: import pyodbc,time,os,shutil,types impo...
wx.ProgressDialog not updating bar or newmsg Question: The update method of wx.ProgressDialog has a newmsg argument that is **supposed to give a textual update on what is happening in each step of the process, but my code is not doing this properly.** Here is the link to the documentation for wx.ProgressDialog <http:/...
Execute an installed Python package as a script? Question: Is there a way to enable a package to be executed as a script? For example: [~]# easy_install /path/to/foo.egg ... [~]# python -m foo --name World Hello World I've tried creating a `__main__.py` file inside my package but it's n...
Using colons in ConfigParser Python Question: According to the documentation: > The configuration file consists of sections, led by a [section] header and > followed by name: value entries, with continuations in the style of RFC 822 > (see section 3.1.1, “LONG HEADER FIELDS”); name=value is also accepted. > [Python Do...
python class attributes not setting? Question: I am having a weird problem with a chatbot I am writing that supports plugin extensions. The base extension class have attributes and methods predefined that will be inherited and can be overloaded and set. Here is the base class: class Ext: # Info a...
override multiprocessing in python Question: how can i get variable in class which is override multiprocessing in python: #!/usr/bin/env python import multiprocessing import os class TestMultiprocess(multiprocessing.Process): def __init__(self): multiprocessing.P...
Using the RESTful interface to Google's AJAX Search API for "Did you mean"? Question: Is it possible to get spelling/search suggestions (i.e. "Did you mean") via the RESTful interface to Google's AJAX search API? I'm trying to access this from Python, though the URL query syntax is all I really need. Thanks! Answer:...
compilation error. AttributeError: 'module' object has no attribute 'init' Question: Here is my small program, import pygame pygame.init() Here is my compilation command. > python myprogram.py Compilation error, File "game.py", line 1, in import pygame File "/h...
How to compare an item in a queue to an item in a set? Question: REDIT: Was trying to avoid just placing the entire block of code on the forum and saying fix it for me, but here it is, to simply the process of determining the error: #! /usr/bin/python2.6 import threading import Queue import s...
Python Tkinter Embed Matplotlib in GUI Question: I'm trying to embed a plot in my Tkinter GUI coded in Python. I believe the code below succeeds in simply putting a graph into a canvas, but I don't have any control of the canvas location within the GUI grid. I want to be able to have a subsection of my GUI be the plot....
how do I modify the system path variable in python script? Question: I'm trying to run a python script from cron, but its not running properly so I'm assuming its the different path env variable. Is there anyway to change the variable within a python script? Answer: @ubuntu has the right approach, but for what it's w...
Using Cython to expose functionality to another application Question: I have this C++ code that shows how to extend a software by compiling it to a DLL and putting it in the application folder: #include <windows.h> #include <DemoPlugin.h> /** A helper function to convert a char array in...
python test script Question: I am trying to automate a test script for a website I have the following error import urllib , urllib2 , cookielib , random ,datetime,time,sys cookiejar = cookielib.CookieJar() urlOpener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookiejar)...
Django: Import CSV file and handle clash of unique values correctly Question: I want to write a Python script to import the contents of CSV file into a Django app's database. So for each CSV record, I create an instance of my model, set the appropriate values from the parsed CSV line and call save on the model instance...
tkinter: grid method strange behavior Question: I want this code to do this: Create 4 frames with this layout (dashes mean the frame spans that column): -X- XXX Within each of these frames (X's) there should be two rows like this: cowN,1 cowN,2 It seems like the grid...
Serializing a user-defined class in Python Question: got a question regarding serializing classes that I've defined. I have some classes like class Foo: def __init__(self, x, y): self.x = x, self.y = y def toDict(self): return dict(Foo = dict(x = self.x,...
How to save web page as image using python Question: I am using python to create a "favorites" section of a website. Part of what I want to do is grab an image to put next to their link. So the process would be that the user puts in a URL and I go grab a screenshot of that page and display it next to the link. Easy eno...
Python equivalent to Java's Class.getResource Question: I have some XML files on my PYTHONPATH that I would like to load using their path on the PYTHONPATH, rather than their (relative or absolute) path on the filesystem. I could simply inline them as strings in a Python module (yay multiline string literals), and then...
Puzzling Parallel Python Problem - TRANSPORT_SOCKET_TIMEOUT Question: The following code doesn't appear to work properly for me. It requires starting a ppserver on another computer on your network, for example with the following command: ppserver.py -r -a -w 4 Once this server is started, on my mac...
What is the difference between pickle and shelve? Question: I am learning about object serialization for the first time. I tried reading and 'googling' for differences in the modules pickle and shelve but I am not sure I understand it. When to use which one? Pickle can turn every python object into stream of bytes whic...
isFollowingCamelCaseConventionInCPlusPlus more_import_than_readability? Question: I'm moving back from Python to C++ for my next project. I know [why I shouldn't](http://yosefk.com/c++fqa/) and I know [why I should](http://stackoverflow.com/questions/3175072/performance-of-c-vs- virtual-machine-languages-in-high-freq...
forms.ValidationError not working Question: i have a fileinput field for uploading files ... the view file looks like this ... from django.contrib.auth.forms import UserCreationForm from django.shortcuts import render_to_response from django.http import HttpResponseRedirect from forms import...
Libraries not imported when creating a Python executable with pyinstaller Question: I am trying to build a Python .exe for Windows and am able to create it fine. However, when I run the application, I notice that it cannot perform all of its functions because not all the libraries were imported; PySNMP is not getting i...
how to use python xml.etree.ElementTree to parse eBay API response? Question: I am trying to use xml.etree.ElementTree to parse responses from eBay finding API, findItemsByProduct. After lengthy trial and error, I came up with this code which prints some data: import urllib from xml.etree import Elem...
how to "reimport" module to python then code be changed after import Question: I have a `foo.py` def foo(): print "test" In IPython I use: In [6]: import foo In [7]: foo.foo() test Then I changed the `foo()` to: def foo(): print "test ch...
java: how to both read and write to & from process thru pipe (stdin/stdout) Question: (i'm new to java) I need to start a process and receive 2 or 3 handles: for STDIN, STDOUT, (and STDERR), so I can write input to the process and receive its output, the same way command line pipes behave (e.g. "grep") in Python this ...
negative pow in python Question: I have this problem >>> import math >>> math.pow(-1.07,1.3) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: math domain error any suggestion ? Answer: (-1.07)1.3 will not be a real number, thus the Math do...
Converting UTC datetime to user's local date and time Question: I'm using python on Django and Google App Engine. I'm also using the DateTimeProperty in one of my models. Occasionally I would like to display that date and time to the user. What is the best to convert the datetime stored in DateTimeProperty into the us...
sys.argv[1] meaning in script Question: I'm currently teaching myself Python and was just wondering (In reference to my example below) in simplified terms what the sys.argv[1] represents. Is it simply asking for an input? #!/usr/bin/python3.1 # import modules used here -- sys is a very standard ...
Prevent OpenCV function CreateVideoWriter from printing to console in Python Question: I'm using the Python bindings for OpenCV and have run into a little annoyance using CreateVideoWriter where when I call the function, it prints something similar to the below to the console and I can't seem to surpress it or ideally ...
app engine python setup Question: << Big update below implies it's simply a logging issue >> I'm trying to get app engine setup with python and having some problem that I suspect is some simple step I've missed. My app.yaml says this: application: something #name here is the one I used to register i.e....
Stack performance in programming languages Question: Just for fun, I tried to compare the stack performance of a couple of programming languages calculating the Fibonacci series using the naive recursive algorithm. The code is mainly the same in all languages, i'll post a java version: public class Fib {...
Getting the root (head) of a DiGraph in networkx (Python) Question: I'm trying to use `networkx` to do some graph representation in a project, and I'm not sure how to do a few things that should be simple. I created a directed graph with a bunch of nodes and edges, such that there is only one root element in this graph...
How can i access the file-selection in Path Finder via py-appscript? Question: Using the filemanager Path Finder on mac os x, i wanna retrieve the selected files/folders with python by using [py- appscript](http://appscript.sourceforge.net). py-appscript is a high-level event bridge that allows you to control scriptabl...
Why aren't anonymous (C)Python objects deallocated immediately? Question: I noticed something about CPython's object deallocation which piqued my curiosity. Let's say I define a type that prints a message from its `tp_dealloc` function: static void pyfoo_Bar_dealloc(pyfoo_Bar* self) { PyS...
Simple Python server Question: How can I start a simple python server that will allow me to connect to sockets from some outer source ? I've tried : import SocketServer class MyUDPHandler(SocketServer.BaseRequestHandler): def handle(self): data = self.request[0].strip() ...
Having trouble importing C# interface into Python Question: I've been doing a bunch of searching and reading today, and haven't figured out the right way to implement something, or even determining if it's possible. Here's the gist of what I'm attempting right now. I have an application that loads plugins via MEF. Plu...
Can't connect to org.freedesktop.UDisks via DBus-Python Question: It's the first time I'm using DBus so please bear with me. This is my code: import gobject import pprint gobject.threads_init() from dbus import glib glib.init_threads() import dbus bus = dbus.SessionBus()...
Python + QT, Windows Forms or Swing for a cross-platform application? Question: I'd like to develop a small/medium-size cross-platform application (including GUI). My background: mostly web applications with MVC architectures, both Python (Pylons + SqlAlchemy) and Java (know the language well, but don't like it that m...
Uniqueness of global Python objects void in sub-interpreters? Question: I have a question about inner-workings of Python sub-interpreter initialization (from Python/C API) and Python `id()` function. More precisely, about handling of global module objects in a WSGI Python containers (like uWSGI used with nginx and mod_...
Lazy logger message string evaluation Question: I'm using standard python logging module in my python application: import logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger("log") while True: logger.debug('Stupid log message " + ' '.join([str(i) for i in range(20...
efficient circular buffer? Question: I want to create an efficient [circular buffer](http://en.wikipedia.org/wiki/Circular_buffer) in python (with the goal of taking averages of the integer values in the buffer). Is this an efficient way to use a list to collect values? def add_to_buffer( self, num ): ...