title
stringlengths
12
150
question_id
int64
469
40.1M
question_score
int64
2
5.52k
question_date
stringdate
2008-08-02 15:11:16
2016-10-18 06:16:31
answer_id
int64
536
40.1M
answer_score
int64
7
8.38k
answer_date
stringdate
2008-08-02 18:49:07
2016-10-18 06:19:33
tags
listlengths
1
5
question_body_md
stringlengths
15
30.2k
answer_body_md
stringlengths
11
27.8k
How to filter files (with known type) from os.walk?
1,176,441
17
2009-07-24T08:40:31Z
10,812,969
10
2012-05-30T08:52:24Z
[ "python" ]
I have list from `os.walk`. But I want to exclude some directories and files. I know how to do it with directories: ``` for root, dirs, files in os.walk('C:/My_files/test'): if "Update" in dirs: dirs.remove("Update") ``` But how can I do it with files, which type I know. because this doesn't work: ``` if...
Exclude multiple extensions. ``` files = [ file for file in files if not file.endswith( ('.dat','.tar') ) ] ```
Python- about file-handle limits on OS
1,177,230
4
2009-07-24T12:02:40Z
1,177,261
7
2009-07-24T12:08:33Z
[ "python" ]
HI i wrote a program by python , and when i open too many tempfile, i will got an exception: Too many open files ... Then i figure out that windows OS or C runtime has the file-handle limits, so, i alter my program using StringIO(), but still don`t know whether StringIO also is limited??
Python's StringIO does not use OS file handles, so it won't be limited in the same way. StringIO will be limited by available virtual memory, but you've probably got heaps of available memory. Normally the OS allows a single process to open thousands of files before running into the limit, so if your program is runnin...
Decoding double encoded utf8 in Python
1,177,316
14
2009-07-24T12:23:26Z
1,177,542
32
2009-07-24T13:11:26Z
[ "python", "string", "utf-8", "decode" ]
I've got a problem with strings that I get from one of my clients over xmlrpc. He sends me utf8 strings that are encoded twice :( so when I get them in python I have an unicode object that has to be decoded one more time, but obviously python doesn't allow that. I've noticed my client however I need to do quick workaro...
``` >>> s = u'Rafa\xc5\x82' >>> s.encode('raw_unicode_escape').decode('utf-8') u'Rafa\u0142' >>> ```
Change current process environment's LD_LIBRARY_PATH
1,178,094
18
2009-07-24T14:33:06Z
1,186,194
29
2009-07-27T02:33:05Z
[ "python", "shared-libraries", "environment-variables" ]
Is it possible to change environment variables of current process? More specifically in a python script I want to change `LD_LIBRARY_PATH` so that on import of a module 'x' which depends on some `xyz.so`, `xyz.so` is taken from my given path in LD\_LIBRARY\_PATH is there any other way to dynamically change path from ...
The reason ``` os.environ["LD_LIBRARY_PATH"] = ... ``` doesn't work is simple: this environment variable controls behavior of the dynamic loader (`ld-linux.so.2` on Linux, `ld.so.1` on Solaris), but the loader only looks at `LD_LIBRARY_PATH` once at process startup. Changing the value of `LD_LIBRARY_PATH` in the curr...
Change current process environment's LD_LIBRARY_PATH
1,178,094
18
2009-07-24T14:33:06Z
16,517,435
7
2013-05-13T08:10:32Z
[ "python", "shared-libraries", "environment-variables" ]
Is it possible to change environment variables of current process? More specifically in a python script I want to change `LD_LIBRARY_PATH` so that on import of a module 'x' which depends on some `xyz.so`, `xyz.so` is taken from my given path in LD\_LIBRARY\_PATH is there any other way to dynamically change path from ...
Based on the answer from Employed Russian, this is what works for me ``` oracle_libs = os.environ['ORACLE_HOME']+"/lib/" rerun = True if not 'LD_LIBRARY_PATH' in os.environ: os.environ['LD_LIBRARY_PATH'] = ":"+oracle_libs elif not oracle_libs in os.environ.get('LD_LIBRARY_PATH'): os.environ['LD_LIBRARY_PATH'] += ...
In Python 2.4, how can I strip out characters after ';'?
1,178,335
18
2009-07-24T15:15:17Z
1,178,356
10
2009-07-24T15:18:36Z
[ "python", "string", "python-2.4" ]
Let's say I'm parsing a file, which uses `;` as the comment character. I don't want to parse comments. So if I a line looks like this: ``` example.com. 600 IN MX 8 s1b9.example.net ; hello! ``` Is there an easier/more-elegant way to strip chars out other than this: ``` rtr = '' for line in...
just do a split on the line by comment then get the first element eg ``` line.split(";")[0] ```
In Python 2.4, how can I strip out characters after ';'?
1,178,335
18
2009-07-24T15:15:17Z
1,178,360
67
2009-07-24T15:18:42Z
[ "python", "string", "python-2.4" ]
Let's say I'm parsing a file, which uses `;` as the comment character. I don't want to parse comments. So if I a line looks like this: ``` example.com. 600 IN MX 8 s1b9.example.net ; hello! ``` Is there an easier/more-elegant way to strip chars out other than this: ``` rtr = '' for line in...
I'd recommend saying ``` line.split(";")[0] ``` which will give you a string of all characters up to but not including the first ";" character. If no ";" character is present, then it will give you the entire line.
exit failed script run (python)
1,178,989
4
2009-07-24T17:22:47Z
1,179,002
15
2009-07-24T17:25:19Z
[ "python", "exception", "exit" ]
I have seen several questions about exiting a script after a task is successfully completed, but is there a way to do the same for a script which has failed? I am writing a testing script which just checks that a camera is functioning correctly. If the first test fails it is more than likely that the following tests wi...
Are you just looking for the [`exit()`](http://docs.python.org/library/sys.html#sys.exit) function? ``` import sys if 1 < 0: print >> sys.stderr, "Something is seriously wrong." sys.exit(1) ``` The (optional) parameter of `exit()` is the return code the script will return to the shell. Usually values different t...
Expat parsing in python 3
1,179,305
4
2009-07-24T18:19:40Z
1,179,454
7
2009-07-24T18:47:07Z
[ "python", "python-3.x", "python-2.6" ]
``` import xml.parsers.expat def start_element(name, attrs): print('Start element:', name, attrs) def end_element(name): print('End element:', name) def character_data(data): print('Character data: %s' % data) parser = xml.parsers.expat.ParserCreate() parser.StartElementHandler = start_element parser.En...
you need to open that file as binary: ``` parser.ParseFile(open('sample.xml', 'rb')) ```
Add text to Existing PDF using Python
1,180,115
50
2009-07-24T20:58:31Z
2,180,841
56
2010-02-01T23:28:31Z
[ "python", "pdf" ]
I need to add some extra text to an existing PDF using Python, what is the best way to go about this and what extra modules will I need to install. Note: Ideally I would like to be able to run this on both Windows and Linux, but at a push Linux only will do. Thanks in advance. Richard. Edit: pyPDF and ReportLab lo...
I know this is an older post, but I spent a long time trying to find a solution. I came across a decent one using only ReportLab and PyPDF so I thought I'd share: 1. read your PDF using PdfFileReader(), we'll call this *input* 2. create a new pdf containing your text to add using ReportLab, save this as a string objec...
Add text to Existing PDF using Python
1,180,115
50
2009-07-24T20:58:31Z
17,538,003
42
2013-07-09T00:16:42Z
[ "python", "pdf" ]
I need to add some extra text to an existing PDF using Python, what is the best way to go about this and what extra modules will I need to install. Note: Ideally I would like to be able to run this on both Windows and Linux, but at a push Linux only will do. Thanks in advance. Richard. Edit: pyPDF and ReportLab lo...
Here is a complete answer that I found elsewhere: ``` from pyPdf import PdfFileWriter, PdfFileReader import StringIO from reportlab.pdfgen import canvas from reportlab.lib.pagesizes import letter packet = StringIO.StringIO() # create a new PDF with Reportlab can = canvas.Canvas(packet, pagesize=letter) can.drawString...
Best way to sort 1M records in Python
1,180,240
7
2009-07-24T21:25:24Z
1,180,286
12
2009-07-24T21:38:22Z
[ "python" ]
I have a service that runs that takes a list of about 1,000,000 dictionaries and does the following ``` myHashTable = {} myLists = { 'hits':{}, 'misses':{}, 'total':{} } sorted = { 'hits':[], 'misses':[], 'total':[] } for item in myList: id = item.pop('id') myHashTable[id] = item for k, v in item.iteritems(): ...
You may find this related answer from Guido: [Sorting a million 32-bit integers in 2MB of RAM using Python](http://neopythonic.blogspot.com/2008/10/sorting-million-32-bit-integers-in-2mb.html)
Static vs instance methods of str in Python
1,180,303
4
2009-07-24T21:41:32Z
1,180,322
15
2009-07-24T21:45:16Z
[ "python", "string" ]
So, I have learnt that strings have a center method. ``` >>> 'a'.center(3) ' a ' ``` Then I have noticed that I can do the same thing using the 'str' object which is a type, since ``` >>> type(str) <type 'type'> ``` Using this 'type' object I could access the string methods like they were static functions. ``` >>>...
That's simply how classes in Python work: ``` class C: def method(self, arg): print "In C.method, with", arg o = C() o.method(1) C.method(o, 1) # Prints: # In C.method, with 1 # In C.method, with 1 ``` When you say `o.method(1)` you can think of it as a shorthand for `C.method(o, 1)`. A `method_descripto...
Static vs instance methods of str in Python
1,180,303
4
2009-07-24T21:41:32Z
1,180,424
8
2009-07-24T22:07:39Z
[ "python", "string" ]
So, I have learnt that strings have a center method. ``` >>> 'a'.center(3) ' a ' ``` Then I have noticed that I can do the same thing using the 'str' object which is a type, since ``` >>> type(str) <type 'type'> ``` Using this 'type' object I could access the string methods like they were static functions. ``` >>>...
> There should be one-- and preferably only one --obvious way to do it. Philosophically speaking, there *is* only one obvious way to do it: 'a'.center(3). The fact that there is an unobvious way of calling any method (i.e. the well-explained-by-previous-commentors o.method(x) and Type.method(o, x)) which is useful in ...
Activate a virtualenv via fabric as deploy user
1,180,411
115
2009-07-24T22:03:57Z
1,180,665
91
2009-07-24T23:32:09Z
[ "python", "virtualenv", "fabric", "automated-deploy" ]
I want to run my fabric script locally, which will in turn, log into my server, switch user to deploy, activate the projects .virtualenv, which will change dir to the project and issue a git pull. ``` def git_pull(): sudo('su deploy') # here i need to switch to the virtualenv run('git pull') ``` I typical...
Right now, you can do what I do, which is kludgy but works perfectly well\* (this usage assumes you're using virtualenvwrapper -- which you should be -- but you can easily substitute in the rather longer 'source' call you mentioned, if not): ``` def task(): workon = 'workon myvenv && ' run(workon + 'git pull')...
Activate a virtualenv via fabric as deploy user
1,180,411
115
2009-07-24T22:03:57Z
3,403,558
17
2010-08-04T07:48:49Z
[ "python", "virtualenv", "fabric", "automated-deploy" ]
I want to run my fabric script locally, which will in turn, log into my server, switch user to deploy, activate the projects .virtualenv, which will change dir to the project and issue a git pull. ``` def git_pull(): sudo('su deploy') # here i need to switch to the virtualenv run('git pull') ``` I typical...
I'm just using a simple wrapper function virtualenv() that can be called instead of run(). It doesn't use the cd context manager, so relative paths can be used. ``` def virtualenv(command): """ Run a command in the virtualenv. This prefixes the command with the source command. Usage: virtualenv...
Activate a virtualenv via fabric as deploy user
1,180,411
115
2009-07-24T22:03:57Z
5,359,988
122
2011-03-19T04:06:46Z
[ "python", "virtualenv", "fabric", "automated-deploy" ]
I want to run my fabric script locally, which will in turn, log into my server, switch user to deploy, activate the projects .virtualenv, which will change dir to the project and issue a git pull. ``` def git_pull(): sudo('su deploy') # here i need to switch to the virtualenv run('git pull') ``` I typical...
As an update to bitprophet's forecast: With Fabric 1.0 you can make use of prefix() and your own context managers. ``` from __future__ import with_statement from fabric.api import * from contextlib import contextmanager as _contextmanager env.hosts = ['servername'] env.user = 'deploy' env.keyfile = ['$HOME/.ssh/deplo...
Activate a virtualenv via fabric as deploy user
1,180,411
115
2009-07-24T22:03:57Z
18,397,479
7
2013-08-23T07:45:03Z
[ "python", "virtualenv", "fabric", "automated-deploy" ]
I want to run my fabric script locally, which will in turn, log into my server, switch user to deploy, activate the projects .virtualenv, which will change dir to the project and issue a git pull. ``` def git_pull(): sudo('su deploy') # here i need to switch to the virtualenv run('git pull') ``` I typical...
`virtualenvwrapper` can make this a little simpler 1. Using @nh2's approach (this approach also works when using `local`, but only for virtualenvwrapper installations where `workon` is in `$PATH`, in other words -- Windows) ``` from contextlib import contextmanager from fabric.api import prefix @contextm...
Using subprocess.Popen for Process with Large Output
1,180,606
20
2009-07-24T23:08:07Z
1,180,641
13
2009-07-24T23:23:35Z
[ "python", "subprocess" ]
I have some Python code that executes an external app which works fine when the app has a small amount of output, but hangs when there is a lot. My code looks like: ``` p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) errcode = p.wait() retval = p.stdout.read() errmess = p.stderr.r...
You're doing blocking reads to two files; the first needs to complete before the second starts. If the application writes a lot to stderr, and nothing to stdout, then your process will sit waiting for data on stdout that isn't coming, while the program you're running sits there waiting for the stuff it wrote to stderr ...
Spoofing the origination IP address of an HTTP request
1,180,878
19
2009-07-25T01:11:24Z
1,180,938
40
2009-07-25T01:46:29Z
[ "python", "http", "networking", "sockets", "urllib2" ]
This only needs to work on a single subnet and is not for malicious use. I have a load testing tool written in Python that basically blasts HTTP requests at a URL. I need to run performance tests against an IP-based load balancer, so the requests must come from a range of IP's. Most commercial performance tools provid...
This is a misunderstanding of HTTP. The HTTP protocol is based on top of [TCP](http://en.wikipedia.org/wiki/Transmission%5FControl%5FProtocol). The TCP protocol relies on a 3 way handshake to initialize requests. ![alt text](http://upload.wikimedia.org/wikipedia/commons/archive/c/c7/20051221162333!300px-Tcp-handshake....
Practical point of view: Why would I want to use Python with C++?
1,181,462
4
2009-07-25T07:14:52Z
1,181,475
21
2009-07-25T07:24:16Z
[ "c++", "python" ]
I've been seeing some examples of Python being used with c++, and I'm trying to understand why would someone want to do it. What are the benefits of calling C++ code from an external language such as Python? I'd appreciate a simple example - Boost::Python will do
It depends on your point of view: **Calling C++ code from a python application** You generally want to do this when performance is an issue. Highly dynamic languages like python are typically somewhat slower then native code such as C++. "Features" of C++ such as manual memory management allows for the development of...
Controlling mouse with Python
1,181,464
101
2009-07-25T07:15:30Z
1,181,517
7
2009-07-25T07:43:37Z
[ "python", "mouse" ]
How does one control the mouse cursor in Python, i.e. move it to certain position and click, under Windows?
<http://danielbaggio.blogspot.com/2009/03/python-mouse-move-in-5-lines-of-code.html> ``` from Xlib import X, display d = display.Display() s = d.screen() root = s.root root.warp_pointer(300,300) d.sync() ```
Controlling mouse with Python
1,181,464
101
2009-07-25T07:15:30Z
1,181,538
193
2009-07-25T07:57:19Z
[ "python", "mouse" ]
How does one control the mouse cursor in Python, i.e. move it to certain position and click, under Windows?
Tested on WinXP, Python 2.6 after installing [pywin32](http://sourceforge.net/projects/pywin32/files/) (pywin32-214.win32-py2.6.exe in my case): ``` import win32api, win32con def click(x,y): win32api.SetCursorPos((x,y)) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,x,y,0,0) win32api.mouse_event(win32c...
Controlling mouse with Python
1,181,464
101
2009-07-25T07:15:30Z
1,181,539
60
2009-07-25T07:57:19Z
[ "python", "mouse" ]
How does one control the mouse cursor in Python, i.e. move it to certain position and click, under Windows?
You can use `win32api` or `ctypes` module to use win32 apis for controlling mouse or any gui Here is a fun example to control mouse using win32api: ``` import win32api import time import math for i in range(500): x = int(500+math.sin(math.pi*i/100)*500) y = int(500+math.cos(i)*100) win32api.SetCursorPos(...
Controlling mouse with Python
1,181,464
101
2009-07-25T07:15:30Z
6,600,457
17
2011-07-06T17:24:03Z
[ "python", "mouse" ]
How does one control the mouse cursor in Python, i.e. move it to certain position and click, under Windows?
Check out the cross platform PyMouse: <https://github.com/pepijndevos/PyMouse/>
Controlling mouse with Python
1,181,464
101
2009-07-25T07:15:30Z
17,578,569
13
2013-07-10T18:46:50Z
[ "python", "mouse" ]
How does one control the mouse cursor in Python, i.e. move it to certain position and click, under Windows?
Another option is to use the cross-platform [AutoPy package](https://pypi.python.org/pypi/autopy/0.51). This package has two different options for moving the mouse: This code snippet will instantly move the cursor to position (200,200): ``` import autopy autopy.mouse.move(200,200) ``` If you instead want the cursor ...
Controlling mouse with Python
1,181,464
101
2009-07-25T07:15:30Z
27,046,948
30
2014-11-20T18:32:50Z
[ "python", "mouse" ]
How does one control the mouse cursor in Python, i.e. move it to certain position and click, under Windows?
Try with the [PyAutoGUI](https://pypi.python.org/pypi/PyAutoGUI) module. It's multiplatform. ``` pip install pyautogui ``` And so: ``` import pyautogui pyautogui.click(100, 100) ``` It also has other features: ``` import pyautogui pyautogui.moveTo(100, 150) pyautogui.moveRel(0, 10) # move mouse 10 pixels down pya...
Python base 36 encoding
1,181,919
22
2009-07-25T11:32:32Z
1,181,922
23
2009-07-25T11:35:25Z
[ "python" ]
How can I encode an integer with base 36 in Python and then decode it again?
Have you tried Wikipedia's sample code? ``` def base36encode(number, alphabet='0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'): """Converts an integer to a base36 string.""" if not isinstance(number, (int, long)): raise TypeError('number must be an integer') base36 = '' sign = '' if number < 0: ...
Python base 36 encoding
1,181,919
22
2009-07-25T11:32:32Z
1,181,924
27
2009-07-25T11:36:08Z
[ "python" ]
How can I encode an integer with base 36 in Python and then decode it again?
I wish I had read this before. Here is the answer: ``` def base36encode(number): if not isinstance(number, (int, long)): raise TypeError('number must be an integer') if number < 0: raise ValueError('number must be positive') alphabet, base36 = ['0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ', ''] ...
Python base 36 encoding
1,181,919
22
2009-07-25T11:32:32Z
11,406,745
8
2012-07-10T04:43:11Z
[ "python" ]
How can I encode an integer with base 36 in Python and then decode it again?
terrible answer, but was just playing around with this an thought i'd share. ``` import string, math int2base = lambda a, b: ''.join( [(string.digits + string.lowercase + string.uppercase)[(a/b**i)%b] for i in xrange(int(math.log(a, b)), -1, -1)] ) num = 1412823931503067241 test = int2base(num, 36) test...
Python: Multicore processing?
1,182,315
20
2009-07-25T15:31:35Z
1,182,343
17
2009-07-25T15:45:49Z
[ "python", "multicore", "multiprocessing" ]
I've been reading about Python's [multiprocessing module](http://docs.python.org/library/multiprocessing.html). I still don't think I have a very good understanding of what it can do. Let's say I have a quadcore processor and I have a list with 1,000,000 integers and I want the sum of all the integers. I could simply ...
Welcome the world of concurrent programming. What Python can (and can't) do depends on two things. 1. What the OS can (and can't) do. Most OS's allocate processes to cores. To use 4 cores, you need to break your problem into four processes. This is easier than it sounds. Sometimes. 2. What the underlying C libraries ...
Python: Multicore processing?
1,182,315
20
2009-07-25T15:31:35Z
1,182,350
25
2009-07-25T15:48:51Z
[ "python", "multicore", "multiprocessing" ]
I've been reading about Python's [multiprocessing module](http://docs.python.org/library/multiprocessing.html). I still don't think I have a very good understanding of what it can do. Let's say I have a quadcore processor and I have a list with 1,000,000 integers and I want the sum of all the integers. I could simply ...
Yes, it's possible to do this summation over several processes, very much like doing it with multiple threads: ``` from multiprocessing import Process, Queue def do_sum(q,l): q.put(sum(l)) def main(): my_list = range(1000000) q = Queue() p1 = Process(target=do_sum, args=(q,my_list[:500000])) p2...
Python: Multicore processing?
1,182,315
20
2009-07-25T15:31:35Z
1,182,364
7
2009-07-25T15:55:45Z
[ "python", "multicore", "multiprocessing" ]
I've been reading about Python's [multiprocessing module](http://docs.python.org/library/multiprocessing.html). I still don't think I have a very good understanding of what it can do. Let's say I have a quadcore processor and I have a list with 1,000,000 integers and I want the sum of all the integers. I could simply ...
Sure, for example: ``` from multiprocessing import Process, Queue thelist = range(1000*1000) def f(q, sublist): q.put(sum(sublist)) def main(): start = 0 chunk = 500*1000 queue = Queue() NP = 0 subprocesses = [] while start < len(thelist): p = Process(target=f, args=(queue, thelist...
How to get the distinct value of one of my models in Google App Engine
1,183,102
5
2009-07-25T21:22:49Z
1,183,146
7
2009-07-25T21:42:23Z
[ "python", "google-app-engine", "gae-datastore" ]
I have a model, below, and I would like to get all the distinct `area` values. The SQL equivalent is `select distinct area from tutorials` ``` class Tutorials(db.Model): path = db.StringProperty() area = db.StringProperty() sub_area = db.StringProperty() title = db.StringProperty() content = db.B...
Datastore cannot do this for you in a single query. A datastore request always returns a consecutive block of results from an index, and an index always consists of all the entities of a given type, sorted according to whatever orders are specified. There's no way for the query to skip items just because one field has ...
To SHA512-hash a password in MySQL database by Python
1,183,161
3
2009-07-25T21:49:58Z
1,183,213
12
2009-07-25T22:15:17Z
[ "python", "mysql", "database", "hash" ]
This question is based [on the answer](http://stackoverflow.com/questions/1182798/to-improve-a-relation-figure-for-a-database/1182807#1182807). I would like to know how you can hash your password by SHA1 and then remove the clear-text password in a MySQL database by Python. **How can you hash your password in a MySQL...
As the documentation says you should use [hashlib](http://docs.python.org/library/hashlib.html) library not the sha since python 2.5. It is pretty easy to do make a hash. ``` hexhash = hashlib.sha512("some text").hexdigest() ``` This hex number will be easy to store in a database.
To SHA512-hash a password in MySQL database by Python
1,183,161
3
2009-07-25T21:49:58Z
1,183,439
7
2009-07-26T00:37:23Z
[ "python", "mysql", "database", "hash" ]
This question is based [on the answer](http://stackoverflow.com/questions/1182798/to-improve-a-relation-figure-for-a-database/1182807#1182807). I would like to know how you can hash your password by SHA1 and then remove the clear-text password in a MySQL database by Python. **How can you hash your password in a MySQL...
If you're storing passwords in a database, a recommended article to read is Jeff's [You're Probably Storing Passwords Incorrectly](http://www.codinghorror.com/blog/archives/000953.html). This article describes the use of *salt* and some of the things about storing passwords that are deceptively easy to get wrong.
Is there something like Python's 'with' in C#?
1,183,233
8
2009-07-25T22:27:18Z
1,183,236
21
2009-07-25T22:29:24Z
[ "c#", "python", "exception" ]
Python has a nice keyword since 2.6 called **with**. Is there something similar in C#?
The equivalent is the `using` statement An example would be ``` using (var reader = new StreamReader(path)) { DoSomethingWith(reader); } ``` The restriction is that the type of the variable scoped by the using clause must implement `IDisposable` and it is its `Dispose()` method that gets called on exit fro...
Unbuffered read from process using subprocess in Python
1,183,643
20
2009-07-26T03:21:35Z
1,183,654
27
2009-07-26T03:30:39Z
[ "python", "subprocess" ]
I am trying to read from a process that produces long and time-consuming output. However, I want to catch it's output *as and when* it is produced. But using something like the following seems to be buffering the command's output, so I end up getting the output lines all at once: ``` p = subprocess.Popen(cmd, shell=Tr...
The file iterator is doing some internal buffering [on its own](http://docs.python.org/library/stdtypes.html#file.next). Try this: ``` line = p.stdout.readline() while line: print line line = p.stdout.readline() ```
Python Properties & Swig
1,183,716
14
2009-07-26T04:17:48Z
4,750,081
27
2011-01-20T16:55:31Z
[ "c++", "python", "properties", "swig" ]
I am attempting to create python bindings for some C++ code using swig. I seem have run into a problem trying to create python properties from some accessor functions I have for methods like the following: ``` class Player { public: void entity(Entity* entity); Entity* entity() const; }; ``` I tried creating a pr...
There is an easy way to make python properties from methods with swig. Suppose C++ code Example.h: **C++ header** ``` class Example{ public: void SetX(int x); int GetX() const; }; ``` Lets convert this setter and getter to python propery 'x'. The trick is in .i file. We add some "swiggy" inlin...
Python Properties & Swig
1,183,716
14
2009-07-26T04:17:48Z
11,386,066
13
2012-07-08T19:40:20Z
[ "c++", "python", "properties", "swig" ]
I am attempting to create python bindings for some C++ code using swig. I seem have run into a problem trying to create python properties from some accessor functions I have for methods like the following: ``` class Player { public: void entity(Entity* entity); Entity* entity() const; }; ``` I tried creating a pr...
# Use Attributes.i In the SWIG Lib folder is a file called "attributes.i" which is not discussed in the documentation but that contains inline documentation. All you have to do is add the following line to your interface file. ``` %include <attributes.i> ``` You then receive a number of macros (such as %attribute) ...
How can I use Facebook Connect with Google App Engine without using Django?
1,183,863
10
2009-07-26T06:06:54Z
1,726,735
10
2009-11-13T02:21:00Z
[ "python", "google-app-engine", "authentication", "facebook" ]
I'm developing on the Google App Engine and I would like to integrate Facebook Connect into my site as a means for registering and authenticating. In the past, I relied on Google's Accounts API for user registration. I'm trying to use Google's webapp framework instead of Django but it seems that all the resources regar...
It's not Facebook Connect, really, but at least it's webapp FBML handling: [http://github.com/WorldMaker/pyfacebook/.../facebook/webappfb.py](http://github.com/WorldMaker/pyfacebook/blob/35b6e4dbb83ca14fbb23046bd675fa4d80d568c9/facebook/webappfb.py) [This guy made a post](http://forum.developers.facebook.com/viewtopic...
why __builtins__ is both module and dict
1,184,016
8
2009-07-26T08:05:17Z
1,184,036
10
2009-07-26T08:25:03Z
[ "python", "python-module", "built-in" ]
I am using the built-in module to insert a few instances, so they can be accessed globally for debugging purposes. The problem with the `__builtins__` module is that it is a module in a main script and is a dict in modules, but as my script depending on cases can be a main script or a module, I have to do this: ``` if...
I think you want the `__builtin__` module (note the singular). See the docs: > [27.3. `__builtin__` — Built-in objects](http://docs.python.org/library/__builtin__.html) > > **CPython implementation detail:** Most modules have the name `__builtins__` (note the `'s'`) made available as part of their globals. The valu...
Python: extending int and MRO for __init__
1,184,337
10
2009-07-26T11:27:59Z
1,184,377
7
2009-07-26T11:49:20Z
[ "python", "class-design", "override" ]
In Python, I'm trying to extend the builtin 'int' type. In doing so I want to pass in some keywoard arguments to the constructor, so I do this: ``` class C(int): def __init__(self, val, **kwargs): super(C, self).__init__(val) # Do something with kwargs here... ``` However while calling `C(3)` w...
The docs for the Python data model advise using `__new__`: [object.**new**(cls[, ...])](http://docs.python.org/reference/datamodel.html#object.%5F%5Fnew%5F%5F) > **new**() is intended mainly to allow subclasses of immutable types (like int, str, or tuple) to customize instance creation. It is also commonly overridden...
Creating child frames of main frame in wxPython
1,185,156
12
2009-07-26T18:08:57Z
1,185,226
10
2009-07-26T18:37:56Z
[ "python", "wxpython" ]
I am trying create a new frame in wxPython that is a child of the main frame so that when the main frame is closed, the child frame will also be closed. Here is a simplified example of the problem that I am having: ``` #! /usr/bin/env python import wx class App(wx.App): def OnInit(self): frame = MainFra...
``` class AboutFrame(wx.Frame): title = "About this program" def __init__(self): wx.Frame.__init__(self, wx.GetApp().TopWindow, title=self.title) ```
Passing expressions to functions in python?
1,185,199
5
2009-07-26T18:26:21Z
1,185,254
11
2009-07-26T18:50:41Z
[ "python", "parameters", "sqlalchemy" ]
I'm not quite sure what i mean here, so please bear with me.. In sqlalchemy, it appears i'm supposed to pass an expression? to [filter()](http://www.sqlalchemy.org/docs/05/ormtutorial.html#common-filter-operators) in certain cases. When i try to implement something like this myself, i end up with: ``` >>> def someFun...
You can achieve your example if you make "op" a function: ``` >>> def magic(left, op, right): ... return op(left, right) ... >>> magic(5, (lambda a, b: a == b), 5) True >>> magic(5, (lambda a, b: a == b), 4) False ``` This is more Pythonic than passing a String. It's how functions like...
Algorithms to identify Markov generated content?
1,185,369
11
2009-07-26T19:45:13Z
1,185,431
8
2009-07-26T20:11:29Z
[ "python", "algorithm", "markov" ]
Markov chains are a (almost standard) way to generate [random gibberish](http://uswaretech.com/blog/2009/06/pseudo-random-text-markov-chains-python/) which looks intelligent to untrained eye. How would you go about identifying markov generated text from human written text. It would be awesome if the resources you poin...
One simple approach would be to have a large group of humans read input text for you and see if the text makes sense. I'm only half-joking, this is a tricky problem. I believe this to be a hard problem, because Markov-chain generated text is going to have a lot of the same properties of real human text in terms of wor...
How do I start a session in a Python web application?
1,185,406
4
2009-07-26T20:00:26Z
1,185,437
7
2009-07-26T20:13:47Z
[ "python", "session" ]
This question is based on [this answer](http://stackoverflow.com/questions/1184888/to-understand-a-line-about-a-login-variable-in-a-session/1184931#1184931). I'm looking for a function similar to PHP's `session_start()` for Python. I want to access a dictionary like `$_SESSION` in PHP which becomes available after run...
As someone who comes from PHP and is working his way into Python I can tell you that [Django](http://www.djangoproject.com/) is a good way to start dealing with Python on the web. This is especially true if you've been using [MVC frameworks in PHP](http://www.phpwact.org/php/mvc%5Fframeworks). That said, Django has bui...
How do I start a session in a Python web application?
1,185,406
4
2009-07-26T20:00:26Z
1,185,496
8
2009-07-26T20:43:45Z
[ "python", "session" ]
This question is based on [this answer](http://stackoverflow.com/questions/1184888/to-understand-a-line-about-a-login-variable-in-a-session/1184931#1184931). I'm looking for a function similar to PHP's `session_start()` for Python. I want to access a dictionary like `$_SESSION` in PHP which becomes available after run...
Let me address some things that might be related to your question...it may not be relevant for you, but I think others might come here with the exact same question and might benefit from my (limited) experience...because I also had this question at one time. Speaking as someone who went from PHP to Python (and never l...
How to trim whitespace (including tabs)?
1,185,524
623
2009-07-26T20:54:38Z
1,185,528
17
2009-07-26T20:56:06Z
[ "python", "string", "trim", "strip" ]
Is there a function that will trim not only spaces for whitespace, but also tabs?
For leading and trailing whitespace: ``` s = ' foo \t ' print s.strip() ``` Otherwise, a regular expression works: ``` import re pat = re.compile(r'\s+') s = ' \t foo \t bar \t ' print pat.sub('', s) ```
How to trim whitespace (including tabs)?
1,185,524
623
2009-07-26T20:54:38Z
1,185,529
908
2009-07-26T20:56:26Z
[ "python", "string", "trim", "strip" ]
Is there a function that will trim not only spaces for whitespace, but also tabs?
Whitespace on the both sides: ``` s = " \t a string example\t " s = s.strip() ``` Whitespace on the right side: ``` s = s.rstrip() ``` Whitespace on the left side: ``` s = s.lstrip() ``` As [thedz](http://stackoverflow.com/users/84380/thedz) points out, you can provide an argument to strip arbitrary characters ...
How to trim whitespace (including tabs)?
1,185,524
623
2009-07-26T20:54:38Z
9,255,908
9
2012-02-13T05:16:24Z
[ "python", "string", "trim", "strip" ]
Is there a function that will trim not only spaces for whitespace, but also tabs?
``` #how to trim a multi line string or a file s=""" line one \tline two\t line three """ #line1 starts with a space, #2 starts and ends with a tab, #3 ends with a space. s1=s.splitlines() print s1 [' line one', '\tline two\t', 'line three '] print [i.strip() for i in s1] ['line one', 'line two', 'line three'] ...
How to trim whitespace (including tabs)?
1,185,524
623
2009-07-26T20:54:38Z
9,326,184
39
2012-02-17T10:00:00Z
[ "python", "string", "trim", "strip" ]
Is there a function that will trim not only spaces for whitespace, but also tabs?
Python `trim` method is called `strip`: ``` str.strip() #trim str.lstrip() #ltrim str.rstrip() #rtrim ```
How to trim whitespace (including tabs)?
1,185,524
623
2009-07-26T20:54:38Z
24,165,293
13
2014-06-11T14:18:09Z
[ "python", "string", "trim", "strip" ]
Is there a function that will trim not only spaces for whitespace, but also tabs?
You can also use very simple, and basic function: [str.replace()](https://docs.python.org/2/library/stdtypes.html#str.replace), works with the whitespaces and tabs: ``` >>> whitespaces = " abcd ef gh ijkl " >>> tabs = " abcde fgh ijkl" >>> print whitespaces.replace(" ", "") abcdefghijkl >>...
Python loop counter in a for loop
1,185,545
101
2009-07-26T21:05:26Z
1,185,557
188
2009-07-26T21:09:15Z
[ "loops", "for-loop", "python" ]
In my example code below, is the counter = 0 really required, or is there a better, more Python, way to get access to a loop counter? I saw a few PEPs related to loop counters, but they were either deferred or rejected ([PEP 212](http://www.python.org/dev/peps/pep-0212/) and [PEP 281](http://www.python.org/dev/peps/pep...
**Use [`enumerate()`](http://docs.python.org/library/functions.html#enumerate) like so:** ``` def draw_menu(options, selected_index): for counter, option in enumerate(options): if counter == selected_index: print " [*] %s" % option else: print " [ ] %s" % option options...
How do I define a unique property for a Model in Google App Engine?
1,185,628
32
2009-07-26T21:41:29Z
1,185,703
21
2009-07-26T22:13:16Z
[ "python", "google-app-engine", "google-cloud-datastore" ]
I need some properties to be unique. How can I achieve this? Is there something like `unique=True`? I'm using Google App Engine for Python.
There's no built-in constraint for making sure a value is unique. You can do this however: ``` query = MyModel.all(keys_only=True).filter('unique_property', value_to_be_used) entity = query.get() if entity: raise Exception('unique_property must have a unique value!') ``` I use `keys_only=True` because it'll impro...
How do I define a unique property for a Model in Google App Engine?
1,185,628
32
2009-07-26T21:41:29Z
5,829,926
24
2011-04-29T08:44:07Z
[ "python", "google-app-engine", "google-cloud-datastore" ]
I need some properties to be unique. How can I achieve this? Is there something like `unique=True`? I'm using Google App Engine for Python.
Google has provided function to do that: <http://code.google.com/appengine/docs/python/datastore/modelclass.html#Model_get_or_insert> ``` Model.get_or_insert(key_name, **kwds) ``` Attempts to get the entity of the model's kind with the given key name. If it exists, get\_or\_insert() simply returns it. If it doesn't ...
How to solve the "Mastermind" guessing game?
1,185,634
34
2009-07-26T21:43:36Z
1,185,638
39
2009-07-26T21:44:24Z
[ "python", "algorithm" ]
How would you create an algorithm to solve the following puzzle, "Mastermind"? Your opponent has chosen four different colours from a set of six (yellow, blue, green, red, orange, purple). You must guess which they have chosen, and in what order. After each guess, your opponent tells you how many (but not which) of th...
Key tools: entropy, greediness, branch-and-bound; Python, generators, itertools, decorate-undecorate pattern In answering this question, I wanted to build up a language of useful functions to explore the problem. I will go through these functions, describing them and their intent. Originally, these had extensive docs,...
How to solve the "Mastermind" guessing game?
1,185,634
34
2009-07-26T21:43:36Z
1,185,776
7
2009-07-26T22:47:24Z
[ "python", "algorithm" ]
How would you create an algorithm to solve the following puzzle, "Mastermind"? Your opponent has chosen four different colours from a set of six (yellow, blue, green, red, orange, purple). You must guess which they have chosen, and in what order. After each guess, your opponent tells you how many (but not which) of th...
Have you seem Raymond Hettingers [attempt](http://code.activestate.com/recipes/496907/)? They certainly match up to some of your requirements. I wonder how his solutions compares to yours.
How to solve the "Mastermind" guessing game?
1,185,634
34
2009-07-26T21:43:36Z
1,353,367
10
2009-08-30T07:41:54Z
[ "python", "algorithm" ]
How would you create an algorithm to solve the following puzzle, "Mastermind"? Your opponent has chosen four different colours from a set of six (yellow, blue, green, red, orange, purple). You must guess which they have chosen, and in what order. After each guess, your opponent tells you how many (but not which) of th...
I once wrote a "[Jotto](http://en.wikipedia.org/wiki/Jotto)" solver which is essentially "Master Mind" with words. (We each pick a word and we take turns guessing at each other's word, scoring "right on" (exact) matches and "elsewhere" (correct letter/color, but wrong placement). **The key to solving such a problem is...
Python: is os.read() / os.write() on an os.pipe() threadsafe?
1,185,660
7
2009-07-26T21:53:25Z
1,186,161
8
2009-07-27T02:19:07Z
[ "python", "multithreading", "thread-safety", "pipe" ]
Consider: ``` pipe_read, pipe_write = os.pipe() ``` Now, I would like to know two things: **(1)** I have two threads. If I guarantee that only one is reading `os.read(pipe_read,n)` and the other is only writing `os.write(pipe_write)`, will I have any problem, even if the two threads do it simultaneously? Will I get ...
`os.read` and `os.write` on the two fds returned from `os.pipe` is threadsafe, but you appear to demand more than that. Sub `(1)`, yes, there is no "atomicity" guarantee for sinle reads or writes -- the scenario you depict (a single short write ends up producing two reads) is entirely possible. (In general, os.whatever...
Using a caesarian cipher on a string of text in python?
1,185,775
2
2009-07-26T22:47:15Z
1,185,809
7
2009-07-26T22:58:39Z
[ "python", "encryption" ]
I'm trying to slowly knock out all of the intricacies of python. Basically, I'm looking for some way, in python, to take a string of characters and push them all over by 'x' characters. For example, inputing abcdefg will give me cdefghi (if x is 2).
My first version: ``` >>> key = 2 >>> msg = "abcdefg" >>> ''.join( map(lambda c: chr(ord('a') + (ord(c) - ord('a') + key)%26), msg) ) 'cdefghi' >>> msg = "uvwxyz" >>> ''.join( map(lambda c: chr(ord('a') + (ord(c) - ord('a') + key)%26), msg) ) 'wxyzab' ``` (Of course it works as expected only if msg is lowercase...)...
Can I use C++ features while extending Python?
1,185,878
5
2009-07-26T23:30:23Z
1,185,907
8
2009-07-26T23:44:31Z
[ "c++", "python", "c", "python-c-api", "python-c-extension" ]
The Python manual says that you can create modules for Python in both C and C++. Can you take advantage of things like classes and templates when using C++? Wouldn't it create incompatibilities with the rest of the libraries and with the interpreter?
It doesn't matter whether your implementation of the hook functions is implemented in C or in C++. In fact, I've already seen some Python extensions which make active use of C++ templates and even the Boost library. **No problem.** :-)
Read content of RAR file into memory in Python
1,185,959
6
2009-07-27T00:25:14Z
1,186,011
7
2009-07-27T00:54:58Z
[ "python", "linux", "stream", "rar" ]
I'm looking for a way to read specific files from a rar archive into memory. Specifically they are a collection of numbered image files (I'm writing a comic reader). While I can simply unrar these files and load them as needed (deleting them when done), I'd prefer to avoid that if possible. That all said, I'd prefer a...
See the rarfile module: * http://grue.l-t.ee/~marko/src/rarfile/README.html * <http://pypi.python.org/pypi/rarfile/> * <https://github.com/markokr/rarfile>
What is the best way to call a Python script from another Python script?
1,186,789
136
2009-07-27T06:52:48Z
1,186,818
78
2009-07-27T07:03:19Z
[ "python", "eval" ]
I have a script named test1.py which is not in a module. It just has code that should execute when the script itself is run. There are no functions, classes, methods, etc. I have another script which runs as a service. I want to call test1.py from the script running as a service. For example: ### File test1.py ``` p...
This is possible in Python 2 using ``` execfile("test2.py") ``` See the [documentation](https://docs.python.org/2/library/functions.html#execfile) for the handling of namespaces, if important in your case. However, you should consider using a different approach; your idea (from what I can see) doesn't look very clea...
What is the best way to call a Python script from another Python script?
1,186,789
136
2009-07-27T06:52:48Z
1,186,826
8
2009-07-27T07:06:37Z
[ "python", "eval" ]
I have a script named test1.py which is not in a module. It just has code that should execute when the script itself is run. There are no functions, classes, methods, etc. I have another script which runs as a service. I want to call test1.py from the script running as a service. For example: ### File test1.py ``` p...
You should not be doing this. Instead, do: test1.py: ``` def print_test(): print "I am a test" print "see! I do nothing productive." ``` service.py ``` #near the top from test1 import print_test #lots of stuff here print_test() ```
What is the best way to call a Python script from another Python script?
1,186,789
136
2009-07-27T06:52:48Z
1,186,844
14
2009-07-27T07:11:51Z
[ "python", "eval" ]
I have a script named test1.py which is not in a module. It just has code that should execute when the script itself is run. There are no functions, classes, methods, etc. I have another script which runs as a service. I want to call test1.py from the script running as a service. For example: ### File test1.py ``` p...
If you want test1.py to remain executable with the same functionality as when it's called inside service.py, then do something like: test1.py ``` def main(): print "I am a test" print "see! I do nothing productive." if __name__ == "__main__": main() ``` service.py ``` import test1 # lots of stuff here ...
What is the best way to call a Python script from another Python script?
1,186,789
136
2009-07-27T06:52:48Z
1,186,847
134
2009-07-27T07:12:30Z
[ "python", "eval" ]
I have a script named test1.py which is not in a module. It just has code that should execute when the script itself is run. There are no functions, classes, methods, etc. I have another script which runs as a service. I want to call test1.py from the script running as a service. For example: ### File test1.py ``` p...
The usual way to do this is something like the following. test1.py ``` def some_func(): print 'in test 1, unproductive' if __name__ == '__main__': # test1.py executed as script # do something some_func() ``` service.py ``` import test1 def service_func(): print 'service func' if __name__ == '...
What is the best way to call a Python script from another Python script?
1,186,789
136
2009-07-27T06:52:48Z
11,230,471
34
2012-06-27T16:01:06Z
[ "python", "eval" ]
I have a script named test1.py which is not in a module. It just has code that should execute when the script itself is run. There are no functions, classes, methods, etc. I have another script which runs as a service. I want to call test1.py from the script running as a service. For example: ### File test1.py ``` p...
Another way: ### File test1.py: ``` print "test1.py" ``` ### File service.py: ``` import subprocess subprocess.call("test1.py", shell=True) ``` The advantage to this method is that you don't have to edit an existing Python script to put all its code into a subroutine.
Persistent Python Command-Line History
1,186,958
14
2009-07-27T07:53:11Z
1,186,981
13
2009-07-27T08:02:14Z
[ "interpreter", "python" ]
I'd like to be able to "up-arrow" to commands that I input in a previous Python interpreter. I have found the `readline` module which offers functions like: `read_history_file`, `write_history_file`, and `set_startup_hook`. I'm not quite savvy enough to put this into practice though, so could someone please help? My th...
I think the suggestions in the Python documentation pretty much cover what you want. Look at the example pystartup file toward the end of section 13.3: * <http://docs.python.org/tutorial/interactive.html> or see this page: * <http://rc98.net/pystartup> But, for an out of the box interactive shell that provides all ...
How to check if some process is running in task manager with python
1,187,264
4
2009-07-27T09:26:20Z
1,187,338
10
2009-07-27T09:54:04Z
[ "python", "process" ]
I have one function in python which should start running when some process (eg. proc.exe) showed up in tasks manager. How can I monitor processes running in tasks manager with python?
here is something, I've adapted from [microsoft](http://www.microsoft.com/technet/scriptcenter/scripts/python/pyindex.mspx?mfr=true) ``` import win32com.client strComputer = "." objWMIService = win32com.client.Dispatch("WbemScripting.SWbemLocator") objSWbemServices = objWMIService.ConnectServer(strComputer,"root\cimv2...
How to exit from Python without traceback?
1,187,970
156
2009-07-27T12:44:15Z
1,187,975
30
2009-07-27T12:45:38Z
[ "python", "exit", "traceback" ]
I would like to know how to I exit from Python without having an traceback dump on the output. I still want want to be able to return an error code but I do not want to display the traceback log. I want to be able to exit using `exit(number)` without trace but in case of an Exception (not an exit) I want the trace.
``` import sys sys.exit(1) ```
How to exit from Python without traceback?
1,187,970
156
2009-07-27T12:44:15Z
1,188,086
182
2009-07-27T13:10:40Z
[ "python", "exit", "traceback" ]
I would like to know how to I exit from Python without having an traceback dump on the output. I still want want to be able to return an error code but I do not want to display the traceback log. I want to be able to exit using `exit(number)` without trace but in case of an Exception (not an exit) I want the trace.
You are presumably encountering an exception and the program is exiting because of this (with a traceback). The first thing to do therefore is to catch that exception, before exiting cleanly (maybe with a message, example given). Try something like this in your `main` routine: ``` import sys, traceback def main(): ...
How to exit from Python without traceback?
1,187,970
156
2009-07-27T12:44:15Z
1,190,864
49
2009-07-27T21:55:27Z
[ "python", "exit", "traceback" ]
I would like to know how to I exit from Python without having an traceback dump on the output. I still want want to be able to return an error code but I do not want to display the traceback log. I want to be able to exit using `exit(number)` without trace but in case of an Exception (not an exit) I want the trace.
Perhaps you're trying to catch all exceptions and this is catching the `SystemExit` exception raised by `sys.exit()`? ``` import sys try: sys.exit(1) # Or something that calls sys.exit() except SystemExit as e: sys.exit(e) except: # Cleanup and reraise. This will print a backtrace. # (Insert your clea...
How to specify which eth interface Django test server should listen on?
1,188,205
11
2009-07-27T13:38:43Z
1,188,359
27
2009-07-27T14:09:34Z
[ "python", "django", "networking", "ethernet" ]
As the title says, in a multiple ethernet interfaces with multiple IP environment, the default Django test server is not attached to the network that I can access from my PC. Is there any way to specify the interface which Django test server should use? -- Added -- The network configuration is here. I'm connecting to...
I think the OP is referring to having multiple interfaces configured on the test machine. You can specify the IP address that Django will bind to as follows: ``` # python manage.py runserver 0.0.0.0:8000 ``` This would bind Django to all interfaces on port 8000. You can pass any active IP address in place of 0.0.0.0...
Writing in file's actual position in Python
1,188,214
2
2009-07-27T13:40:53Z
1,188,221
7
2009-07-27T13:43:45Z
[ "python", "file" ]
I want to read a line in a file and insert the new line ("\n") character in the n position on a line, so that a 9-character line, for instance, gets converted into three 3-character lines, like this: ``` "123456789" (before) "123\n456\n789" (after) ``` I've tried with this: ``` f = open(file, "r+") f.write("12345678...
I don't think there is any way to do that in the way you are trying to: you would have to read in to the end of the file from the position you want to insert, then write your new character at the position you wish it to be, then write the original data back after it. This is the same way things would work in C or any l...
What are the benefits of not using cPickle to create a persistent storage for data?
1,188,585
5
2009-07-27T14:45:12Z
1,188,704
9
2009-07-27T15:04:38Z
[ "python", "database", "data-structures", "persistence" ]
I'm considering the idea of creating a persistent storage like a dbms engine, what would be the benefits to create a custom binary format over directly cPickling the object and/or using the shelve module?
Pickling is a two-face coin. On one side, you have a way to store your object in a very easy way. Just four lines of code and you pickle. You have the object exactly as it is. On the other side, it can become a compatibility nightmare. You cannot unpickle objects if they are not defined in your code, exactly as they ...
Good or bad practice in Python: import in the middle of a file
1,188,640
38
2009-07-27T14:53:25Z
1,188,657
7
2009-07-27T14:57:15Z
[ "python", "python-import" ]
Suppose I have a relatively long module, but need an external module or method only once. Is it considered OK to import that method or module in the middle of the module? Or should `import`s only be in the first part of the module. Example: ``` import string, pythis, pythat ... ... ... ... def func(): blah ...
It is considered "Good Form" to group all imports together at the start of the file. > Modules can import other modules. It is customary but not required to place all import statements at the beginning of a module (or script, for that matter). The imported module names are placed in the importing module’s global sym...
Good or bad practice in Python: import in the middle of a file
1,188,640
38
2009-07-27T14:53:25Z
1,188,672
41
2009-07-27T14:59:05Z
[ "python", "python-import" ]
Suppose I have a relatively long module, but need an external module or method only once. Is it considered OK to import that method or module in the middle of the module? Or should `import`s only be in the first part of the module. Example: ``` import string, pythis, pythat ... ... ... ... def func(): blah ...
[PEP 8](http://www.python.org/dev/peps/pep-0008/) authoritatively states: > Imports are always put at the top of > the file, just after any module > comments and docstrings, and before module globals and constants. PEP 8 should be the basis of any "in-house" style guide, since it summarizes what the core Python team ...
Good or bad practice in Python: import in the middle of a file
1,188,640
38
2009-07-27T14:53:25Z
1,188,674
9
2009-07-27T14:59:13Z
[ "python", "python-import" ]
Suppose I have a relatively long module, but need an external module or method only once. Is it considered OK to import that method or module in the middle of the module? Or should `import`s only be in the first part of the module. Example: ``` import string, pythis, pythat ... ... ... ... def func(): blah ...
If the imported module is infrequently used and the import is expensive, the in-the-middle-import is OK. **Otherwise, is it wise to follow Alex Martelli's suggestion.**
Good or bad practice in Python: import in the middle of a file
1,188,640
38
2009-07-27T14:53:25Z
1,188,693
13
2009-07-27T15:02:08Z
[ "python", "python-import" ]
Suppose I have a relatively long module, but need an external module or method only once. Is it considered OK to import that method or module in the middle of the module? Or should `import`s only be in the first part of the module. Example: ``` import string, pythis, pythat ... ... ... ... def func(): blah ...
There was a detailed discussion of this topic on the Python mailing list in 2001: <https://mail.python.org/pipermail/python-list/2001-July/071567.html>
Good or bad practice in Python: import in the middle of a file
1,188,640
38
2009-07-27T14:53:25Z
1,189,199
12
2009-07-27T16:27:29Z
[ "python", "python-import" ]
Suppose I have a relatively long module, but need an external module or method only once. Is it considered OK to import that method or module in the middle of the module? Or should `import`s only be in the first part of the module. Example: ``` import string, pythis, pythat ... ... ... ... def func(): blah ...
Everyone else has already mentioned the PEPs, but also take care to **not** have import statements in the middle of critical code. At least under Python 2.6, there are several more bytecode instructions required when a function has an import statement. ``` >>> def f(): from time import time print time() >>> d...
Why the trailing slash in the web service is so important?
1,188,927
7
2009-07-27T15:43:16Z
1,188,943
19
2009-07-27T15:46:21Z
[ "php", "python", "wsdl", "soappy" ]
I was testing a web service in PHP and Python. The address of the web service was, let's say, `http://my.domain.com/my/webservice`. When I tested the web service in PHP using that URL everything worked fine. But, when I used the same location but in Python using SOAPpy I got an error. Below is the code I used to commu...
They're different URLs. `http://my.domain.com/my/webservice` implies a file `webservice` in the `my` folder. `http://my.domain.com/my/webservice/` implies the default document inside the my/webservice folder. Many webservers will automatically correct such URLs, but it is not required for them to do so.
What are the Python thread + Unix signals semantics?
1,189,072
8
2009-07-27T16:08:34Z
1,189,162
9
2009-07-27T16:21:02Z
[ "python", "unix", "multithreading", "posix", "signals" ]
What are the rules surrounding Python threads and how Unix signals are handled? Is `KeyboardInterrupt`, which is triggered by `SIGINT` but handled internally by the Python runtime, handled differently?
First, when setting up signal handlers using the [`signal`](http://docs.python.org/library/signal.html) module, you must create them in the main thread. You will receive an exception if you try to create them in a separate thread. Signal handlers registered via the `signal.signal()` function will always be called in t...
Unicode to UTF8 for CSV Files - Python via xlrd
1,189,111
18
2009-07-27T16:13:48Z
1,189,575
24
2009-07-27T17:37:03Z
[ "python", "unicode", "encoding", "csv", "xlrd" ]
I'm trying to translate an Excel spreadsheet to CSV using the Python xlrd and csv modules, but am getting hung up on encoding issues. Xlrd produces output from Excel in Unicode, and the CSV module requires UTF-8. I imaging that this has nothing to do with the xlrd module: everything works fine outputing to stdout or o...
I expect the `cell_value` return value is the unicode string that's giving you problems (please print its `type()` to confirm that), in which case you should be able to solve it by changing this one line: ``` this_row.append(s.cell_value(row,col)) ``` to: ``` this_row.append(s.cell_value(row,col).encode('utf8')) ```...
Unicode to UTF8 for CSV Files - Python via xlrd
1,189,111
18
2009-07-27T16:13:48Z
1,193,301
8
2009-07-28T10:45:53Z
[ "python", "unicode", "encoding", "csv", "xlrd" ]
I'm trying to translate an Excel spreadsheet to CSV using the Python xlrd and csv modules, but am getting hung up on encoding issues. Xlrd produces output from Excel in Unicode, and the CSV module requires UTF-8. I imaging that this has nothing to do with the xlrd module: everything works fine outputing to stdout or o...
You asked for explanations, but some of the phenomena are inexplicable without your help. (A) Strings in XLS files created by Excel 97 onwards are encoded in Latin1 if possible otherwise in UTF16LE. Each string carries a flag telling which was used. Earlier Excels encoded strings according to the user's "codepage". In...
How do I resolve an SRV record in Python?
1,189,253
4
2009-07-27T16:40:11Z
1,189,427
7
2009-07-27T17:14:00Z
[ "python", "networking", "dns", "srv" ]
Something which doesn't rely on native libraries would be better.
[twisted](http://twistedmatrix.com/trac/) has an excellent pure-python implementation, see [twisted.names](http://twistedmatrix.com/trac/browser/trunk/twisted/names) sources (especially [dns.py](http://twistedmatrix.com/trac/browser/trunk/twisted/names/dns.py)). If you can't use all of their code, maybe you can extract...
python non-privileged ICMP
1,189,389
15
2009-07-27T17:02:54Z
1,189,445
10
2009-07-27T17:17:25Z
[ "python", "ping", "icmp" ]
While trying to figure out the best method to ping (ICMP) something from python, I came across these questions: * [How can I perform a ping or traceroute in python, accessing the output as it is produced?](http://stackoverflow.com/questions/1151897/how-can-i-perform-a-ping-or-traceroute-in-python-accessing-the-output-...
The ping program is installed setuid root. This allows any user to use the program, and still be able to open a raw socket. After it opens the raw socket, it typically drops root privs. You generally need a raw socket to do ICMP correctly, and raw sockets are usually restricted. So it's not really python's fault at a...
python non-privileged ICMP
1,189,389
15
2009-07-27T17:02:54Z
1,189,449
9
2009-07-27T17:18:06Z
[ "python", "ping", "icmp" ]
While trying to figure out the best method to ping (ICMP) something from python, I came across these questions: * [How can I perform a ping or traceroute in python, accessing the output as it is produced?](http://stackoverflow.com/questions/1151897/how-can-i-perform-a-ping-or-traceroute-in-python-accessing-the-output-...
Here's how /sbin/ping "somehow manages" (on most Unix-y systems): ``` $ ls -l /sbin/ping -r-sr-xr-x 1 root wheel 68448 Jan 26 10:00 /sbin/ping ``` See? It's owned by `root` and has that crucial `s` bit in the permission -- setuserid. So, no matter what user is running it, ping **runs as root**. If you're using a ...
In Python, what's the correct way to instantiate a class from a variable?
1,189,649
4
2009-07-27T17:58:59Z
1,189,668
14
2009-07-27T18:01:23Z
[ "python", "instantiation" ]
Suppose that I have class `C`. I can write `o = C()` to create an instance of `C` and assign it to `o`. However, what if I want to assign the class itself into a variable and then instantiate it? For example, suppose that I have two classes, such as `C1` and `C2`, and I want to do something like: ``` if (something)...
``` o = C2() ``` This will accomplish what you want. Or, in case you meant to use classToUse, simply use: ``` o = classToUse() ``` Hope this helps.
In Python, what's the correct way to instantiate a class from a variable?
1,189,649
4
2009-07-27T17:58:59Z
1,189,701
10
2009-07-27T18:06:31Z
[ "python", "instantiation" ]
Suppose that I have class `C`. I can write `o = C()` to create an instance of `C` and assign it to `o`. However, what if I want to assign the class itself into a variable and then instantiate it? For example, suppose that I have two classes, such as `C1` and `C2`, and I want to do something like: ``` if (something)...
You're almost there. Instead of calling an instantiate() method, just call the variable directly. It's assigned to the class, and classes are callable: ``` if (something): classToUse = C1 else: classToUse = C2 o = classToUse() ```
Alternative to cvs2svn for performing cvs to svn migration
1,190,413
3
2009-07-27T20:24:55Z
1,190,437
7
2009-07-27T20:29:25Z
[ "python", "osx", "xserver", "cvs2svn", "gdbm" ]
I am trying to perform a migration from cvs to svn on my our new XServe server which is running OS X Server. There is a known conflict between the cvs2svn and dbm libraries that come pre-installed with OS X. The error is: > ERROR: cvs2svn uses the anydbm package, which depends on lower level dbm libraries. Your system...
Since CVS and Subversion repositories are really just collections of files, one way to work around this problem might be to copy your CVS repository to a machine where cvs2svn can run successfully, run it to convert to Subversion, and then copy the new repository back to your server. The added benefit of this method is...
Django FileField with upload_to determined at runtime
1,190,697
110
2009-07-27T21:22:38Z
1,190,866
225
2009-07-27T21:56:18Z
[ "python", "django", "django-models" ]
I'm trying to set up my uploads so that if user joe uploads a file it goes to MEDIA\_ROOT/joe as opposed to having everyone's files go to MEDIA\_ROOT. The problem is I don't know how to define this in the model. Here is how it currently looks: ``` class Content(models.Model): name = models.CharField(max_length=200...
You've probably read [the documentation](http://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.FileField.upload%5Fto), so here's an easy example to make it make sense: ``` def content_file_name(instance, filename): return '/'.join(['content', instance.user.username, filename]) class Content(mod...
Django FileField with upload_to determined at runtime
1,190,697
110
2009-07-27T21:22:38Z
21,841,322
8
2014-02-17T23:23:23Z
[ "python", "django", "django-models" ]
I'm trying to set up my uploads so that if user joe uploads a file it goes to MEDIA\_ROOT/joe as opposed to having everyone's files go to MEDIA\_ROOT. The problem is I don't know how to define this in the model. Here is how it currently looks: ``` class Content(models.Model): name = models.CharField(max_length=200...
This really helped. For a bit more brevity's sake, decided to use lambda in my case: ``` file = models.FileField( upload_to=lambda instance, filename: '/'.join(['mymodel', str(instance.pk), filename]), ) ```
Automatically Generated Python Code from an UML diagram?
1,190,854
15
2009-07-27T21:53:05Z
1,194,326
9
2009-07-28T14:05:48Z
[ "python", "uml" ]
*The question is not the same as [What’s the best way to generate a UML diagram from Python source code?](http://stackoverflow.com/questions/260165/whats-the-best-way-to-generate-a-uml-diagram-from-python-source-code), but the other way around.* [Topcoder UML tool](http://www.topcoder.com/tc?module=Static&d1=dev&d2=...
[Enterprise Architect](http://www.sparxsystems.com.au/products/ea/index.html) is able to generate python code code from UML diagrams. It is also able to also perform some reverse engineering, and therefore maintain the two versions (UML and python) synchronized together. However, I have never used it in that way, ex...
How do you reload your Python source into the console window in Eclipse/Pydev?
1,191,018
10
2009-07-27T22:28:35Z
2,017,129
7
2010-01-06T23:27:46Z
[ "python", "pydev" ]
In other Python IDEs (PythonWin and Idle) it's possible to hit a key and have your current source file window reloaded into the console. I find this useful when experimenting with a piece of code; you can call functions from the console interactively and inspect data structures there. Is there a way to do this with Ec...
You can do it with `Ctrl`+`Alt`+`Enter` on the latest [Pydev](http://pydev.org/manual_adv_interactive_console.html) for details on what `Ctrl`+`Alt`+`Enter` provides as it can do a number of things related to the interactive console.
Using module 'subprocess' with timeout
1,191,374
198
2009-07-28T00:41:23Z
1,191,537
70
2009-07-28T01:43:16Z
[ "python", "multithreading", "timeout", "subprocess" ]
Here's the Python code to run an arbitrary command returning its `stdout` data, or raise an exception on non-zero exit codes: ``` proc = subprocess.Popen( cmd, stderr=subprocess.STDOUT, # Merge stdout and stderr stdout=subprocess.PIPE, shell=True) ``` `communicate` is used to wait for the process to ...
If you're on Unix, ``` import signal ... class Alarm(Exception): pass def alarm_handler(signum, frame): raise Alarm signal.signal(signal.SIGALRM, alarm_handler) signal.alarm(5*60) # 5 minutes try: stdoutdata, stderrdata = proc.communicate() signal.alarm(0) # reset the alarm except Alarm: prin...
Using module 'subprocess' with timeout
1,191,374
198
2009-07-28T00:41:23Z
3,326,559
39
2010-07-24T19:29:54Z
[ "python", "multithreading", "timeout", "subprocess" ]
Here's the Python code to run an arbitrary command returning its `stdout` data, or raise an exception on non-zero exit codes: ``` proc = subprocess.Popen( cmd, stderr=subprocess.STDOUT, # Merge stdout and stderr stdout=subprocess.PIPE, shell=True) ``` `communicate` is used to wait for the process to ...
Here is Alex Martelli's solution as a module with proper process killing. The other approaches do not work because they do not use proc.communicate(). So if you have a process that produces lots of output, it will fill its output buffer and then block until you read something from it. ``` from os import kill from sign...
Using module 'subprocess' with timeout
1,191,374
198
2009-07-28T00:41:23Z
4,144,642
9
2010-11-10T12:51:15Z
[ "python", "multithreading", "timeout", "subprocess" ]
Here's the Python code to run an arbitrary command returning its `stdout` data, or raise an exception on non-zero exit codes: ``` proc = subprocess.Popen( cmd, stderr=subprocess.STDOUT, # Merge stdout and stderr stdout=subprocess.PIPE, shell=True) ``` `communicate` is used to wait for the process to ...
Another option is to write to a temporary file to prevent the stdout blocking instead of needing to poll with communicate(). This worked for me where the other answers did not; for example on windows. ``` outFile = tempfile.SpooledTemporaryFile() errFile = tempfile.SpooledTemporaryFile() proc = subpro...
Using module 'subprocess' with timeout
1,191,374
198
2009-07-28T00:41:23Z
4,825,933
165
2011-01-28T07:39:08Z
[ "python", "multithreading", "timeout", "subprocess" ]
Here's the Python code to run an arbitrary command returning its `stdout` data, or raise an exception on non-zero exit codes: ``` proc = subprocess.Popen( cmd, stderr=subprocess.STDOUT, # Merge stdout and stderr stdout=subprocess.PIPE, shell=True) ``` `communicate` is used to wait for the process to ...
I don't know much about the low level details; but, given that in python 2.6 the API offers the ability to wait for threads and terminate processes, what about running the process in a separate thread? ``` import subprocess, threading class Command(object): def __init__(self, cmd): self.cmd = cmd ...
Using module 'subprocess' with timeout
1,191,374
198
2009-07-28T00:41:23Z
10,012,262
46
2012-04-04T13:36:49Z
[ "python", "multithreading", "timeout", "subprocess" ]
Here's the Python code to run an arbitrary command returning its `stdout` data, or raise an exception on non-zero exit codes: ``` proc = subprocess.Popen( cmd, stderr=subprocess.STDOUT, # Merge stdout and stderr stdout=subprocess.PIPE, shell=True) ``` `communicate` is used to wait for the process to ...
jcollado's answer can be simplified using the threading.Timer class: ``` import subprocess, shlex from threading import Timer def run(cmd, timeout_sec): proc = subprocess.Popen(shlex.split(cmd), stdout=subprocess.PIPE, stderr=subprocess.PIPE) kill_proc = lambda p: p.kill() timer = Timer(timeout_sec, kill_p...