text
stringlengths
226
34.5k
Python: How to force a "print" to use __unicode__ instead of __str__, or otherwise naturally "print" the message without explicitly calling unicode() Question: Basically I just want to be able to create instances using a class called Bottle: eg `class Bottle(object):...` and then in another module be able to simply "pr...
How to set up a cronjob that accesses a website every 5 minutes Question: I am hosting a site on ep.io and heroku. The way they work is that when your website isn't accesed for some amount of time, the server is 'shut off' only to be restarted when someone visits your domain. I noticed that this generally will take up ...
What do you call the elements of a module? Question: I have this code from Learn Python The Hard Way and I need to comment it: from sys import argv So I did: #imports argv from the sys module I know what argv does, but I am having trouble figuring out what to call this element of the sys module? A...
Why is semicolon allowed in this python snippet? Question: Python does not warrant the use of semicolons to end statements. So why is this (below) allowed? import pdb; pdb.set_trace() Answer: Python does not _require_ semi-colons to terminate statements. Semi colons _can_ be used to delimit statem...
SVN : repository structure when 2 differents major version development in parallel? Question: I am quite new with subversion, and I whant to know how to structure a repository. As I read, 'trunk' directory is for the main development, 'tags' is to snapshot a version, 'branches' is for doing some big changes/testing and...
Django uwsgi import error Question: I have a Django project with one app called `subscribe`. In root `urls.py` I use include from `subscribe`'s `urls.py`. I put to `INSTALLED_APPS` `subscribe` and in `subscribe`'s `urls.py` I use `subscribe.views.<name>` for call my views. When server run as `python manage.py runserve...
Using Python networkx for exploring network properties Question: I'm trying to make a code for getting Twitter network properties. But I got an error on my code. I don't know how come it happened. The error is this: Traceback (most recent call last): File "Network_property.py", line 14, in <modul...
python: urllib2 using different network interface Question: I have the following code: f = urllib2.urlopen(url) data = f.read() f.close() It's running on a machine with two network interfaces. I'd like to specify which interface I want the code to use. Specifically, I want it to use the one...
Python trying to write and read class from file but something went horribly wrong Question: Considering this is only for my homework I don't expect much help but I just can't figure this out and honestly I can't get my head around what's going wrong. Usually I have an idea where the problem is but now I just don't get ...
A slider for curses based UI Question: As a learning project, I'd like to set-out to make an ncurses-based UI for a program I had in mind, written in python. After looking at urwid documentation, I cannot see anyway to create a simple slider (I need it to make a volume slider) that can be adjusted with the mouse. Am ...
Secure Copy File from remote server via scp and os module in Python Question: I'm pretty new to Python and programming. I'm trying to copy a file between two computers via a python script. However the code os.system("ssh " + hostname + " scp " + filepath + " " + user + "@" + localhost + ":" cwd) wo...
Python : 2 sockets, sending from A to B and from B to A Question: I've been working on this for 2 days and still I do not manage to get it to work properly. I wanted to write an application that uses 2 sockets with a medium in the middle This medium is this script that should read from socketA and write to SocketB an...
Selenium python do test every 10 seconds Question: I am using selenium (python) testing and I need to test my application automatically every 10 seconds. How can I do this? Answer: You could use [threading.Timer](http://docs.python.org/library/threading.html#timer- objects): import threading impor...
Error: No such file or directory Question: I am trying to extract data from a XML file with python. I tried the following code. from xml.etree.ElementTree import ElementTree tree = ElementTree() tree.parse("data_v2.xml") Error message: IOError: [Errno 2] No such file or dir...
Video file reading by OpenCV is very slow in Python Question: I'm trying to use OpenCV from Python for some video processing and it works extremely slow for me. For example a simple reading and showing of all frames works at about 1 fps: import cv2 cap = cv2.VideoCapture("out1.avi") cv2.namedWind...
Create a list (of tuples?) from two lists of different sizes Question: I am stuck trying to perform this task and while trying I can't help thinking there will be a nicer way to code it than the way I have been trying. I have a line of text and a keyword. I want to make a new list going down each character in each lis...
wsgi application is using an older python version Question: I have deployed a Pyramid app using mod_wsgi. I have setup the python path in the virtualhost: WSGIDaemonProcess MyApp user=myUser group=staff threads=4 python-path=/home/myapp/env/lib/python2.7/site-packages WSGIScriptAlias / /home/myapp/e...
Why is the http request hanging in my python script? Question: One of my script runs perfectly on an XP system, but the exact script hangs on a 2003 system. I always use mechanize to send the http request, here's an example: import socket, mechanize, urllib, urllib2 socket.setdefaulttimeout(60) ...
How to open files given as command line arguments in python? Question: I want my .py file to accept file I give as input in command line. I used the sys.argv[] and also fileinput but I am not getting the output. Answer: If you will write the following script: #!/usr/bin/env python import sys ...
It appears I've run out of 32-bit address space. What are my options? Question: I'm trying to take the covariance of a large matrix using `numpy.cov`. I get the following error: Python(22498,0xa02e3720) malloc: *** mmap(size=1340379136) failed (error code=12) *** error: can't allocate region *** ...
ml-py svm converges but classifying wrongly Question: I am trying to do some classification task with python and SVM. From collected data I extracted the feature vectors for each class and created a training set. The feature vectors have n-dimensions(39 or more). So, say for 2 classes I have a set of 39-d feature vect...
Plone 4: how to get the context for a sub-folder with a hyphen in the shortname Question: I am writing a python script to import content from another CMS into Plone 4.1. For a number of reasons I am running it like so: `bin/instance run path/to/myscript` The question I have is how to get the correct context for a fold...
Get first N key pairs from an Ordered Dictionary to another one in python Question: I have an ordered dictionary (OrderedDict) sorted by value. How can I get the top (say 25) key values and add them to a new dictionary? For example: I have something like this dictionary={'a':10,'b':20,'c':30,'d':5} o...
Python Threading With Concurrency Question: I wrote the following code while trying to learn threading in python. import threading import time def printWorker(x,y): t = time.time() while time.time() - t < 10: print "Name:%s Time:%s" %(y,st...
wxpython cut copy and paste throughout the application Question: I'm developing a small application with multiple TextCtrl and ComboBox widgets. I want that when I press the key Ctrl-C Ctrl-V and Ctrl-X I get the usual behaviour of copying, pasting and cutting in the appropriate entry. What I obtain right now is that,...
Python Popen WHOIS OS command fail test Question: Prefacing this with the text 'just another beginner'. when you have the result of a whois command via the Popen command, how do you test if its good ? Normally when Python returns a list of whatever you can test the length of it and that has usually sufficed for me, bu...
How to use multiple variables read from file with looping subprocess/popen Question: I am using python to read 2 files from my linux os. One contains a single entry/number 'DATE': > > 20111125 > the other file contains many entries, 'TIME': > > 042844UTC > 044601UTC > ... > 044601UTC > I am ...
How to get Fabric to automatically (instead of user-interactively) interact with shell commands? Combine with pexpect? Question: Seeking means to get [Fabric](http://fabfile.org) to automatically (instead of user-interactively) interact with shell commands (and not just requests for passwords, but also requested user i...
Python 3.x and TestLink xmlprc Question: Appreciate your helping first, I am new for the python 3.x. When I try to use Python 3.x to parse the testlink xmlprc server. I got below error, but I can run the code under Python 2.x, any idea? import xmlrpc.client server = xmlrpc.client.Server("http://...
Pass arguments to a slot using QTimer Question: I have written a pyQt client-server application. (python:3.2.2 , pyQT:4.8.6) The sender sends a message to the listening receivers, and the receivers send a response to the sender. I dont want the response to be sent instantly, but after a small delay. This is part of ...
Ultimate answer to relative python imports Question: I know that there are lots of questions about the same import issues in Python but it seems that nobody managed to provide a clear example of correct usage. Let's say that we have a package `mypackage` with two modules `foo` and `bar`. Inside `foo` we need to be abl...
Is it possible to precompile an entire python package? Question: We have a significant ~(50kloc) tree of packages/modules (approx 2200files) that we ship around to our cluster with each job. The jobs run for ~12 hours, so the overhead of untarring/bootrapping (i.e. resolving PYTHONPATH for each module) usually isn't a ...
Undefined Symbol in C++ When Loading a Python Shared Library Question: I have been trying to get a project of mine to run but I have run into trouble. After much debugging I have narrowed down the problem but have no idea how to proceed. Some background, I am using a python script inside C++ code. This is somewhat doc...
ValueError: Cannot assign in django Question: I have encountered a problem when I was trying to add/post a data to my models. this is what i have done in my python manage.py shell: >>> from booking.models import * >>> qa = Product.objects.get(id=5) >>> sd = Booking.objects.create( ... date_se...
Converting excel files to python to frequency Question: Essentially I've got an excel files with voltage in the first column, and time in the second. I want to find the period of the voltages, as it returns a graph of voltage in y axis and time in x axis with a periodicity, looking similar to a sine function. To find ...
QTableView and custom ORM Question: Do you have any ideas, examples how to use `QTableView` with a custom ORM written in Python (for example `Web2Py DAL`). So i have result of a query and fields describing properties of columns in that result: ID (int) Name (str) 1 Lisa 2 Maria ...
scrapy log handler Question: I seek your help in the following 2 questions - How do I set the handler for the different log levels like in python. Currently, I have STATS_ENABLED = True STATS_DUMP = True LOG_FILE = 'crawl.log' But the debug messages generated by Scrapy are also added ...
python module import issues in command prompt Question: I have installed some python packages which I am able to access using IDLE and not through command shell window. Here is the output from IDLE: Python 2.7.2+ (default, Oct 4 2011, 20:03:08) [GCC 4.6.1] on linux2 Type "copyright", "credits"...
More functional os.walk Question: Since I need to do many traversals of directories, which some complex filtering, I thought to create a wrapper around os.walk. Which is something like this: def fwalk(root, pred_dir, pred_files, walk_function=walk): """Wrapper function around the standard os.wal...
Python, string format, newline (C++ - std::endl) Question: I format string (in overloading operator **str**) and i don't want to use raw \n or \r\n tags. Have python cross-platform newline identifier like std::endl in C++? I trying to google it, but don't found answer. Answer: How about using `os.linesep`? It contai...
Is the routes Dispatcher broken in CherryPy for Mac? Question: Is CherryPy broken? I just set it up and tried to use the routes dispatcher but it has an import error, my code is as follows: import cherrypy mapper = cherrypy.dispatch.RoutesDispatcher() The error is: Traceback...
Strange pygame image error Question: I have a small problem in my code. I have the following code: import os,pygame class npc: ntype = 0 image = None x = 0 y = 0 text = "" name = "" def Draw(self,screen): screen.blit(self.image, [sel...
Python's urllib2.urlopen() hanging with local connection to a Java Restlet server Question: I'm trying to connect to a local running Restlet server from python, but the connection hangs infinitely (or times out if I set a timeout). import urllib2 handle = urllib2.urlopen("http://localhost:8182/contac...
ZMQ Pub-Sub Program Failure When Losing Network Connectivity Question: I have a simple pub-sub setup on a mid-sized network, using ZMQ 2.1. Although some subscribers are using C# bindings, others are using Python bindings, and the issue I'm having is the same for either. If I pull the network cable from a machine runn...
wxPython: scrollbars interfering with formatting Question: The following code is intended to demonstrate a problem I'm having with wxPython. When I substitute a `wx.Panel` with a `wx.ScrolledWindow` and then run the program the window that is opened is about as small as it could possibly be. Once the frame has been man...
Python I/O: How to use the wsgi.input stream from io module Question: In a WSGI application we can read the row input data from the _wsgi.input_ field: def application(env, start_response): ..... data = env['wsgi.input'].read(num_bytes) ..... However, I want to w...
How do you deal with multiple Python classes in the same module depending on each other? Question: I'm using an ODM library and I'm defining documents as classes within the same module, when they are related. I've hit a circular dependency problem and because I haven't come across this before in Python, I don't know ho...
Python cannot open file Question: #!/usr/bin/python data = open("/home/mia/Desktop/results/all-nodup.txt", "r") fd = open("/home/mia/Desktop/results/all-filter.txt", "w") last_time = 0.0 last_ip = None last_hash = None row = data.read() for line in row: timestamp, i...
regex - how to recognise a pattern until a second one is found Question: I have a file, named a particular way. Let's say it's: tv_show.s01e01.episode_name.avi it's the standard way a video file of a tv show's episode is named on the net. The pattern is quite the same all over the web, so I want to...
Python: How do I make a button freeze when I press it? - Tkinter Question: This is a memory game where the user selects two buttons (cells). If the two words behind the cells match, the words stays visible else the cells goes hidden and u can't see the words behind them. What I want to do is to make a cell freeze if it...
how to add/subtract 2 days in the target day in python? Question: I have a problem in adding or subtracting 2 days to the target day... here is my code : import datetime target_date = datetime.date(2011,2,7) thanks Answer: Use [`datetime.timedelta`](http://docs.python.org/library/datetim...
Python for android - import modules error Question: I am trying to import a python module in the "Python For Android" application in my emulator. I am able to push the zipped file and extract it but once the extraction is complete, I get the following error :- Errorjava.io. FileNotFoundException: /da...
Parsing puppet-api yaml with python Question: I am creating a script which need to parse the yaml output that the puppet outputs. When I does a request agains example _https://puppet:8140/production/catalog/my.testserver.no_ I will get some yaml back that looks something like: --- &id001 !ruby/object:Pu...
String reverse in Python Question: Write a simple program that reads a line from the keyboard and outputs the same line where every word is reversed. A word is defined as a continuous sequence of alphanumeric characters or hyphen (‘-’). For instance, if the input is “Can you help me!” the output should be “naC uoy pleh...
How can I write a generic Python 2.2 function that returns a list of unset parameters? Question: I have a function with many input parameters, and I need a function that will return a list of parameter names (not values) for each parameter whose value is '' or None Normally I'd throw an exception in such a method. If ...
how to convert string to datetime.timedelta()? Question: how can i convert my string of date to a datetime.timedelta() in python? I have this code : import datetime date_select = '2011-12-1' delta = datetime.timedelta(days=1) target_date = date_select + delta print target_date ...
Python: argparse subcommand subcommand? Question: I have a program that has many available options. For example a configuration option to change settings. ./app config -h gives me the help using normal argparse subcommands now i would like to add another subcommand to the config subcommand called ...
Setup Eclipse to work with Python bindings for Subversion Question: I'm new in the Python world, coming from PHP. So, this question may sound silly for experienced Python developers, but I'm really confused. So, I want to implement simple Python app to work with subversion. For that purpose I want to use python bindin...
How can I fire a Traits static event notification on a List? Question: I am working through the [`traits`](https://github.com/enthought/traits) [presentation from PyCon 2010](http://python.mirocommunity.org/video/1690/pycon-2010-introduction-to- tra). At about 2:30:45 the presenter starts covering [trait event notifica...
Scrapy read list of URLs from file to scrape? Question: I've just installed scrapy and followed their simple dmoz [tutorial](http://doc.scrapy.org/en/latest/intro/tutorial.html) which works. I just looked up basic file handling for python and tried to get the crawler to read a list of URL's from a file but got some err...
Putting a function to a local namespace to speeding up access taking descriptors into account Question: I use `numpy.random.normal` function in a **tough** loop in a class. class MyClass(MyBaseClass): def run(self): while True: ... self.L.append(nump...
Python: Unable to import mechanize module on Mac Question: I have mechanize module installed using easy_install but when I tried to import I get the following error: Python 2.6.7 (r267:88850, Nov 21 2011, 14:59:21) [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin Type "help", "copyright", "...
I have a twisted reactor running, how do I connect to it? Question: I've been following the tutorials and now have a twisted reactor running. I've used telnet to test that it does stuff but I've not managed to find anything in the twisted tutorials on how to connect to the reactor. My assumption was there would be som...
Python: Import Exception Question: Is it possible to import everything except one module from a package? I need a lot of modules from a particular library that I use in my class, but it looks like it used the same module name for one of the modules that I need. I need to use set operation and intersection, but when I...
How to send a mail to hundreds of thousands recipients in python fast which each of recipients is showed as receiver in mail header? Question: I'm looking of solutions to send huge number of mails (hundreds of thousands) in Python. I have a list of recipients (in a file), and I want to send a mail to all of them. I wan...
How do I deploy web2py on PythonAnywhere? Question: How do i get a basic web2py server up and running on [PythonAnywhere](http://www.pythonanywhere.com)? Answer: [update - 29/05] We now have a big button on the web tab that will do all this stuff for you. Just click where it says _Web2Py_ , fill in your admin passwor...
Cython ImportError: No module named parallel Question: I am trying to access the new parallel features of Cython 0.15 (using Cython 0.15.1). However, if I try this minimal example (testp.py), taken from <http://docs.cython.org/src/userguide/parallelism.html>: from cython.parallel import prange, parallel,...
set up python emacs environment mac os x Question: I have followed this tutorial for setting up a python emacs enviroment. <http://www.saltycrane.com/blog/2010/05/my-emacs-python-environment/> I'm able to get python mode for emacs and syntax highlighting but when I try to use rope and ropemacs for example the command...
How to implement a Lock with a timeout in Python 2.7 Question: Is there a way to implement a lock in Python for multithreading purposes whose `acquire` method can have an arbitrary timeout? The only working solutions I found so far use polling, which * I find inelegant and inefficient * Doesn't preserve the bounde...
Newbie Apache / Python error Question: Trying to configure apache on my laptop to execute a python script for a small assignment: * I've created a /scripts folder in root and granted it all permissions 777. * In my virtual hosts file I have added `ScriptAlias /scripts/ /scripts/` * Added directory handle also in...
python networking: asynchat handshake Question: I am using python asynchat to implement a network protocol. At connection time I need to send a command and the server answer with a session. My main problem is that I need to wait until I get the session response. but not sure how to implement this. should I use socket....
Does the Rdio Desktop API give tracks unique IDs? Question: I've built a small desktop app for myself that logs listens from iTunes and Rdio so I can create powerful playlists based on how I listen to music over time, but it requires each track to have a unique ID that will never change, regardless of which app I used ...
Custom include tag Question: I want to make a custom include tag (like `{% smart_include something %}` ), which realize what kind a thing we want to include and then call regular `{% include %}` tag. That's should be something like this: @register.simple_tag def smart_include(something): if s...
Why does this work in Python 3 IDLE on Windows and not in the terminal on Ubuntu? Question: I have a program where I use `input()` to take input from STDIN. I use the input to read the first word from a line and use it as a dictionary key, with every subsequent word added to a list which is the value of the aformentio...
Map multiple lists of values to a list of keys in a python dictionary? Question: I want to map some values(a list of lists) to some keys(a list) in a python dictionary. I read [Map two lists into a dictionary in Python](http://stackoverflow.com/questions/209840/map-two-lists-into-a- dictionary-in-python) and figured I...
Trouble installing pyserial with macports python (python27) on Mac Question: I installed py-serial using macports (on my mac) but it installed python24 instead of using my existing python27. So if use the python24 that macports py-serial installed then I can import py- serial # /opt/local/bin/python2.4 ...
How to use std::vector in PHP using SWIG Question: I am working on wrapping a C++ API in PHP using SWIG. I am most of the way there but I am having problems with a function that returns a vector. The header looks something like this: #include <vector> namespace STF { class MyClass { ...
Easier way to create a JSON object from an SQLObject Question: EDIT -- took the code from below and made it so it can handle ForiegnKeys, Decimal numbers (although i'm doing a very forced float conversion). It returns a dict now so it can be recursive. from sqlobject import SQLObject from decimal imp...
How to import modules from alternate locations when using Python IDLE? Question: I've been trying to figure this out for more than 2 days, screening the internet and the tutorial, but yet I don't have solved my problem. I'm a real newb and don't yet really know what I'm doing.. Software I use: Mac OS X 10.6 Python v3....
html forms to django Question: > **Possible Duplicate:** > [python/django adder](http://stackoverflow.com/questions/8423687/python- > django-adder) I am new to django and tryed to make a site that takes my number (inputted from an of html) and add/ subtract it to an other. So i tryed this in views.py: ...
Colorbar does not show values when using LogNorm() Question: I am trying to make a contour plot with the contour levels scaled by the log of the values. However, the colorbar does not show enough values next to the colors. Here is a simple example. import numpy as N import matplotlib as M import ...
Call a python main from another python script Question: I have been giving some huge command line tool from a colleague. The main reads a bunch of arguments, parses those using the elegant `import OptionParser` later on and does the job. if __name__ == '__main__': main(sys.argv) I can eithe...
python - tkinter -- Having trouble with resizing multiple grids Question: i have the following code and i can't manage to resize properly the frames. When i resize, everything disappears.. When i run it, it's ok.But when i resize it, i want to keep the original view. from Tkinter import * import os,...
How to use paramiko to talk interactivity with a remote application? Question: I am trying to use paramiko to interatively speak with an command line application, but I'm doing something wrong. # that's the echo.py, the script I am connecting to via SSH import sys, time while 1: x = sys.s...
simple thread management within python classes Question: Im trying to write a module for Python that prints out text for my program and displays a progress bar while i do something in the background. Im using the 'threading' module currently but open to suggestions if something else will make it easier. what i want to...
linking between two modules with distutils Question: I have recently [exposed a problem](http://stackoverflow.com/questions/8443652/dependencies-between- compiled-modules-in-python) when working with several compiled C++ modules and would like to rephrase the question. I have two modules 'mod1' and 'mod2'. They are co...
python threads, how to return results generated during the execution of a multithread code Question: I'm tring to learn how to use threads in python to save a list of object. I'm starting from this code : import threading import urllib from tempfile import NamedTemporaryFile singlelock =...
Like FourWaySplitter but different Question: Using Python 2.6, wx.Python: Wonder if someone might know how to build a four panel window w/o using FourWaySplitter. (Unless I am wrong FourWaySplitter will do what I am about to describe. With FourWaySplitter any change of the size of any sub-panel changes the size of ALL...
python map string split list Question: I am trying to map the `str.split` function to an array of string. namely, I would like to split all the strings in a string array that follow the same format. Any idea how to do that with `map` in python? For example let's assume we have a list like this: >>> a = [...
Masks in python opencv cv2 not working? Question: While in general the new python bindings for opencv (cv2) are a beauty, "masks" don't seem to be working properly - unless I really get something wrong: For example "cv2.add" still works properly without a mask: import cv2 a = ones((2,2,3), dtype=uin...
how to read a file that can be saved as either ansi or unicode in python? Question: I have to write a script that support reading of a file which can be saved as either Unicode or Ansi (using MS's notepad). I don't have any indication of the encoding format in the file, how can I support both encoding formats? (kind o...
Python: os.chdir() not working within a for loop? Question: I'm trying to get a homemade path navigation function working - basically I need to go through one folder, and explore every folder within it, running a function within each folder. I reach a problem when I try to change directories within a for loop. I've go...
Using mock patch to mock an instance method Question: I'm trying to mock something while testing a Django app using the imaginatively named [Mock testing library](http://www.voidspace.org.uk/python/mock/index.html). I can't seem to quite get it to work, I'm trying to do this: models.py from some...
Scrolling windows with wxPython Question: I am making a frame with a scrollbar and some images inside. The scrollbar works fine when the frame is empty. However, when I add a picture in, the scrollbars seem to get pushed up into the top left corner of the frame. How can I implement my code so that the scrollbars stay w...
Matching strings for multiple data set in Python Question: I am working on python and I need to match the strings of several data files. First I used pickle to unpack my files and then I place them into a list. I only want to match strings that have the same conditions. This conditions are indicated at the end of the s...
how do i write to a python subprocess' stdin Question: I'm trying to write a python script that starts a subprocess, and writes to the subprocess stdin. I'd also like to be able to determine an action to be taken if the subprocess crashes. The process I'm trying to start is a program called nuke which has its own buil...
PyQt4's udp broadcast doesn't seem to work Question: My application written in PyQt4 doesn't seem to get any data. readyRead event isn't even fired. Use of the applications is following: python server.py -s -p 50000 #(server on port 50000) python server.py -c -p 50000 #(client sending data to port 50...
How to create a new window button PySide/PyQt? Question: I'm having problems with a "New Window" function in PyQt4/PySide with Python 2.7. I connected a `initNewWindow()` function, to create a new window, to an action and put it in a menu bar. Once a common function in desktop software. Instead of giving me a new persi...
Python's trigonmetric function return unexpected values Question: import math print "python calculator" print "calc or eval" while 0 == 0: check = raw_input() #(experimental evaluation or traditional calculator) if check == "eval": a = raw_input("operator\n") #operator ...
How to extract Ethernet level data from pcap file? Question: I have some pcap files, previously I used tshark combined python to extract source IP address, timestamp, ect. However, now I open these pcap files in Wireshark. It also contains the VLAN info, VID is the thing I want to extract right now. I use `tshark -r ...