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 keep a Python script output window open?
1,000,900
108
2009-06-16T11:31:16Z
1,031,891
30
2009-06-23T11:03:09Z
[ "python", "windows" ]
I have just started with Python. When I execute a python script file on Windows, the output window appears but instantaneously goes away. I need it to stay there so I can analyze my output. How can I keep it open?
`cmd /k` is the typical way to open any console application (not only Python) with a console window that will remain after the application closes. The easiest way I can think to do that, is to press Win+R, type `cmd /k` and then drag&drop the script you want to the Run dialog.
How to keep a Python script output window open?
1,000,900
108
2009-06-16T11:31:16Z
9,232,527
9
2012-02-10T18:01:31Z
[ "python", "windows" ]
I have just started with Python. When I execute a python script file on Windows, the output window appears but instantaneously goes away. I need it to stay there so I can analyze my output. How can I keep it open?
you can combine the answers before: (for Notepad++ User) press F5 to run current script and type in command: ``` cmd /k python -i "$(FULL_CURRENT_PATH)" ``` in this way you stay in interactive mode after executing your Notepad++ python script and you are able to play around with your variables and so on :)
How to keep a Python script output window open?
1,000,900
108
2009-06-16T11:31:16Z
22,352,721
11
2014-03-12T13:15:04Z
[ "python", "windows" ]
I have just started with Python. When I execute a python script file on Windows, the output window appears but instantaneously goes away. I need it to stay there so I can analyze my output. How can I keep it open?
To keep your window open in case of exception (yet, while printing the exception using <http://stackoverflow.com/a/3702726/2436175>) ``` if __name__ == '__main__': try: ## your code, typically one function call except: import sys print sys.exc_info()[0] import traceback ...
Creating dynamic images with WSGI, no files involved
1,001,068
3
2009-06-16T12:06:56Z
1,001,092
8
2009-06-16T12:14:19Z
[ "python", "image-processing", "wsgi" ]
I would like to send dynamically created images to my users, such as charts, graphs etc. These images are "throw-away" images, they will be only sent to one user and then destroyed, hence the "no files involved". I would like to send the image directly to the user, without saving it on the file system first. With PHP ...
It is not related to WSGI or php or any other specific web technology. consider ``` <img src="someScript.php?param1=xyz"> ``` in general for url `someScript.php?param1=xyz` server should return data of image type and it would work Consider this example: ``` from wsgiref.simple_server import make_server def serveIm...
How do I concatenate files in Python?
1,001,538
32
2009-06-16T13:38:56Z
1,001,587
42
2009-06-16T13:44:51Z
[ "python", "file", "mp3" ]
I have multiple (between 40 and 50) MP3 files that I'd like to concatenate into one file. What's the best way to do this in Python? Use [`fileinput`](http://docs.python.org/library/fileinput.html) module to loop through each line of each file and write it to an output file? Outsource to windows [`copy`](http://www.com...
Putting the bytes in those files together is easy... however I am not sure if that will cause a continuous play - I think it might if the files are using the same bitrate, but I'm not sure. ``` from glob import iglob import shutil import os PATH = r'C:\music' destination = open('everything.mp3', 'wb') for filename i...
How do I concatenate files in Python?
1,001,538
32
2009-06-16T13:38:56Z
1,518,697
30
2009-10-05T07:40:10Z
[ "python", "file", "mp3" ]
I have multiple (between 40 and 50) MP3 files that I'd like to concatenate into one file. What's the best way to do this in Python? Use [`fileinput`](http://docs.python.org/library/fileinput.html) module to loop through each line of each file and write it to an output file? Outsource to windows [`copy`](http://www.com...
Just to summarize (and steal from [nosklo's answer](http://stackoverflow.com/questions/1001538/how-do-i-concatenate-files-in-python/1001587#1001587)), in order to concatenate two files you do: ``` destination = open(outfile,'wb') shutil.copyfileobj(open(file1,'rb'), destination) shutil.copyfileobj(open(file2,'rb'), de...
Python class to merge sorted files, how can this be improved?
1,001,569
7
2009-06-16T13:42:24Z
1,001,625
14
2009-06-16T13:50:56Z
[ "python", "merge", "mergesort", "large-file-support" ]
**Background:** I'm cleaning large (cannot be held in memory) tab-delimited files. As I clean the input file, I build up a list in memory; when it gets to 1,000,000 entries (about 1GB in memory) I sort it (using the default key below) and write the list to a file. This class is for putting the sorted files back togeth...
Note that in python2.6, heapq has a new [merge](http://docs.python.org/library/heapq.html#heapq.merge) function which will do this for you. To handle the custom key function, you can just wrap the file iterator with something that decorates it so that it compares based on the key, and strip it out afterwards: ``` def...
Why are there extra blank lines in my python program output?
1,001,601
2
2009-06-16T13:47:10Z
1,001,606
8
2009-06-16T13:48:18Z
[ "python" ]
I'm not particularly experienced with python, so may be doing something silly below. I have the following program: ``` import os import re import linecache LINENUMBER = 2 angles_file = open("d:/UserData/Robin Wilson/AlteredData/ncaveo/16-June/scan1_high/000/angles.txt") lines = angles_file.readlines() for line in ...
Change this: ``` output_file.write("0\t" + str(DN) + "\t" + Zenith + "\n") ``` to this: ``` output_file.write("0\t" + str(DN) + "\t" + Zenith) ``` The `Zenith` string already contains the trailing `\n` from the original file when you read it in.
Why are there extra blank lines in my python program output?
1,001,601
2
2009-06-16T13:47:10Z
1,001,658
14
2009-06-16T13:58:32Z
[ "python" ]
I'm not particularly experienced with python, so may be doing something silly below. I have the following program: ``` import os import re import linecache LINENUMBER = 2 angles_file = open("d:/UserData/Robin Wilson/AlteredData/ncaveo/16-June/scan1_high/000/angles.txt") lines = angles_file.readlines() for line in ...
For a GENERAL solution, remove the trailing newline from your INPUT: ``` splitted_line = line.rstrip("\n").split(";") ``` Removing the extraneous newline from your output "works" in this case but it's a kludge. ALSO: (1) it's not a good idea to open your output file in the middle of a loop; do it once, otherwise you...
Array division- translating from MATLAB to Python
1,001,634
6
2009-06-16T13:54:13Z
1,008,869
7
2009-06-17T18:41:38Z
[ "python", "matlab", "numpy", "linear-algebra" ]
I have this line of code in MATLAB, written by someone else: ``` c=a.'/b ``` I need to translate it into Python. a, b, and c are all arrays. The dimensions that I am currently using to test the code are: a: 18x1, b: 25x18, which gives me c with dimensions 1x25. The arrays are not square, but I would not want the...
The line ``` c = a.' / b ``` computes the solution of the equation *c b = aT* for *c*. Numpy does not have an operator that does this directly. Instead you should solve *bT cT = a* for *cT* and transpose the result: ``` c = numpy.linalg.lstsq(b.T, a.T)[0].T ```
Can bin() be overloaded like oct() and hex() in Python 2.6?
1,002,116
12
2009-06-16T15:08:55Z
1,011,888
11
2009-06-18T10:04:34Z
[ "python", "binary", "overloading", "python-2.6" ]
In Python 2.6 (and earlier) the `hex()` and `oct()` built-in functions can be overloaded in a class by defining `__hex__` and `__oct__` special functions. However there is not a `__bin__` special function for overloading the behaviour of Python 2.6's new `bin()` built-in function. I want to know if there is any way of...
As you've already discovered, you can't override `bin()`, but it doesn't sound like you need to do that. You just want a 0-padded binary value. Unfortunately in python 2.5 and previous, you couldn't use "%b" to indicate binary, so you can't use the "%" string formatting operator to achieve the result you want. Luckily...
python web framework large project
1,003,131
4
2009-06-16T18:21:43Z
1,003,161
13
2009-06-16T18:26:09Z
[ "python", "frameworks", "web-frameworks" ]
I need your advices to choose a Python Web Framework for developing a large project: Database (Postgresql)will have at least 500 tables, most of them with a composite primary key, lots of constraints, indexes & queries. About 1,500 views for starting. The project belongs to the financial area. Alwasy new requirements ...
Django has been used by many large organizations (Washington Post, etc.) and can connect with Postgresql easily enough. I use it fairly often and have had no trouble.
python web framework large project
1,003,131
4
2009-06-16T18:21:43Z
1,003,173
7
2009-06-16T18:28:34Z
[ "python", "frameworks", "web-frameworks" ]
I need your advices to choose a Python Web Framework for developing a large project: Database (Postgresql)will have at least 500 tables, most of them with a composite primary key, lots of constraints, indexes & queries. About 1,500 views for starting. The project belongs to the financial area. Alwasy new requirements ...
Yes. An ORM is essential for mapping SQL stuff to objects. You have three choices. 1. Use someone else's ORM 2. Roll your own. 3. Try to execute low-level SQL queries and pick out the fields they want from the result set. This is -- actually -- a kind of ORM with the mappings scattered throughout the applications. It...
App Engine Datastore IN Operator - how to use?
1,003,247
3
2009-06-16T18:42:38Z
1,005,813
9
2009-06-17T08:34:16Z
[ "python", "google-app-engine", "gql", "gae-datastore" ]
Reading: <http://code.google.com/appengine/docs/python/datastore/gqlreference.html> I want to use: := IN but am unsure how to make it work. Let's assume the following ``` class User(db.Model): name = db.StringProperty() class UniqueListOfSavedItems(db.Model): str = db.StringPropery() datesaved = db.Dat...
Since you have a list of keys, you don't need to do a second query - you can do a batch fetch, instead. Try this: ``` #and this should get me the items that a user saved useritems = db.get(saveditemkeys) ``` (Note you don't even need the guard clause - a db.get on 0 entities is short-circuited appropritely.) What's ...
How to import a module from a directory on level above the current script
1,003,843
8
2009-06-16T20:42:51Z
1,003,918
7
2009-06-16T21:01:55Z
[ "python", "import", "gchart" ]
For my Python application, I have the following directories structure: ``` \myapp \myapp\utils\ \myapp\utils\GChartWrapper\ \myapp\model\ \myapp\view\ \myapp\controller\ ``` One of my class in \myapp\view\ must import a class called [GChartWrapper](http://code.google.com/p/google-chartwrapper/). However, I am getting...
The [`__init__.py` file](http://code.google.com/p/google-chartwrapper/source/browse/trunk/GChartWrapper/%5F%5Finit%5F%5F.py) of the GChartWrapper package expects the GChartWrapper package on PYTHONPATH. You can tell by the first line: ``` from GChartWrapper.GChart import * ``` Is it necessary to have the GChartWrappe...
Is there a python ftp library for uploading whole directories (including subdirectories)?
1,003,968
4
2009-06-16T21:14:19Z
1,003,989
11
2009-06-16T21:17:48Z
[ "python", "ftp" ]
So I know about ftplib, but that's a bit too low for me as it still requires me to handle uploading files one at a time as well as determining if there are subdirectories, creating the equivalent subdirectories on the server, cd'ing into those subdirectories and then finally uploading the correct files into those subdi...
> The ftputil Python library is a high-level interface to the ftplib module. Looks like this could help. [ftputil website](http://ftputil.sschwarzer.net/trac)
Know any creative ways to interface Python with Tcl?
1,004,434
15
2009-06-16T23:40:11Z
1,004,513
19
2009-06-17T00:10:03Z
[ "python", "tcl" ]
Here's the situation. The company I work for has quite a bit of existing Tcl code, but some of them want to start using python. It would nice to be able to reuse some of the existing Tcl code, because that's money already spent. Besides, some of the test equipment only has Tcl API's. So, one of the ways I thought of w...
I hope you're ready for this. Standard Python ``` import Tkinter tclsh = Tkinter.Tcl() tclsh.eval(""" proc unknown args {puts "Hello World!"} }"!dlroW olleH" stup{ sgra nwonknu corp """) ``` *Edit in Re to comment*: Python's tcl interpreter is not aware of other installed tcl components. You can deal with tha...
Using Django JSON serializer for object that is not a Model
1,005,422
2
2009-06-17T06:32:57Z
1,005,489
15
2009-06-17T07:01:29Z
[ "python", "django", "json", "google-app-engine", "serialization" ]
* Is it possible to use Django serializer without a Model? * How it is done? * Will it work with google-app-engine? I don't use Django framework, but since it is available, I would want to use its resources here and there. Here is the code I tried: ``` from django.core import serializers obj = {'a':42,'q':'meaning of...
Serializers are only for models. Instead you can use [simplejson](http://code.google.com/p/simplejson/) bundled with Django. ``` from django.utils import simplejson json_str = simplejson.dumps(my_object) ``` Simplejson 2.0.9 docs are [here](http://simplejson.googlecode.com/svn/tags/simplejson-2.0.9/docs/index.html).
SQLite parameter substitution and quotes
1,005,552
8
2009-06-17T07:18:25Z
1,006,056
8
2009-06-17T09:37:26Z
[ "python", "sqlite", "sqlite3" ]
I have this line that works OK: ``` c.execute('select cleanseq from cleanseqs WHERE newID="%s"'%name) ``` But I want to use SQLite parameter substitution instead instead of string substitution (because I see [here](http://docs.python.org/library/sqlite3.html) that this is safer). This is my (failed) try: ``` t = (n...
about """If I delete the quotes sourronding the ?, it works. But I want the quotes to remain there since I remember that there are cases where I need them.""" What you remember from when you were building the whole SQL statement yourself is irrelevant. The new story is: mark with a ? each place in the SQL statement w...
SQLite parameter substitution and quotes
1,005,552
8
2009-06-17T07:18:25Z
1,010,804
11
2009-06-18T04:43:40Z
[ "python", "sqlite", "sqlite3" ]
I have this line that works OK: ``` c.execute('select cleanseq from cleanseqs WHERE newID="%s"'%name) ``` But I want to use SQLite parameter substitution instead instead of string substitution (because I see [here](http://docs.python.org/library/sqlite3.html) that this is safer). This is my (failed) try: ``` t = (n...
I find the named-parameter binding style much more readable -- and `sqlite3` supports it: ``` c.execute('SELECT cleanseq FROM cleanseqs WHERE newID=:t', locals()) ``` Note: passing `{'t': t}` or `dict(t=t)` instead of `locals()` would be more punctiliously correct, but in my opinion it would interfere with readabilit...
SQLite parameter substitution and quotes
1,005,552
8
2009-06-17T07:18:25Z
23,797,896
10
2014-05-22T04:35:40Z
[ "python", "sqlite", "sqlite3" ]
I have this line that works OK: ``` c.execute('select cleanseq from cleanseqs WHERE newID="%s"'%name) ``` But I want to use SQLite parameter substitution instead instead of string substitution (because I see [here](http://docs.python.org/library/sqlite3.html) that this is safer). This is my (failed) try: ``` t = (n...
To anyone who like me found this thread and got really frustrated by people ignoring the fact that sometimes you can't just ignore the quotes (because you're using say a LIKE command) you can fix this by doing something to the effect of: ``` var = name + "%" c.execute('SELECT foo FROM bar WHERE name LIKE ?',(var,)) ``...
What is the runtime complexity of python list functions?
1,005,590
36
2009-06-17T07:28:54Z
1,005,674
30
2009-06-17T07:57:35Z
[ "python", "complexity-theory" ]
I was writing a python function that looked something like this ``` def foo(some_list): for i in range(0, len(some_list)): bar(some_list[i], i) ``` so that it was called with ``` x = [0, 1, 2, 3, ... ] foo(x) ``` I had assumed that index access of lists was `O(1)`, but was surprised to find that for large...
there is [a very detailed table on python wiki](http://wiki.python.org/moin/TimeComplexity) which answers your question. However, in your particular example you should use `enumerate` to get an index of an iterable within a loop. like so: ``` for i, item in enumerate(some_seq): bar(item, i) ```
What is the easiest way to see if a process with a given pid exists in Python?
1,005,972
7
2009-06-17T09:12:08Z
1,006,032
10
2009-06-17T09:27:17Z
[ "python", "posix" ]
In a POSIX system, I want to see if a given process (PID 4356, for example) is running. It would be even better if I could get metadata about that process.
Instead of os.waitpid, you can also use os.kill with signal 0: ``` >>> os.kill(8861, 0) >>> os.kill(12765, 0) Traceback (most recent call last): File "<stdin>", line 1, in <module> OSError: [Errno 3] No such process >>> ``` Edit: more expansively: ``` import errno import os def pid_exists(pid): try: o...
How do I look inside a Python object?
1,006,169
118
2009-06-17T10:17:18Z
1,006,176
35
2009-06-17T10:18:01Z
[ "python", "introspection" ]
I'm starting to code in various projects using Python (including Django web development and Panda3D game development). To help me understand what's going on, I would like to basically 'look' inside the Python objects to see how they tick - like their methods and properties. So say I have a Python object, what would I...
First, read the source. Second, use the `dir()` function.
How do I look inside a Python object?
1,006,169
118
2009-06-17T10:17:18Z
1,006,194
7
2009-06-17T10:21:29Z
[ "python", "introspection" ]
I'm starting to code in various projects using Python (including Django web development and Panda3D game development). To help me understand what's going on, I would like to basically 'look' inside the Python objects to see how they tick - like their methods and properties. So say I have a Python object, what would I...
``` """Visit http://diveintopython.net/""" __author__ = "Mark Pilgrim ([email protected])" def info(object, spacing=10, collapse=1): """Print methods and doc strings. Takes module, class, list, dictionary, or string.""" methodList = [e for e in dir(object) if callable(getattr(object, e))] proc...
How do I look inside a Python object?
1,006,169
118
2009-06-17T10:17:18Z
1,006,231
143
2009-06-17T10:28:53Z
[ "python", "introspection" ]
I'm starting to code in various projects using Python (including Django web development and Panda3D game development). To help me understand what's going on, I would like to basically 'look' inside the Python objects to see how they tick - like their methods and properties. So say I have a Python object, what would I...
Python has a strong set of introspection features. Take a look at the following [built-in functions](http://docs.python.org/library/functions.html): * type() * dir() * id() * getattr() * hasattr() * globals() * locals() * callable() type() and dir() are particularly useful for inspecting the type of an object and it...
How do I look inside a Python object?
1,006,169
118
2009-06-17T10:17:18Z
1,007,108
13
2009-06-17T13:41:07Z
[ "python", "introspection" ]
I'm starting to code in various projects using Python (including Django web development and Panda3D game development). To help me understand what's going on, I would like to basically 'look' inside the Python objects to see how they tick - like their methods and properties. So say I have a Python object, what would I...
If this is for exploration to see what's going on, I'd recommend looking at [IPython](http://ipython.scipy.org/moin/). This adds various shortcuts to obtain an objects documentation, properties and even source code. For instance appending a "?" to a function will give the help for the object (effectively a shortcut for...
How do I look inside a Python object?
1,006,169
118
2009-06-17T10:17:18Z
1,007,121
94
2009-06-17T13:43:33Z
[ "python", "introspection" ]
I'm starting to code in various projects using Python (including Django web development and Panda3D game development). To help me understand what's going on, I would like to basically 'look' inside the Python objects to see how they tick - like their methods and properties. So say I have a Python object, what would I...
`object.__dict__`
How do I look inside a Python object?
1,006,169
118
2009-06-17T10:17:18Z
1,010,136
26
2009-06-18T00:11:32Z
[ "python", "introspection" ]
I'm starting to code in various projects using Python (including Django web development and Panda3D game development). To help me understand what's going on, I would like to basically 'look' inside the Python objects to see how they tick - like their methods and properties. So say I have a Python object, what would I...
I'm surprised no one's mentioned help yet! ``` In [1]: def foo(): ...: "foo!" ...: In [2]: help(foo) Help on function foo in module __main__: foo() foo! ``` Help lets you read the docstring and get an idea of what attributes a class might have, which is pretty helpful.
How to find out the number of CPUs using python
1,006,289
230
2009-06-17T10:41:44Z
1,006,301
118
2009-06-17T10:43:28Z
[ "python", "system-information" ]
I want to know the number of CPUs on the local machine using Python. The result should be `user/real` as output by `time(1)` when called with an optimally scaling userspace-only program.
If you're interested into the number of processors *available* to your current process, you have to check [cpuset](http://man7.org/linux/man-pages/man7/cpuset.7.html) first. Otherwise (or if cpuset is not in use), [`multiprocessing.cpu_count()`](http://docs.python.org/library/multiprocessing.html#multiprocessing.cpu_co...
How to find out the number of CPUs using python
1,006,289
230
2009-06-17T10:41:44Z
1,006,337
401
2009-06-17T10:53:53Z
[ "python", "system-information" ]
I want to know the number of CPUs on the local machine using Python. The result should be `user/real` as output by `time(1)` when called with an optimally scaling userspace-only program.
If you have python with a version >= 2.6 you can simply use ``` import multiprocessing multiprocessing.cpu_count() ``` <http://docs.python.org/library/multiprocessing.html#multiprocessing.cpu_count>
How to find out the number of CPUs using python
1,006,289
230
2009-06-17T10:41:44Z
3,845,635
7
2010-10-02T12:16:02Z
[ "python", "system-information" ]
I want to know the number of CPUs on the local machine using Python. The result should be `user/real` as output by `time(1)` when called with an optimally scaling userspace-only program.
Can't figure out how to add to the code or reply to the message but here's support for jython that you can tack in before you give up: ``` # jython try: from java.lang import Runtime runtime = Runtime.getRuntime() res = runtime.availableProcessors() if res > 0: return res except ImportError: ...
How to find out the number of CPUs using python
1,006,289
230
2009-06-17T10:41:44Z
14,840,102
39
2013-02-12T19:19:05Z
[ "python", "system-information" ]
I want to know the number of CPUs on the local machine using Python. The result should be `user/real` as output by `time(1)` when called with an optimally scaling userspace-only program.
An other option is to use the [`psutil`](http://code.google.com/p/psutil/) library, which always turn out useful in these situations: ``` >>> import psutil >>> psutil.cpu_count() 2 ``` This should work on any platform supported by `psutil`(unix and windows). Note that in some occasions `multiprocessing.cpu_count` ma...
How to find out the number of CPUs using python
1,006,289
230
2009-06-17T10:41:44Z
24,805,009
11
2014-07-17T13:32:10Z
[ "python", "system-information" ]
I want to know the number of CPUs on the local machine using Python. The result should be `user/real` as output by `time(1)` when called with an optimally scaling userspace-only program.
`multiprocessing.cpu_count()` will return the number of logical CPUs, so if you have a quad-core CPU with hyperthreading, it will return `8`. If you want the number of physical CPUs, use the python bindings to hwloc: ``` #!/usr/bin/env python import hwloc topology = hwloc.Topology() topology.load() print topology.get_...
How to find out the number of CPUs using python
1,006,289
230
2009-06-17T10:41:44Z
25,636,145
8
2014-09-03T04:16:56Z
[ "python", "system-information" ]
I want to know the number of CPUs on the local machine using Python. The result should be `user/real` as output by `time(1)` when called with an optimally scaling userspace-only program.
In Python 3.4+: [os.cpu\_count()](https://docs.python.org/3/library/os.html#os.cpu_count). `multiprocessing.cpu_count()` is implemented in terms of this function but raises `NotImplementedError` if `os.cpu_count()` returns `None` ("can't determine number of CPUs").
Capitalizing non-ASCII words in Python
1,006,450
5
2009-06-17T11:24:42Z
1,006,463
10
2009-06-17T11:30:16Z
[ "python", "unicode", "ascii", "capitalization" ]
How to capitalize words containing non-ASCII characters in Python? Is there a way to tune `string`'s `capitalize()` method to do that?
Use Unicode strings: ``` # coding: cp1252 print u"é".capitalize() # Prints É ``` If all you have is an 8-bit string, decode it into Unicode first: ``` # coding: cp1252 print "é".decode('cp1252').capitalize() # Prints É ``` If you then need it as an 8-bit string again, encode it: ``` # coding: cp1252 print "é"...
How do you make this code more pythonic?
1,007,215
3
2009-06-17T14:00:46Z
1,007,355
9
2009-06-17T14:23:22Z
[ "python", "machine-learning", "scipy" ]
Could you guys please tell me how I can make the following code more pythonic? The code is correct. Full disclosure - it's problem 1b in Handout #4 of [this](http://www.stanford.edu/class/cs229/materials.html) machine learning course. I'm supposed to use newton's algorithm on the two data sets for fitting a logistic h...
One obvious change is to get rid of the "for i in range(1, 100):" and just iterate over the file lines. To iterate over both files (xfile and yfile), zip them. ie replace that block with something like: ``` import itertools for xline, yline in itertools.izip(xfile, yfile): s= xline.split(" ") x[0] = float(...
How do I replace whitespaces with underscore and vice versa?
1,007,481
77
2009-06-17T14:41:36Z
1,007,499
137
2009-06-17T14:44:23Z
[ "python", "regex", "django" ]
I want to replace whitespace with underscore in a string to create nice URLs. So that for example: ``` "This should be connected" becomes "This_should_be_connected" ``` I am using Python with Django. Can this be solved using regular expressions?
You don't need regular expressions, Python has a string method that does what you need: ``` mystring.replace (" ", "_") ```
How do I replace whitespaces with underscore and vice versa?
1,007,481
77
2009-06-17T14:41:36Z
1,007,503
11
2009-06-17T14:45:07Z
[ "python", "regex", "django" ]
I want to replace whitespace with underscore in a string to create nice URLs. So that for example: ``` "This should be connected" becomes "This_should_be_connected" ``` I am using Python with Django. Can this be solved using regular expressions?
Using the `re` module: ``` import re re.sub('\s+', '_', "This should be connected") # This_should_be_connected re.sub('\s+', '_', 'And so\tshould this') # And_so_should_this ``` Unless you have multiple spaces or other whitespace possibilities as above, you may just wish to use `string.replace` as others have su...
How do I replace whitespaces with underscore and vice versa?
1,007,481
77
2009-06-17T14:41:36Z
1,007,508
9
2009-06-17T14:45:30Z
[ "python", "regex", "django" ]
I want to replace whitespace with underscore in a string to create nice URLs. So that for example: ``` "This should be connected" becomes "This_should_be_connected" ``` I am using Python with Django. Can this be solved using regular expressions?
use string's replace method: `"this should be connected".replace(" ", "_")` `"this_should_be_disconnected".replace("_", " ")`
How do I replace whitespaces with underscore and vice versa?
1,007,481
77
2009-06-17T14:41:36Z
1,007,615
42
2009-06-17T15:03:21Z
[ "python", "regex", "django" ]
I want to replace whitespace with underscore in a string to create nice URLs. So that for example: ``` "This should be connected" becomes "This_should_be_connected" ``` I am using Python with Django. Can this be solved using regular expressions?
Replacing spaces is fine, but I might suggest going a little further to handle other URL-hostile characters like question marks, apostrophes, exclamation points, etc. Also note that the general consensus among SEO experts is that [dashes are preferred to underscores in URLs.](http://www.google.com/search?q=dashes+unde...
How do I replace whitespaces with underscore and vice versa?
1,007,481
77
2009-06-17T14:41:36Z
1,007,685
33
2009-06-17T15:15:21Z
[ "python", "regex", "django" ]
I want to replace whitespace with underscore in a string to create nice URLs. So that for example: ``` "This should be connected" becomes "This_should_be_connected" ``` I am using Python with Django. Can this be solved using regular expressions?
Django has a 'slugify' function which does this, as well as other URL-friendly optimisations. It's hidden away in the defaultfilters module. ``` >>> from django.template.defaultfilters import slugify >>> slugify("This should be connected") this-should-be-connected ``` This isn't exactly the output you asked for, but...
How do I replace whitespaces with underscore and vice versa?
1,007,481
77
2009-06-17T14:41:36Z
10,376,875
16
2012-04-29T23:18:36Z
[ "python", "regex", "django" ]
I want to replace whitespace with underscore in a string to create nice URLs. So that for example: ``` "This should be connected" becomes "This_should_be_connected" ``` I am using Python with Django. Can this be solved using regular expressions?
This takes into account blank characters other than space and I think it's faster than using `re` module: ``` url = "_".join( title.split() ) ```
How do I build a list of all possible tuples from this table?
1,007,666
2
2009-06-17T15:12:01Z
1,007,741
13
2009-06-17T15:22:28Z
[ "python", "algorithm" ]
Suppose I have a set of column definitions: ``` Col1: value11 value12 value13 Col2: value21 value22 Col3: value31 value32 value33 ... ``` Given some subset of columns -- 2 or more -- I want to find all possible values for those columns. Suppose I choose columns 1 and 2, above: ``` (value11 value21) (value11 value22...
The best way to get this is going to be using itertools.product(). For example: ``` import itertools group1 = ['a', 'b'] group2 = ['c', 'd'] print list(itertools.product(group1, group2)) #==> [('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd')] ``` This function accepts multiple arguments (i.e. multiple columns). For...
Popen and python
1,007,855
4
2009-06-17T15:38:25Z
1,007,878
7
2009-06-17T15:41:15Z
[ "python", "popen" ]
Working on some code and I'm given the error when running it from the command prompt... ``` NameError: name 'Popen' is not defined ``` but I've imported both `import os` and `import sys`. Here's part of the code ``` exepath = os.path.join(EXE File location is here) exepath = '"' + os.path.normpath(exepath) + '"' cm...
Popen is defined in the subprocess module ``` import subprocess ... subprocess.Popen(...) ``` Or: ``` from subprocess import Popen Popen(...) ```
Popen and python
1,007,855
4
2009-06-17T15:38:25Z
1,007,901
26
2009-06-17T15:43:15Z
[ "python", "popen" ]
Working on some code and I'm given the error when running it from the command prompt... ``` NameError: name 'Popen' is not defined ``` but I've imported both `import os` and `import sys`. Here's part of the code ``` exepath = os.path.join(EXE File location is here) exepath = '"' + os.path.normpath(exepath) + '"' cm...
you should do: ``` import subprocess subprocess.Popen(cmd, stderr=subprocess.STDOUT, stdout=subprocess.PIPE) # etc. ```
Name of file I'm editing
1,008,557
2
2009-06-17T17:45:14Z
1,008,586
9
2009-06-17T17:48:58Z
[ "python", "vim" ]
I'm editing a file in ~/Documents. However, my working directory is somewhere else, say ~/Desktop. The file I'm editing is a Python script. I'm interested in doing a command like... :!python without needing to do :!python ~/Documents/script.py Is that possible? If so, what would be the command? Thank you.
Try: !python %
Processing pairs of values from two sequences in Clojure
1,009,037
8
2009-06-17T19:20:23Z
1,009,096
12
2009-06-17T19:34:06Z
[ "python", "clojure", "zip" ]
I'm trying to get into the Clojure community. I've been working a lot with Python, and one of the features I make extensive use of is the zip() method, for iterating over pairs of values. Is there a (clever and short) way of achieving the same in Clojure?
Another way is to simply use map together with some function that collects its arguments in a sequence, like this: ``` user=> (map vector '(1 2 3) "abc") ([1 \a] [2 \b] [3 \c]) ```
Using string as variable name
1,009,831
6
2009-06-17T22:27:22Z
1,009,837
16
2009-06-17T22:31:03Z
[ "python" ]
Is there any way for me to use a string to call a method of a class? Here's an example that will hopefully explain better (using the way I think it should be): ``` class helloworld(): def world(self): print "Hello World!" str = "world" hello = helloworld() hello.`str`() ``` Which would output `Hello Wor...
You can use [`getattr`](http://docs.python.org/3.0/library/functions.html#getattr): ``` >>> class helloworld: ... def world(self): ... print("Hello World!") ... >>> m = "world" >>> hello = helloworld() >>> getattr(hello, m)() Hello World! ``` * Note that the parens in `class helloworld()` as in your exam...
Command Line Arguments In Python
1,009,860
269
2009-06-17T22:38:30Z
1,009,864
200
2009-06-17T22:39:49Z
[ "python", "command-line", "command-line-arguments" ]
I am originally a C programmer. I have seen numerous tricks and "hacks" to read many different arguments. What are some of the ways Python programmers can do this? ### Related * [What’s the best way to grab/parse command line arguments passed to a Python script?](http://stackoverflow.com/questions/20063/whats-the-...
## *Please* note that optparse was deprecated in version 2.7 of Python: <http://docs.python.org/2/library/optparse.html>. **argparse** is the replacement: <http://docs.python.org/2/library/argparse.html#module-argparse> --- There are the following modules in the standard library: * The [getopt](http://docs.python.o...
Command Line Arguments In Python
1,009,860
269
2009-06-17T22:38:30Z
1,009,879
233
2009-06-17T22:42:25Z
[ "python", "command-line", "command-line-arguments" ]
I am originally a C programmer. I have seen numerous tricks and "hacks" to read many different arguments. What are some of the ways Python programmers can do this? ### Related * [What’s the best way to grab/parse command line arguments passed to a Python script?](http://stackoverflow.com/questions/20063/whats-the-...
``` import sys print "\n".join(sys.argv) ``` `sys.argv` is a list that contains all the arguments passed to the script on the command line. Basically, ``` import sys print sys.argv[1:] ```
Command Line Arguments In Python
1,009,860
269
2009-06-17T22:38:30Z
1,009,882
31
2009-06-17T22:43:08Z
[ "python", "command-line", "command-line-arguments" ]
I am originally a C programmer. I have seen numerous tricks and "hacks" to read many different arguments. What are some of the ways Python programmers can do this? ### Related * [What’s the best way to grab/parse command line arguments passed to a Python script?](http://stackoverflow.com/questions/20063/whats-the-...
One way to do it is using `sys.argv`. This will print the script name as the first argument and all the other parameters that you pass to it. ``` import sys for arg in sys.argv: print arg ```
Command Line Arguments In Python
1,009,860
269
2009-06-17T22:38:30Z
1,010,597
34
2009-06-18T03:12:25Z
[ "python", "command-line", "command-line-arguments" ]
I am originally a C programmer. I have seen numerous tricks and "hacks" to read many different arguments. What are some of the ways Python programmers can do this? ### Related * [What’s the best way to grab/parse command line arguments passed to a Python script?](http://stackoverflow.com/questions/20063/whats-the-...
There is also [`argparse` stdlib module](https://docs.python.org/library/argparse.html) (an "impovement" on stdlib's `optparse` module). Example from [the introduction to argparse](https://docs.python.org/howto/argparse.html): ``` # script.py import argparse if __name__ == '__main__': parser = argparse.ArgumentPa...
Command Line Arguments In Python
1,009,860
269
2009-06-17T22:38:30Z
1,010,728
16
2009-06-18T04:07:57Z
[ "python", "command-line", "command-line-arguments" ]
I am originally a C programmer. I have seen numerous tricks and "hacks" to read many different arguments. What are some of the ways Python programmers can do this? ### Related * [What’s the best way to grab/parse command line arguments passed to a Python script?](http://stackoverflow.com/questions/20063/whats-the-...
I use optparse myself, but really like the direction Simon Willison is taking with his recently introduced [optfunc](http://github.com/simonw/optfunc/tree/master) library. It works by: > "introspecting a function > definition (including its arguments > and their default values) and using > that to construct a command ...
Command Line Arguments In Python
1,009,860
269
2009-06-17T22:38:30Z
1,050,472
102
2009-06-26T18:15:02Z
[ "python", "command-line", "command-line-arguments" ]
I am originally a C programmer. I have seen numerous tricks and "hacks" to read many different arguments. What are some of the ways Python programmers can do this? ### Related * [What’s the best way to grab/parse command line arguments passed to a Python script?](http://stackoverflow.com/questions/20063/whats-the-...
Just going around evangelizing for [argparse](http://code.google.com/p/argparse/) which is better for [these](http://argparse.googlecode.com/svn/trunk/doc/argparse-vs-optparse.html) reasons.. essentially: *(copied from the link)* * argparse module can handle positional and optional arguments, while optparse can h...
Command Line Arguments In Python
1,009,860
269
2009-06-17T22:38:30Z
10,545,218
18
2012-05-11T03:53:30Z
[ "python", "command-line", "command-line-arguments" ]
I am originally a C programmer. I have seen numerous tricks and "hacks" to read many different arguments. What are some of the ways Python programmers can do this? ### Related * [What’s the best way to grab/parse command line arguments passed to a Python script?](http://stackoverflow.com/questions/20063/whats-the-...
``` #set default args as -h , if no args: if len(sys.argv) == 1: sys.argv[1:] = ["-h"] ```
Command Line Arguments In Python
1,009,860
269
2009-06-17T22:38:30Z
14,790,373
24
2013-02-09T16:52:31Z
[ "python", "command-line", "command-line-arguments" ]
I am originally a C programmer. I have seen numerous tricks and "hacks" to read many different arguments. What are some of the ways Python programmers can do this? ### Related * [What’s the best way to grab/parse command line arguments passed to a Python script?](http://stackoverflow.com/questions/20063/whats-the-...
The [docopt](https://github.com/docopt/docopt) library is really slick. It builds an argument dict from the usage string for your app. Eg from the docopt readme: ``` """Naval Fate. Usage: naval_fate.py ship new <name>... naval_fate.py ship <name> move <x> <y> [--speed=<kn>] naval_fate.py ship shoot <x> <y> n...
Python - Get original function arguments in decorator
1,010,080
9
2009-06-17T23:55:25Z
1,010,109
17
2009-06-18T00:02:17Z
[ "python", "decorator" ]
I am trying to write a "login\_required" decorator for the views in a WSGI+Werkzeug application. In order to do this, I need to get at the user's session, which is accessible via the Request object that is passed into the view methods. I can't figure out how to get at that instance of Request in the decorator, though...
The decorator `login_required` is passed the function (`hello` in this case). So what you want to do is: ``` def login_required(f): # This function is what we "replace" hello with def wrapper(*args, **kw): args[0].client_session['test'] = True logged_in = 0 if logged_in: return f(*args, **kw) ...
Python factorization
1,010,381
11
2009-06-18T01:39:13Z
1,010,460
10
2009-06-18T02:17:59Z
[ "python", "algorithm" ]
I'd just like to know the best way of listing all integer factors of a number, given a dictionary of its prime factors and their exponents. For example if we have {2:3, 3:2, 5:1} (2^3 \* 3^2 \* 5 = 360) Then I could write: ``` for i in range(4): for j in range(3): for k in range(1): print 2**i * 3**j *...
Using [`itertools.product`](http://docs.python.org/library/itertools.html#itertools.product) from Python 2.6: ``` #!/usr/bin/env python import itertools, operator def all_factors(prime_dict): series = [[p**e for e in range(maxe+1)] for p, maxe in prime_dict.items()] for multipliers in itertools.product(*serie...
Python factorization
1,010,381
11
2009-06-18T01:39:13Z
1,010,463
9
2009-06-18T02:18:50Z
[ "python", "algorithm" ]
I'd just like to know the best way of listing all integer factors of a number, given a dictionary of its prime factors and their exponents. For example if we have {2:3, 3:2, 5:1} (2^3 \* 3^2 \* 5 = 360) Then I could write: ``` for i in range(4): for j in range(3): for k in range(1): print 2**i * 3**j *...
Well, not only you have 3 loops, but this approach won't work if you have more than 3 factors :) One possible way: ``` def genfactors(fdict): factors = set([1]) for factor, count in fdict.iteritems(): for ignore in range(count): factors.update([n*factor for n in factors]) ...
Python factorization
1,010,381
11
2009-06-18T01:39:13Z
1,011,573
14
2009-06-18T08:53:59Z
[ "python", "algorithm" ]
I'd just like to know the best way of listing all integer factors of a number, given a dictionary of its prime factors and their exponents. For example if we have {2:3, 3:2, 5:1} (2^3 \* 3^2 \* 5 = 360) Then I could write: ``` for i in range(4): for j in range(3): for k in range(1): print 2**i * 3**j *...
I have [blogged about this](http://numericalrecipes.wordpress.com/tag/divisors/), and the fastest pure python (without itertools) comes from a post by Tim Peters to the python list, and uses nested recursive generators: ``` def divisors(factors) : """ Generates all divisors, unordered, from the prime factoriza...
Mapping URL Pattern to a Single RequestHandler in a WSGIApplication
1,010,427
3
2009-06-18T02:05:22Z
1,012,365
8
2009-06-18T12:27:29Z
[ "python", "google-app-engine" ]
Is it possible to map a URL pattern (regular expression or some other mapping) to a single RequestHandler? If so how can I accomplish this? Ideally I'd like to do something like this: ``` application=WSGIApplication([('/*',MyRequestHandler),]) ``` So that MyRequestHandler handles all requests made. Note that I'm wor...
The pattern you describe will work fine. Also, any groups in the regular expression you specify will be passed as arguments to the handler methods (get, post, etc). For example: ``` class MyRequestHandler(webapp.RequestHandler): def get(self, date, id): # Do stuff. Note that date and id are both strings, even if...
Mathematical equation manipulation in Python
1,010,583
10
2009-06-18T03:07:52Z
1,010,666
20
2009-06-18T03:40:25Z
[ "python", "math", "equation" ]
I want to develop a GUI application which displays a given mathematical equation. When you click upon a particular variable in the equation to signify that it is the unknown variable ie., to be calculated, the equation transforms itself to evaluate the required unknown variable. For example: --- ``` a = (b+c*d)/e ``...
Using [SymPy](http://sympy.org/), your example would go something like this: ``` >>> import sympy >>> a,b,c,d,e = sympy.symbols('abcde') >>> r = (b+c*d)/e >>> l = a >>> r = sympy.solve(l-r,d) >>> l = d >>> r [(-b + a*e)/c] >>> ``` It seems to work for trigonometric functions too: ``` >>> l = a >>> r = b*sympy.sin(c)...
String Slicing Python
1,010,961
5
2009-06-18T05:45:47Z
1,010,973
23
2009-06-18T05:48:55Z
[ "python" ]
I have a string, example: ``` s = "this is a string, a" ``` where ','(comma) will always be the 3rd last character, aka s[-3]. I am thinking of ways to remove the ',' but can only think of converting the string into a list, deleting it, and converting it back to a string. This however seems a bit too much for simple...
Normally, you would just do: ``` s = s[:-3] + s[-2:] ``` The `s[:-3]` gives you a string up to, but not including, the comma you want removed (`"this is a string"`) and the `s[-2:]` gives you another string starting one character beyond that comma (`" a"`). Then, joining the two strings together gives you what you w...
Relative file paths in Python packages
1,011,337
8
2009-06-18T07:51:23Z
1,011,366
10
2009-06-18T08:00:44Z
[ "python", "reference", "packages", "relative-path" ]
How do I reference a file relatively to a package's directory? My directory structure is: ``` /foo package1/ resources/ __init__.py package2/ resources/ __init__.py script.py ``` `script.py` imports packages `package1` and `package2`. Although the packages can be imported b...
If you want to reference files from the `foo/package1/resources` folder you would want to use the `__file__` variable of the module. Inside `foo/package1/__init__.py`: ``` from os import path resources_dir = path.join(path.dirname(__file__), 'resources') ```
Configuring Django to use SQLAlchemy
1,011,476
17
2009-06-18T08:31:04Z
1,011,495
8
2009-06-18T08:34:42Z
[ "python", "django", "sqlalchemy", "configure" ]
how we configure django with SQLAlchemy??
Check this: [Replacing django orm](http://lethain.com/entry/2008/jul/23/replacing-django-s-orm-with-sqlalchemy/)
Configuring Django to use SQLAlchemy
1,011,476
17
2009-06-18T08:31:04Z
8,539,407
8
2011-12-16T19:53:12Z
[ "python", "django", "sqlalchemy", "configure" ]
how we configure django with SQLAlchemy??
You can use SQLAlchemy within a Django project with Aldjemy: <https://github.com/Deepwalker/aldjemy>
Python - Previous and next values inside a loop
1,011,938
33
2009-06-18T10:23:38Z
1,011,962
45
2009-06-18T10:28:51Z
[ "python", "loops" ]
How can I do thing like this in python? ``` foo = somevalue previous = next = 0 for (i=1; i<objects.length(); i++) { if (objects[i]==foo){ previous = objects[i-1] next = objects[i+1] } } ```
This should do the trick. ``` foo = somevalue previous = next_ = None l = len(objects) for index, obj in enumerate(objects): if obj == foo: if index > 0: previous = objects[index - 1] if index < (l - 1): next_ = objects[index + 1] ``` Here's the docs on the [`enumerate`](ht...
Python - Previous and next values inside a loop
1,011,938
33
2009-06-18T10:23:38Z
1,012,089
71
2009-06-18T11:12:58Z
[ "python", "loops" ]
How can I do thing like this in python? ``` foo = somevalue previous = next = 0 for (i=1; i<objects.length(); i++) { if (objects[i]==foo){ previous = objects[i-1] next = objects[i+1] } } ```
Solutions until now only deal with lists, and most are copying the list. In my experience a lot of times that isn't possible. Also, they don't deal with the fact that you can have repeated elements in the list. The title of your question says "*Previous and next values inside a loop*", but if you run most answers her...
In Python, how do I index a list with another list?
1,012,185
36
2009-06-18T11:36:06Z
1,012,197
85
2009-06-18T11:38:46Z
[ "python", "list", "indexing" ]
I would like to index a list with another list like this ``` L = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'] Idx = [0, 3, 7] T = L[ Idx ] ``` and T should end up being a list containing ['a', 'd', 'h']. Is there a better way than ``` T = [] for i in Idx: T.append(L[i]) print T # Gives result ['a', 'd', 'h'] ```
``` T = [L[i] for i in Idx] ```
In Python, how do I index a list with another list?
1,012,185
36
2009-06-18T11:36:06Z
1,012,484
16
2009-06-18T12:54:26Z
[ "python", "list", "indexing" ]
I would like to index a list with another list like this ``` L = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'] Idx = [0, 3, 7] T = L[ Idx ] ``` and T should end up being a list containing ['a', 'd', 'h']. Is there a better way than ``` T = [] for i in Idx: T.append(L[i]) print T # Gives result ['a', 'd', 'h'] ```
If you are using numpy, you can perform extended slicing like that: ``` >>> import numpy >>> a=numpy.array(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']) >>> Idx = [0, 3, 7] >>> a[Idx] array(['a', 'd', 'h'], dtype='|S1') ``` ...and is probably much faster (if performance is enough of a concern to to bother with the...
How to concatenate strings with binary values in python?
1,012,457
3
2009-06-18T12:48:28Z
1,012,472
9
2009-06-18T12:51:12Z
[ "python", "string", "binary", "concatenation" ]
What's the easiest way in python to concatenate string with binary values ? ``` sep = 0x1 data = ["abc","def","ghi","jkl"] ``` Looking for result data `"abc0x1def0x1ghi0x1jkl"` with the 0x1 being binary value not string "0x1".
I think ``` joined = '\x01'.join(data) ``` should do it. `\x01` is the escape sequence for a byte with value 0x01.
Call Python From Bat File And Get Return Code
1,013,246
10
2009-06-18T15:11:43Z
1,013,293
14
2009-06-18T15:17:46Z
[ "python", "batch-file" ]
I'm looking for a way to call a python script from a batch file and getting a return code from the python script. Confusing I know, but it's based on a system that's currently in use. I'd re-write it, but this way would be much, much quicker. So: ``` Bat ---------------------> Python * call python file * Bat <-...
The windows shell saves the return code in the `ERRORLEVEL` variable: ``` python somescript.py echo %ERRORLEVEL% ``` In the python script you can exit the script and set the return value by calling `exit()`: ``` exit(15) ``` In older versions of python you might first have to import the `exit()` function from the `...
What is the purpose of the two colons in this Python string-slicing statement?
1,013,272
13
2009-06-18T15:14:57Z
1,013,295
19
2009-06-18T15:18:13Z
[ "python", "slice" ]
For example, ``` str = "hello" str[1::3] ``` And where can I find this in Python documentation?
in [sequences' description](http://docs.python.org/library/stdtypes.html#index-510): ``` s[i:j:k] slice of s from i to j with step k ``` > The slice of `s` from `i` to `j` with step `k` is defined as the sequence of items with index `x = i + n*k` such that `0 <= n < (j-i)/k`. In other words, the indices are `i`, `...
After writing to a file, why does os.path.getsize still return the previous size?
1,013,778
12
2009-06-18T16:38:24Z
1,013,799
9
2009-06-18T16:41:16Z
[ "python", "filesize" ]
I am trying to split up a large xml file into smaller chunks. I write to the output file and then check its size to see if its passed a threshold, but I dont think the getsize() method is working as expected. What would be a good way to get the filesize of a file that is changing in size. Ive done something like this...
Yes, Python is buffering your output. You'd be better off tracking the size yourself, something like this: ``` size = 0 for line in f1: if str(line) == '</Service>\n': break else: f2.write(line) size += len(line) print('size = ' + str(size)) ``` (That might not be 100% accurate, eg. on Windows eac...
After writing to a file, why does os.path.getsize still return the previous size?
1,013,778
12
2009-06-18T16:38:24Z
5,821,833
11
2011-04-28T16:22:11Z
[ "python", "filesize" ]
I am trying to split up a large xml file into smaller chunks. I write to the output file and then check its size to see if its passed a threshold, but I dont think the getsize() method is working as expected. What would be a good way to get the filesize of a file that is changing in size. Ive done something like this...
File size is different from file position. For example, ``` os.path.getsize('sample.txt') ``` It exactly returns file size in bytes. But ``` f = open('sample.txt') print f.readline() f.tell() ``` Here f.tell() returns the current position of the file handler - i.e. where the next write will put its data. Since it ...
How to write a Perl, Python, or Ruby program to change the memory of another process on Windows?
1,013,828
8
2009-06-18T16:45:46Z
1,013,870
13
2009-06-18T16:52:57Z
[ "python", "ruby", "perl", "winapi", "readprocessmemory" ]
I wonder if Perl, Python, or Ruby can be used to write a program so that it will look for 0x12345678 in the memory of another process (probably the heap, for both data and code data) and then if it is found, change it to 0x00000000? It is something similar to [Cheat Engine](http://www.cheatengine.org/), which can do so...
I initially thought this was not possible but after seeing Brian's comment, I searched CPAN and lo and behold, there is [Win32::Process::Memory](http://search.cpan.org/perldoc/Win32%3a%3aProcess%3a%3aMemory): ``` C:\> ppm install Win32::Process::Info C:\> ppm install Win32::Process::Memory ``` The module apparently u...
How to write a Perl, Python, or Ruby program to change the memory of another process on Windows?
1,013,828
8
2009-06-18T16:45:46Z
1,014,468
8
2009-06-18T18:42:44Z
[ "python", "ruby", "perl", "winapi", "readprocessmemory" ]
I wonder if Perl, Python, or Ruby can be used to write a program so that it will look for 0x12345678 in the memory of another process (probably the heap, for both data and code data) and then if it is found, change it to 0x00000000? It is something similar to [Cheat Engine](http://www.cheatengine.org/), which can do so...
It is possible to do so if you have attached your program as a debugger to the process, which should be possible in those languages if wrappers around the appropriate APIs exist, or by directly accessing the windows functions through something like ctypes (for python). However, it may be easier to do in a more low-leve...
How do I convert a nested tuple of tuples and lists to lists of lists in Python?
1,014,352
2
2009-06-18T18:20:54Z
1,014,669
12
2009-06-18T19:19:02Z
[ "python", "list", "tuples" ]
I have a tuple containing lists and more tuples. I need to convert it to nested lists with the same structure. For example, I want to convert `(1,2,[3,(4,5)])` to `[1,2,[3,[4,5]]]`. How do I do this (in Python)?
``` def listit(t):     return list(map(listit, t)) if isinstance(t, (list, tuple)) else t ``` The shortest solution I can imagine.
What does : TypeError: cannot concatenate 'str' and 'list' objects mean?
1,014,503
8
2009-06-18T18:49:36Z
1,014,596
11
2009-06-18T19:03:32Z
[ "python", "string" ]
What does this error mean? > TypeError: cannot concatenate 'str' and 'list' objects Here's part of the code: ``` for j in ('90.','52.62263.','26.5651.','10.8123.'): if j == '90.': z = ('0.') elif j == '52.62263.': z = ('0.', '72.', '144.', '216.', '288.') for k in z: exepath = os...
I'm not sure you're aware that `cmd` is a one-element `list`, and not a string. Changing that line to the below would construct a string, and the rest of your code will work: ``` # Just removing the square brackets cmd = exepath + '-j' + str(j) + '-n' + str(z) ``` I assume you used brackets just to group the operati...
Simple syntax for bringing a list element to the front in python?
1,014,523
17
2009-06-18T18:52:58Z
1,014,533
19
2009-06-18T18:55:17Z
[ "python" ]
I have an array with a set of elements. I'd like to bring a given element to the front but otherwise leave the order unchanged. Do folks have suggestions as to the cleanest syntax for this? This is the best I've been able to come up with, but it seems like bad form to have an N log N operation when an N operation coul...
To bring (for example) the 5th element to the front, use: ``` mylist.insert(0, mylist.pop(5)) ```
Simple syntax for bringing a list element to the front in python?
1,014,523
17
2009-06-18T18:52:58Z
1,014,544
41
2009-06-18T18:57:35Z
[ "python" ]
I have an array with a set of elements. I'd like to bring a given element to the front but otherwise leave the order unchanged. Do folks have suggestions as to the cleanest syntax for this? This is the best I've been able to come up with, but it seems like bad form to have an N log N operation when an N operation coul...
I would go with: ``` mylist.insert(0, mylist.pop(mylist.index(targetvalue))) ```
Python Authentication with urllib2
1,014,570
4
2009-06-18T19:00:28Z
1,014,646
7
2009-06-18T19:13:13Z
[ "python" ]
So I'm trying to download a file from a site called vsearch.cisco.com with python [python] ``` #Connects to the Cisco Server and Downloads files at the URL specified import urllib2 #Define Useful Variables url = 'http://vsearch.cisco.com' username = 'xxxxxxxx' password = 'xxxxxxxx' realm = 'CEC' # Begin Making co...
A "password manager" might help: ``` mgr = urllib2.HTTPPasswordMgrWithDefaultRealm() mgr.add_password(None, url, user, password) urllib2.build_opener(urllib2.HTTPBasicAuthHandler(mgr), urllib2.HTTPDigestAuthHandler(mgr)) ```
Traversing foreign key related tables in django templates
1,014,591
27
2009-06-18T19:02:45Z
1,014,610
43
2009-06-18T19:06:31Z
[ "python", "django", "django-models", "django-templates" ]
## View ``` categories = Category.objects.all() t = loader.get_template('index.html') v = Context({ 'categories': categories }) return HttpResponse(t.render(v)) ``` ## Template ``` {% for category in categories %} <h1>{{ category.name }}</h1> {% endfor %} ``` this works great. now im trying to print each compa...
Just get rid of the parentheses: ``` {% for company in category.company_set.all %} ``` Here's the [appropriate documentation](http://docs.djangoproject.com/en/dev/topics/templates/#variables). You can call methods that take 0 parameters this way.
Logging All Exceptions in a pyqt4 app
1,015,047
11
2009-06-18T20:34:23Z
1,015,272
15
2009-06-18T21:27:06Z
[ "python", "logging", "pyqt" ]
What's the best way to log all of the exceptions in a pyqt4 application using the standard python logging api? I've tried wrapping exec\_() in a try, except block, and logging the exceptions from that, but it only logs exceptions from the initialization of the app. As a temporary solution, I wrapped the most importan...
You need to override [`sys.excepthook`](http://docs.python.org/library/sys.html) ``` def my_excepthook(type, value, tback): # log the exception here # then call the default handler sys.__excepthook__(type, value, tback) sys.excepthook = my_excepthook ```
Is it possible to override the method used to call Django's admin delete confirmation page?
1,015,072
4
2009-06-18T20:40:14Z
1,015,332
7
2009-06-18T21:37:38Z
[ "python", "django", "django-admin" ]
On Django's admin pages, I'd like to perform an action when the administrator clicks the Delete button for an object. In other words, I'd like to execute some code prior to arriving on the "Are you sure?" delete confirmation page. I realize I could override the template page for this object, but I was hoping for somet...
You can override `ModelAdmin.delete_view()` method, like: ``` class MyModelAdmin(ModelAdmin): def delete_view(self, request, object_id, extra_context=None): # if request.POST is set, the user already confirmed deletion if not request.POST: perform_my_action() super(MyModelAdmin,...
Running Python code contained in a string
1,015,142
7
2009-06-18T20:55:33Z
1,015,147
22
2009-06-18T20:57:11Z
[ "python", "pygame", "exec", "eval" ]
I'm writing a game engine using pygame and box2d, and in the character builder, I want to be able to write the code that will be executed on keydown events. My plan was to have a text editor in the character builder that let you write code similar to: ``` if key == K_a: ## Move left pass elif key == K_d: ...
You can use the [`eval(string)`](http://docs.python.org/library/functions.html#eval) method to do this. ## Definition `eval(code, globals=None, locals=None)` The code is just standard Python code - this means that it still needs to be properly indented. The globals can have a custom `__builtins__` defined, which c...
Python: Bind an Unbound Method?
1,015,307
82
2009-06-18T21:33:18Z
1,015,389
65
2009-06-18T21:50:36Z
[ "python", "class", "methods", "bind" ]
In Python, is there a way to bind an unbound method without calling it? I am writing a wxPython program, and for a certain class I decided it'd be nice to group the data of all of my buttons together as a class-level list of tuples, like so: ``` class MyWidget(wx.Window): buttons = [("OK", OnOK), (...
This can be done cleanly with [types.MethodType](http://docs.python.org/library/types.html#types.MethodType). Example: ``` import types def f(self): print self class C(object): pass meth = types.MethodType(f, C(), C) # Bind f to an instance of C print meth # prints <bound method C.f of <__main__.C object at 0x01255...
Python: Bind an Unbound Method?
1,015,307
82
2009-06-18T21:33:18Z
1,015,405
119
2009-06-18T21:54:29Z
[ "python", "class", "methods", "bind" ]
In Python, is there a way to bind an unbound method without calling it? I am writing a wxPython program, and for a certain class I decided it'd be nice to group the data of all of my buttons together as a class-level list of tuples, like so: ``` class MyWidget(wx.Window): buttons = [("OK", OnOK), (...
All functions are also *descriptors*, so you can bind them by calling their `__get__` method: ``` bound_handler = handler.__get__(self, MyWidget) ``` Here's R. Hettinger's excellent [guide](http://users.rcn.com/python/download/Descriptor.htm) to descriptors.
Python: Bind an Unbound Method?
1,015,307
82
2009-06-18T21:33:18Z
7,312,062
7
2011-09-05T19:31:03Z
[ "python", "class", "methods", "bind" ]
In Python, is there a way to bind an unbound method without calling it? I am writing a wxPython program, and for a certain class I decided it'd be nice to group the data of all of my buttons together as a class-level list of tuples, like so: ``` class MyWidget(wx.Window): buttons = [("OK", OnOK), (...
Creating a closure with self in it will not technically bind the function, but it is an alternative way of solving the same (or very similar) underlying problem. Here's a trivial example: ``` self.method = (lambda self: lambda args: self.do(args))(self) ```
Continuous unit testing with Pydev (Python and Eclipse)
1,015,581
42
2009-06-18T22:46:50Z
1,039,552
9
2009-06-24T16:44:23Z
[ "python", "unit-testing", "pydev" ]
Is there a way to integrate background unit tests with the Pydev Eclipse environment? My unit tests run well, but I would like to integrate them to run in the background based on source file changes (e.g. with nose) and to integrate the result back to Eclipse (I'm thinking big red X when tests fail with a console and ...
Pydev does have some unit-test integration, but that's only as a run configuration...so... This is not a very elegant way, but if you: 1. Enable Project->Build Automatically 2. In your project properties, add a new builder of type Program 3. Configure it to run your tests and select 'during auto builds' Then at leas...
Continuous unit testing with Pydev (Python and Eclipse)
1,015,581
42
2009-06-18T22:46:50Z
5,650,640
34
2011-04-13T14:09:41Z
[ "python", "unit-testing", "pydev" ]
Is there a way to integrate background unit tests with the Pydev Eclipse environment? My unit tests run well, but I would like to integrate them to run in the background based on source file changes (e.g. with nose) and to integrate the result back to Eclipse (I'm thinking big red X when tests fail with a console and ...
This feature has been added to PyDev 2.0.1 with an option to relaunch the tests in the last test run whenever a python file change, with an additional option to rerun only the errors -- although it'll run the full test suite if no errors were found, as the idea is that you work through your errors and when all pass a f...
Why is `self` in Python objects immutable?
1,015,592
24
2009-06-18T22:51:21Z
1,015,602
58
2009-06-18T22:55:06Z
[ "python", "object" ]
Why can't I perform an action like the following: ``` class Test(object): def __init__(self): self = 5 t = Test() print t ``` I would expect it to print `5` since we're overwriting the instance with it, but instead it doesn't do anything at all. Doesn't even throw an error. Just ignores the assignment. ...
*Any* simple assignment to *any* argument of *any* function behaves exactly the same way in Python: binds that name to a different value, and does nothing else whatsoever. "No special case is special enough to break the rules", as the Zen of Python says!-) So, far from it being odd (that simply=assigning to a specific...
Why is `self` in Python objects immutable?
1,015,592
24
2009-06-18T22:51:21Z
1,015,604
9
2009-06-18T22:55:28Z
[ "python", "object" ]
Why can't I perform an action like the following: ``` class Test(object): def __init__(self): self = 5 t = Test() print t ``` I would expect it to print `5` since we're overwriting the instance with it, but instead it doesn't do anything at all. Doesn't even throw an error. Just ignores the assignment. ...
It doesnt "ignore" the assignment. The assignment works just fine, you created a local name that points to the data 5. If you *really* want to do what you are doing... ``` class Test(object): def __new__(*args): return 5 ```
Cross-platform subprocess with hidden window
1,016,384
25
2009-06-19T04:52:50Z
1,016,651
27
2009-06-19T06:48:07Z
[ "python", "windows", "linux", "cross-platform", "subprocess" ]
I want to open a process in the background and interact with it, but this process should be invisible in both Linux and Windows. In Windows you have to do some stuff with STARTUPINFO, while this isn't valid in Linux: > ValueError: startupinfo is only supported on Windows platforms Is there a simpler way than creating...
You can reduce one line :) ``` startupinfo = None if os.name == 'nt': startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW proc = subprocess.Popen(command, startupinfo=startupinfo) ```
Cross-platform subprocess with hidden window
1,016,384
25
2009-06-19T04:52:50Z
3,443,174
12
2010-08-09T18:49:16Z
[ "python", "windows", "linux", "cross-platform", "subprocess" ]
I want to open a process in the background and interact with it, but this process should be invisible in both Linux and Windows. In Windows you have to do some stuff with STARTUPINFO, while this isn't valid in Linux: > ValueError: startupinfo is only supported on Windows platforms Is there a simpler way than creating...
Just a note: for **Python 2.7** I have to use `subprocess._subprocess.STARTF_USESHOWWINDOW` instead of `subprocess.STARTF_USESHOWWINDOW`.
What to do with "Unexpected indent" in python?
1,016,814
60
2009-06-19T07:53:20Z
1,016,829
8
2009-06-19T07:58:22Z
[ "python", "syntax-error" ]
How do I rectify the error "unexpected indent" in python?
By using correct indentation. Python is whitespace aware, so you need to follow its indentation guidlines for blocks or you'll get indentation errors.
What to do with "Unexpected indent" in python?
1,016,814
60
2009-06-19T07:53:20Z
1,016,836
21
2009-06-19T08:00:08Z
[ "python", "syntax-error" ]
How do I rectify the error "unexpected indent" in python?
In Python, the spacing is very important, this gives the structure of your code blocks. This error happens when you mess up your code structure, for example like this : ``` def test_function() : if 5 > 3 : print "hello" ``` You may also have a mix of tabs and spaces in your file. I suggest you use a python syn...
What to do with "Unexpected indent" in python?
1,016,814
60
2009-06-19T07:53:20Z
1,017,404
85
2009-06-19T11:03:01Z
[ "python", "syntax-error" ]
How do I rectify the error "unexpected indent" in python?
Python uses spacing at the start of the line to determine when code blocks start and end. Errors you can get are: **Unexpected indent.** This line of code has more spaces at the start than the one before, but the one before is not the start of a subblock (e.g. if/while/for statement). All lines of code in a block must...
What to do with "Unexpected indent" in python?
1,016,814
60
2009-06-19T07:53:20Z
1,017,458
8
2009-06-19T11:25:47Z
[ "python", "syntax-error" ]
How do I rectify the error "unexpected indent" in python?
**Turn on visible whitespace in whatever editor you are using and turn on replace tabs with spaces.** While you can use tabs with Python mixing tabs and space usually leads to the error you are experiencing. Replacing tabs with 4 spaces is the recommended approach for writing Python code.