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 |
|---|---|---|---|---|---|---|---|---|---|
Can I use Win32 COM to replace text inside a word document? | 1,045,628 | 4 | 2009-06-25T18:58:32Z | 1,045,710 | 8 | 2009-06-25T19:13:28Z | [
"python",
"winapi",
"com",
"ms-word",
"replace"
] | I have to perform a large number of replacements in some documents, and the thing is, I would like to be able to automate that task. Some of the documents contain common strings, and this would be pretty useful if it could be automated. From what I read so far, COM could be one way of doing this, but I don't know if te... | See if [this](http://www.devshed.com/c/a/Python/Windows-Programming-in-Python/2/) gives you a start on word automation using python.
Once you open a document, you could do the following.
After the following code, you can Close the document & open another.
```
Selection.Find.ClearFormatting
Selection.Find.Replacemen... |
Can I use Win32 COM to replace text inside a word document? | 1,045,628 | 4 | 2009-06-25T18:58:32Z | 1,045,808 | 10 | 2009-06-25T19:36:43Z | [
"python",
"winapi",
"com",
"ms-word",
"replace"
] | I have to perform a large number of replacements in some documents, and the thing is, I would like to be able to automate that task. Some of the documents contain common strings, and this would be pretty useful if it could be automated. From what I read so far, COM could be one way of doing this, but I don't know if te... | I like the answers so far;
here's a tested example (slightly modified from [here](http://www.programmingforums.org/post105986.html))
that replaces all occurrences of a string in a Word document:
```
import win32com.client
def search_replace_all(word_file, find_str, replace_str):
''' replace all occurrences ... |
Would one have to know the machine architecture to write code? | 1,046,068 | 6 | 2009-06-25T20:30:22Z | 1,046,099 | 15 | 2009-06-25T20:34:25Z | [
"java",
"c++",
"python",
"64bit",
"32-bit"
] | Let's say I'm programming in Java or Python or C++ for a simple problem, could be to build an TCP/UDP echo server or computation of factorial. Do I've to bother about the architecture details, i.e., if it is 32 or 64-bit?
IMHO, unless I'm programming something to do with fairly low-level stuff then I don't have to bot... | **correct for most circumstances**
The runtime/language/compiler will abstract those details unless you are dealing directly with word sizes or binary at a low level.
Even byteorder is abstracted by the NIC/Network stack in the kernel. It is translated for you. When programming sockets in C, you do sometimes have to ... |
Would one have to know the machine architecture to write code? | 1,046,068 | 6 | 2009-06-25T20:30:22Z | 1,046,128 | 14 | 2009-06-25T20:37:48Z | [
"java",
"c++",
"python",
"64bit",
"32-bit"
] | Let's say I'm programming in Java or Python or C++ for a simple problem, could be to build an TCP/UDP echo server or computation of factorial. Do I've to bother about the architecture details, i.e., if it is 32 or 64-bit?
IMHO, unless I'm programming something to do with fairly low-level stuff then I don't have to bot... | Knowing how things work, be it how the virtual machine works, and how it works on your platform, or how certain C++ constructs are transformed into assembly will always make you a better programmer, because you will understand why things should be done the way they are.
You need to understand things like memory to kno... |
python classes that refer to each other | 1,046,150 | 3 | 2009-06-25T20:40:08Z | 1,046,418 | 11 | 2009-06-25T21:46:20Z | [
"python",
"django",
"oop"
] | I have two classes that refer to each other, but obviously the compiler complains. Is there any way around this?
**EDIT**
Actually my code is slightly different than what Hank Gay uses. So python can definitely deal with some kinds of circular references, but it tosses an error in the following situation. Below is wh... | In python, the code in a class is run when the class is loaded.
Now, what the hell does that mean? ;-)
Consider the following code:
```
class x:
print "hello"
def __init__(self): print "hello again"
```
When you load the module that contains the code, python will print `hello`. Whenever you create an `x`, p... |
Python - Subprocess - How to call a Piped command in Windows? | 1,046,474 | 5 | 2009-06-25T22:04:16Z | 1,046,522 | 11 | 2009-06-25T22:18:50Z | [
"python",
"subprocess",
"pipe",
"echo",
"popen"
] | How do I run this command with subprocess?
I tried:
```
proc = subprocess.Popen(
'''ECHO bosco|"C:\Program Files\GNU\GnuPG\gpg.exe" --batch --passphrase-fd 0 --output "c:\docume~1\usi\locals~1\temp\tmptlbxka.txt" --decrypt "test.txt.gpg"''',
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subproc... | First and foremost, you don't actually need a pipe; you are just sending input. You can use [subprocess.communicate](http://docs.python.org/library/subprocess.html#subprocess.Popen.communicate) for that.
Secondly, don't specify the command as a string; that's messy as soon as filenames with spaces are involved.
Third... |
Importing Python modules from different working directory | 1,046,628 | 21 | 2009-06-25T23:03:09Z | 1,046,837 | 22 | 2009-06-26T00:26:27Z | [
"python"
] | I have a Python script that uses built-in modules but also imports a number of custom modules that exist in the same directory as the main script itself.
For example, I would call
```
python agent.py
```
and agent.py has a number of imports, including:
```
import checks
```
where checks is in a file in the same di... | Actually your example works because checks.py is in the same directory as agent.py, but say checks.py was in the preceeding directory, eg;
```
agent/agent.py
checks.py
```
Then you could do the following:
```
path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
if not path in sys.path:
sys.path.... |
An integer is required? open() | 1,046,656 | 22 | 2009-06-25T23:11:49Z | 1,046,674 | 38 | 2009-06-25T23:16:56Z | [
"python",
"file-io",
"integer",
"argv"
] | I have a very simple python script that **should** scan a text file, which contains lines formatted as *id*='*value*' and put them into a dict. the python module is called chval.py and the input file is in.txt. here's the code:
```
import os,sys
from os import *
from sys import *
vals = {}
f = open(sys.argv[1], 'r')... | Because you did `from os import *`, you are (accidenally) using os.open, which indeed requires an integer flag instead of a textual "r" or "w". Take out that line and you'll get past that error. |
An integer is required? open() | 1,046,656 | 22 | 2009-06-25T23:11:49Z | 1,046,706 | 7 | 2009-06-25T23:31:22Z | [
"python",
"file-io",
"integer",
"argv"
] | I have a very simple python script that **should** scan a text file, which contains lines formatted as *id*='*value*' and put them into a dict. the python module is called chval.py and the input file is in.txt. here's the code:
```
import os,sys
from os import *
from sys import *
vals = {}
f = open(sys.argv[1], 'r')... | Don't do `import * from wherever` without a good reason (and there aren't many).
Your code is picking up the os.open() function instead of the built-in open() function. If you really want to use os.open(), do `import os` then call `os.open(....)`. Whichever open you want to call, read the documentation about what argu... |
Does Python's heapify() not play well with list comprehension and slicing? | 1,046,683 | 2 | 2009-06-25T23:21:02Z | 1,046,689 | 8 | 2009-06-25T23:23:49Z | [
"python",
"heap",
"list-comprehension"
] | I found an interesting bug in a program that I implemented somewhat lazily, and wondered if I'm comprehending it correctly. The short version is that [Python's `heapq` implementation](http://docs.python.org/library/heapq.html) doesn't actually order a list, it merely groks the list in a heap-centric way. Specifically, ... | A heap is not a sorted list (it's a representation of a partially sorted binary tree).
So yes, you're right, if you expect a heapified list to behave like a sorted list, you'll be disappointed. The only sorting assumption you can make about a heap is that `heap[0]` is always its smallest element.
(It's difficult to a... |
Overriding "+=" in Python? (__iadd__() method) | 1,047,021 | 25 | 2009-06-26T02:04:24Z | 1,047,034 | 61 | 2009-06-26T02:08:45Z | [
"python",
"operators",
"override"
] | Is it possible to override += in Python? | Yes, override the [`__iadd__`](https://docs.python.org/2/library/stdtypes.html#numeric-types-int-float-long-complex) method. Example:
```
def __iadd__(self, other):
self.number += other.number
return self
``` |
Overriding "+=" in Python? (__iadd__() method) | 1,047,021 | 25 | 2009-06-26T02:04:24Z | 1,047,068 | 9 | 2009-06-26T02:26:01Z | [
"python",
"operators",
"override"
] | Is it possible to override += in Python? | In addition to overloading `__iadd__` (remember to return self!), you can also fallback on `__add__`, as x += y will work like x = x + y. (This is one of the pitfalls of the += operator.)
```
>>> class A(object):
... def __init__(self, x):
... self.x = x
... def __add__(self, other):
... return A(self.x + ... |
Easiest way to persist a data structure to a file in python? | 1,047,318 | 17 | 2009-06-26T04:22:39Z | 1,047,335 | 35 | 2009-06-26T04:27:36Z | [
"python",
"file",
"persistence"
] | Let's say I have something like this:
```
d = { "abc" : [1, 2, 3], "qwerty" : [4,5,6] }
```
What's the easiest way to **progammatically** get that into a file that I can load from python later?
Can I somehow save it as python source (from within a python script, not manually!), then `import` it later?
Or should I u... | Use the [pickle](http://docs.python.org/library/pickle.html) module.
```
import pickle
d = { "abc" : [1, 2, 3], "qwerty" : [4,5,6] }
afile = open(r'C:\d.pkl', 'wb')
pickle.dump(d, afile)
afile.close()
#reload object from file
file2 = open(r'C:\d.pkl', 'rb')
new_d = pickle.load(file2)
file2.close()
#print dictionary ... |
Easiest way to persist a data structure to a file in python? | 1,047,318 | 17 | 2009-06-26T04:22:39Z | 1,047,338 | 10 | 2009-06-26T04:28:03Z | [
"python",
"file",
"persistence"
] | Let's say I have something like this:
```
d = { "abc" : [1, 2, 3], "qwerty" : [4,5,6] }
```
What's the easiest way to **progammatically** get that into a file that I can load from python later?
Can I somehow save it as python source (from within a python script, not manually!), then `import` it later?
Or should I u... | Take your pick: [Python Standard Library - Data Persistance](http://docs.python.org/library/persistence.html). Which one is most appropriate can vary by what your specific needs are.
[`pickle`](http://docs.python.org/library/pickle.html) is probably the simplest and most capable as far as "write an arbitrary object to... |
PHP Sockets or Python, Perl, Bash Sockets? | 1,047,991 | 2 | 2009-06-26T08:31:30Z | 1,048,024 | 7 | 2009-06-26T08:38:58Z | [
"php",
"python",
"perl",
"bash",
"sockets"
] | I'm trying to implement a socket server that will run in most shared PHP hosting.
The requirements are that the Socket server can be installed, started and stopped from PHP automatically without the user doing anything. It doesn't matter what language the socket server is written in, as long as it will run on the majo... | Any server can be stopped or started by PHP under Linux. Of course, if you are running a server which accepts sockets from the internet, then you can just connect directly to the server and tell it to shutdown. No need to go via PHP!
As for "starting a server from PHP", well, under Linux, anything can be started from ... |
How to parse for tags with '+' in python | 1,048,541 | 3 | 2009-06-26T11:09:32Z | 1,048,556 | 8 | 2009-06-26T11:12:46Z | [
"python",
"regex"
] | I'm getting a "nothing to repeat" error when I try to compile this:
```
search = re.compile(r'([^a-zA-Z0-9])(%s)([^a-zA-Z0-9])' % '+test', re.I)
```
The problem is the '+' sign. How should I handle that? | ```
re.compile(r'([^a-zA-Z0-9])(%s)([^a-zA-Z0-9])' % '\+test', re.I)
```
The "+" is the "repeat at least once" quantifier in regular expressions. It must follow something that is repeatable, or it must be escaped if you want to match a literal "+".
Better is this, if you want to build your regex dynamically.
```
re.... |
Resize images in directory | 1,048,658 | 4 | 2009-06-26T11:37:32Z | 1,048,702 | 11 | 2009-06-26T11:43:41Z | [
"python",
"perl",
"image",
"resize",
"image-scaling"
] | I have a directory full of images that I would like to resize to around 60% of their original size.
How would I go about doing this? Can be in either Python or Perl
Cheers
Eef | How about using mogrify, part of [ImageMagick](http://www.imagemagick.org/)? If you really need to control this from Perl, then you could use [Image::Magick](http://search.cpan.org/dist/Image-Magick), [Image::Resize](http://search.cpan.org/dist/Image-Resize) or [Imager](http://search.cpan.org/dist/Imager). |
Resize images in directory | 1,048,658 | 4 | 2009-06-26T11:37:32Z | 1,048,754 | 9 | 2009-06-26T12:01:07Z | [
"python",
"perl",
"image",
"resize",
"image-scaling"
] | I have a directory full of images that I would like to resize to around 60% of their original size.
How would I go about doing this? Can be in either Python or Perl
Cheers
Eef | Can it be in shell?
```
mkdir resized
for a in *.jpg; do convert "$a" -resize 60% resized/"$a"; done
```
If you have > 1 core, you can do it like this:
```
find . -maxdepth 1 -type f -name '*.jpg' -print0 | xargs -0 -P3 -I XXX convert XXX -resize 60% resized/XXX
```
-P3 means that you want to resize up to 3 images ... |
Resize images in directory | 1,048,658 | 4 | 2009-06-26T11:37:32Z | 1,048,793 | 14 | 2009-06-26T12:09:34Z | [
"python",
"perl",
"image",
"resize",
"image-scaling"
] | I have a directory full of images that I would like to resize to around 60% of their original size.
How would I go about doing this? Can be in either Python or Perl
Cheers
Eef | If you want to do it programatically, which I assume is the case, use PIL to resize e.g.
```
newIm = im.resize((newW, newH)
```
then save it to same file or a new location.
Go through the folder recursively and apply resize function to all images.
I have come up with a sample script which I think will work for you.... |
Dictionaries with volatile values in Python unit tests? | 1,049,551 | 2 | 2009-06-26T14:49:52Z | 1,049,563 | 9 | 2009-06-26T14:52:49Z | [
"python",
"unit-testing"
] | I need to write a unit test for a function that returns a dictionary. One of the values in this dictionary is `datetime.datetime.now()` which of course changes with every test run.
I want to ignore that key completely in my assert. Right now I have a dictionary comparison function but I really want to use assertEqual ... | Just delete the timestamp from the dict before doing the comparison:
```
class MonkeyTester(unittest.TestCase):
def test_myfunc(self):
without_timestamp = my_func()
del without_timestamp["monkey_creation"]
self.assertEqual(without_timestamp, {'monkey_head_count': 3})
```
If you find yourse... |
Check if Python Package is installed | 1,051,254 | 40 | 2009-06-26T20:54:38Z | 1,051,266 | 53 | 2009-06-26T21:00:17Z | [
"python",
"package",
"skype",
"python-import"
] | What's a good way to check if a package is installed while within a Python script? I know it's easy from the interpreter, but I need to do it within a script.
I guess I could check if there's a directory on the system that's created during the installation, but I feel like there's a better way. I'm trying to make sure... | If you mean a python script, just do something like this:
```
try:
import mymodule
except ImportError, e:
pass # module doesn't exist, deal with it.
``` |
Check if Python Package is installed | 1,051,254 | 40 | 2009-06-26T20:54:38Z | 27,496,113 | 12 | 2014-12-16T01:29:25Z | [
"python",
"package",
"skype",
"python-import"
] | What's a good way to check if a package is installed while within a Python script? I know it's easy from the interpreter, but I need to do it within a script.
I guess I could check if there's a directory on the system that's created during the installation, but I feel like there's a better way. I'm trying to make sure... | A better way of doing this is:
```
import pip
installed_packages = pip.get_installed_distributions()
```
Why this way? Sometimes you have app name collisions. Importing from the app namespace doesn't give you the full picture of what's installed on the system.
As a result, you get a list of `pkg_resources.Distributi... |
Reading a single character (getch style) in Python is not working in Unix | 1,052,107 | 4 | 2009-06-27T04:19:23Z | 1,052,115 | 9 | 2009-06-27T04:34:18Z | [
"python",
"getch"
] | Any time I use the recipe at <http://code.activestate.com/recipes/134892/> I can't seem to get it working. It always throws the following error:
```
Traceback (most recent call last):
...
old_settings = termios.tcgetattr(fd)
termios.error: (22, 'Invalid argument)
```
My best thought is that it is because I'm ... | This is working on Ubuntu 8.04.1 , Python 2.5.2, i get no such error. May be you should try it from command line, eclipse may be using its own stdin, i get exact same error if I run it from Wing IDE, but from command line it works great.
Reason is that IDE e.g Wing is using there own class netserver.CDbgInputStream as ... |
Convert python filenames to unicode | 1,052,225 | 15 | 2009-06-27T06:17:20Z | 1,052,238 | 42 | 2009-06-27T06:34:37Z | [
"python",
"unicode"
] | I am on python 2.6 for Windows.
I use os.walk to read a file tree. Files may have non-7-bit characters (German "ae" for example) in their filenames. These are encoded in Pythons internal string representation.
I am processing these filenames with Python library functions and that fails due to wrong encoding.
How can... | If you pass a Unicode string to `os.walk()`, you'll get Unicode results:
```
>>> list(os.walk(r'C:\example')) # Passing an ASCII string
[('C:\\example', [], ['file.txt'])]
>>>
>>> list(os.walk(ur'C:\example')) # Passing a Unicode string
[(u'C:\\example', [], [u'file.txt'])]
``` |
How to create a message box with tkinter? | 1,052,420 | 5 | 2009-06-27T08:48:36Z | 1,052,428 | 14 | 2009-06-27T08:54:42Z | [
"python",
"tkinter",
"messagebox"
] | I've been trying to build a fairly simple message box in tkinter that has "YES" and "NO" buttons. When I push the "YES" button internally it must go and write YES to a file. Similarly, when "NO" is pushed, NO must be written to a file. How can I do this? | You can use the module [tkMessageBox](http://infohost.nmt.edu/tcc/help/pubs/tkinter/dialogs.html#tkMessageBox) for Python 2.7 or the corresponding version for Python 3 called `tkinter.messagebox`.
It looks like `askquestion()` is exactly the function that you want. It will even return the string `"yes"` or `"no"` for ... |
Run a function every X minutes - Python | 1,052,574 | 11 | 2009-06-27T10:28:42Z | 1,052,581 | 22 | 2009-06-27T10:34:54Z | [
"python",
"gtk",
"timer",
"pygtk"
] | I'm using Python and PyGTK. I'm interested in running a certain function, which gets data from a serial port and saves it, every several minutes.
Currently, I'm using the sleep() function in the time library. In order to be able to do processing, I have my system set up like this:
```
import time
waittime = 300 # 5 m... | Do not use such loop with sleep, it will block gtk from processing any UI events, instead use gtk timer e.g.
```
def my_timer(*args):
return True# do ur work here, but not for long
gtk.timeout_add(60*1000, my_timer) # call every min
``` |
Run a function every X minutes - Python | 1,052,574 | 11 | 2009-06-27T10:28:42Z | 1,309,480 | 8 | 2009-08-21T00:01:57Z | [
"python",
"gtk",
"timer",
"pygtk"
] | I'm using Python and PyGTK. I'm interested in running a certain function, which gets data from a serial port and saves it, every several minutes.
Currently, I'm using the sleep() function in the time library. In order to be able to do processing, I have my system set up like this:
```
import time
waittime = 300 # 5 m... | This is exactly like [my answer here](http://stackoverflow.com/questions/1309006/running-function-5-seconds-after-pygtk-widget-is-shown/1309404#1309404)
If the time is not critical to be exact to the tenth of a second, use
```
glib.timeout_add_seconds(60, ..)
```
else as above.
\*timeout\_add\_seconds\* allows the ... |
How can I parse the output of /proc/net/dev into key:value pairs per interface using Python? | 1,052,589 | 2 | 2009-06-27T10:40:34Z | 1,052,628 | 9 | 2009-06-27T11:00:13Z | [
"python",
"linux",
"parsing"
] | The output of [/proc/net/dev](http://www.redhat.com/docs/manuals/enterprise/RHEL-4-Manual/en-US/Reference%5FGuide/s2-proc-dir-net.html) on Linux looks like this:
```
Inter-| Receive | Transmit
face |bytes packets errs drop fifo frame compressed multicast|bytes p... | this is pretty formatted input and you can easily get columns and data list by splitting each line, and then create a dict of of it.
here is a simple script without regex
```
lines = open("/proc/net/dev", "r").readlines()
columnLine = lines[1]
_, receiveCols , transmitCols = columnLine.split("|")
receiveCols = map(l... |
Very large matrices using Python and NumPy | 1,053,928 | 60 | 2009-06-28T00:32:21Z | 1,054,017 | 28 | 2009-06-28T01:46:24Z | [
"python",
"matrix",
"numpy"
] | [NumPy](http://en.wikipedia.org/wiki/NumPy) is an extremely useful library, and from using it I've found that it's capable of handling matrices which are quite large (10000 x 10000) easily, but begins to struggle with anything much larger (trying to create a matrix of 50000 x 50000 fails). Obviously, this is because of... | You should be able to use numpy.memmap to memory map a file on disk. With newer python and 64-bit machine, you should have the necessary address space, without loading everything into memory. The OS should handle only keep part of the file in memory. |
Very large matrices using Python and NumPy | 1,053,928 | 60 | 2009-06-28T00:32:21Z | 1,054,070 | 21 | 2009-06-28T02:23:40Z | [
"python",
"matrix",
"numpy"
] | [NumPy](http://en.wikipedia.org/wiki/NumPy) is an extremely useful library, and from using it I've found that it's capable of handling matrices which are quite large (10000 x 10000) easily, but begins to struggle with anything much larger (trying to create a matrix of 50000 x 50000 fails). Obviously, this is because of... | To handle sparse matrices, you need the `scipy` package that sits on top of `numpy` -- see [here](http://docs.scipy.org/doc/scipy/reference/sparse.html) for more details about the sparse-matrix options that `scipy` gives you. |
Very large matrices using Python and NumPy | 1,053,928 | 60 | 2009-06-28T00:32:21Z | 1,054,113 | 46 | 2009-06-28T02:53:45Z | [
"python",
"matrix",
"numpy"
] | [NumPy](http://en.wikipedia.org/wiki/NumPy) is an extremely useful library, and from using it I've found that it's capable of handling matrices which are quite large (10000 x 10000) easily, but begins to struggle with anything much larger (trying to create a matrix of 50000 x 50000 fails). Obviously, this is because of... | `numpy.array`s are meant to live in memory. If you want to work with matrices larger than your RAM, you have to work around that. There are at least two approaches you can follow:
1. **Try a more efficient matrix representation** that exploits any special structure that your matrices have. For example, as others have ... |
Very large matrices using Python and NumPy | 1,053,928 | 60 | 2009-06-28T00:32:21Z | 1,054,114 | 9 | 2009-06-28T02:54:20Z | [
"python",
"matrix",
"numpy"
] | [NumPy](http://en.wikipedia.org/wiki/NumPy) is an extremely useful library, and from using it I've found that it's capable of handling matrices which are quite large (10000 x 10000) easily, but begins to struggle with anything much larger (trying to create a matrix of 50000 x 50000 fails). Obviously, this is because of... | Stefano Borini's [post](http://stackoverflow.com/questions/1053928/python-numpy-very-large-matrices/1053953#1053953) got me to look into how far along this sort of thing already is.
[This is it.](http://h5py.alfven.org/) It appears to do basically what you want. HDF5 will let you store very large datasets, and then ac... |
Very large matrices using Python and NumPy | 1,053,928 | 60 | 2009-06-28T00:32:21Z | 1,062,629 | 74 | 2009-06-30T09:11:55Z | [
"python",
"matrix",
"numpy"
] | [NumPy](http://en.wikipedia.org/wiki/NumPy) is an extremely useful library, and from using it I've found that it's capable of handling matrices which are quite large (10000 x 10000) easily, but begins to struggle with anything much larger (trying to create a matrix of 50000 x 50000 fails). Obviously, this is because of... | PyTables and NumPy are the way to go.
PyTables will store the data on disk in HDF format, with optional compression. My datasets often get 10x compression, which is handy when dealing with tens or hundreds of millions of rows. It's also very fast; my 5 year old laptop can crunch through data doing SQL-like GROUP BY ag... |
printing bit representation of numbers in python | 1,054,116 | 37 | 2009-06-28T02:55:44Z | 1,054,126 | 19 | 2009-06-28T03:00:48Z | [
"python"
] | I want to print the bit representation of numbers onto console, so that I can see all operations that are being done on bits itself.
How can I possibly do it in python? | **In Python 2.6+**:
```
print bin(123)
```
Results in:
```
0b1111011
```
**In python 2.x**
```
>>> binary = lambda n: n>0 and [n&1]+binary(n>>1) or []
>>> binary(123)
[1, 1, 0, 1, 1, 1, 1]
```
Note, example taken from: "Mark Dufour" at <http://mail.python.org/pipermail/python-list/2003-December/240914.html> |
printing bit representation of numbers in python | 1,054,116 | 37 | 2009-06-28T02:55:44Z | 1,054,130 | 41 | 2009-06-28T03:02:54Z | [
"python"
] | I want to print the bit representation of numbers onto console, so that I can see all operations that are being done on bits itself.
How can I possibly do it in python? | This kind of thing?
```
>>> ord('a')
97
>>> hex(ord('a'))
'0x61'
>>> bin(ord('a'))
'0b1100001'
``` |
printing bit representation of numbers in python | 1,054,116 | 37 | 2009-06-28T02:55:44Z | 18,946,037 | 15 | 2013-09-22T16:26:14Z | [
"python"
] | I want to print the bit representation of numbers onto console, so that I can see all operations that are being done on bits itself.
How can I possibly do it in python? | From Python 2.6, with the [string.format method](http://docs.python.org/2/library/string.html#string-formatting):
```
"{0:b}".format(0x1234)
```
in particular, you might like to use padding, so that multiple prints of different numbers still line up:
```
"{0:16b}".format(0x1234)
```
and to have left padding with le... |
How frequently should Python decorators be used? | 1,054,249 | 3 | 2009-06-28T04:41:28Z | 1,054,283 | 12 | 2009-06-28T05:02:09Z | [
"python",
"django",
"decorator"
] | I recently started experimenting with Python decorators (and higher-order functions) because it looked like they might make my Django unit tests more concise. e.g., instead of writing:
```
def visit1():
login()
do_stuff()
logout()
```
I could instead do
```
@handle_login
def visit1():
do_stuff()
```
... | Decorators are fine in their place and definitely not to be avoided -- when appropriate;-). I see your question as meaning essentially "OK so when *are* they appropriate"?
Adding some prefix and/or postfix code around some but not all methods of some classes is a good example. Were it all methods, a *class* decorator ... |
How to import a Python class that is in a directory above? | 1,054,271 | 83 | 2009-06-28T04:56:25Z | 1,054,281 | 73 | 2009-06-28T05:01:14Z | [
"python",
"module",
"directory",
"python-import"
] | I want to inherit from a class in a file that lies in a directory above the current one.
Is it possible to relatively import that file? | Inside a package hierarchy, use two dots, as the [import statement](http://docs.python.org/reference/simple_stmts.html#the-import-statement) doc says:
> When specifying what module to import you do not have to specify the absolute name of the module. When a module or package is contained within another package it is p... |
How to import a Python class that is in a directory above? | 1,054,271 | 83 | 2009-06-28T04:56:25Z | 1,054,293 | 47 | 2009-06-28T05:07:01Z | [
"python",
"module",
"directory",
"python-import"
] | I want to inherit from a class in a file that lies in a directory above the current one.
Is it possible to relatively import that file? | @gimel's answer is correct *if* you can guarantee the package hierarchy he mentions. If you can't -- if your real need is as you expressed it, exclusively tied to directories and without any necessary relationship to packaging -- then you need to work on `__file__` to find out the parent directory (a couple of `os.path... |
How to import a Python class that is in a directory above? | 1,054,271 | 83 | 2009-06-28T04:56:25Z | 11,096,846 | 32 | 2012-06-19T08:06:11Z | [
"python",
"module",
"directory",
"python-import"
] | I want to inherit from a class in a file that lies in a directory above the current one.
Is it possible to relatively import that file? | ```
import sys
sys.path.append("..") # Adds higher directory to python modules path.
``` |
How to import a Python class that is in a directory above? | 1,054,271 | 83 | 2009-06-28T04:56:25Z | 23,103,505 | 8 | 2014-04-16T08:05:59Z | [
"python",
"module",
"directory",
"python-import"
] | I want to inherit from a class in a file that lies in a directory above the current one.
Is it possible to relatively import that file? | ```
from .. import module # Import module from a higher directory.
``` |
Django official tutorial for the absolute beginner, absolutely failed! | 1,054,494 | 2 | 2009-06-28T07:59:10Z | 1,054,535 | 12 | 2009-06-28T08:40:02Z | [
"python",
"django"
] | Not that level of failure indeed. I just completed the 4 part tutorial from djangoproject.com, my administration app works fine and my entry point url (/polls/) works well, with the exception that I get this http response:
**No polls are available.**
Even if the database has one registry. Entering with the admin app,... | You overlooked this paragraph in the 4. part of the tutorial:
> In previous parts of the tutorial, the templates have been provided with a context that contains the poll and `latest_poll_list` context variables. However, the generic views provide the variables `object` and `object_list` as context. Therefore, you need... |
How do you get Python documentation in Texinfo Info format? | 1,054,903 | 30 | 2009-06-28T13:11:38Z | 3,952,588 | 22 | 2010-10-17T08:48:56Z | [
"python",
"emacs",
"restructuredtext",
"texinfo"
] | Since Python 2.6, it seems the documentation is in the new [reStructuredText](http://docs.python.org/whatsnew/2.6.html#new-documentation-format-restructuredtext-using-sphinx) format, and it doesn't seem very easy to build a [Texinfo Info](http://en.wikipedia.org/wiki/Info%5F%28Unix%29) file out of the box anymore.
I'm... | Jon Waltman <http://bitbucket.org/jonwaltman/sphinx-info> has forked sphinx and written a texinfo builder, it can build the python documentation (I've yet done it). It seems that it will be merged soon into sphinx.
Here's the quick links for the downloads (temporary):
* <http://dl.dropbox.com/u/1276730/python.info>
*... |
How do you get Python documentation in Texinfo Info format? | 1,054,903 | 30 | 2009-06-28T13:11:38Z | 18,847,967 | 7 | 2013-09-17T10:56:02Z | [
"python",
"emacs",
"restructuredtext",
"texinfo"
] | Since Python 2.6, it seems the documentation is in the new [reStructuredText](http://docs.python.org/whatsnew/2.6.html#new-documentation-format-restructuredtext-using-sphinx) format, and it doesn't seem very easy to build a [Texinfo Info](http://en.wikipedia.org/wiki/Info%5F%28Unix%29) file out of the box anymore.
I'm... | I've packaged up the [Python docs as a texinfo file](https://github.com/wilfred/python-info).
If you're using Emacs with MELPA, you can simply install this with `M-x package-install python-info`. |
Unicode friendly alphabetic pattern for python regex? | 1,055,160 | 4 | 2009-06-28T16:04:58Z | 1,055,173 | 11 | 2009-06-28T16:09:44Z | [
"python",
"regex"
] | I'm looking for a pattern equivalent to \w, and which doesn't match numeric pattern.
I cannot use [a-zA-Z] because I would like it to match japanese kanjis as well.
Is there a way to write something like [\w^[0-9]] ?
Is there an equivalent of [:alpha:] in python regex? | ```
[^\W\d]
```
Throw out non-word characters and throw out digits. Keep the rest. |
how to tell a variable is iterable but not a string | 1,055,360 | 37 | 2009-06-28T17:45:28Z | 1,055,378 | 29 | 2009-06-28T17:56:28Z | [
"python"
] | I have a function that take an argument which can be either a single item or a double item:
```
def iterable(arg)
if #arg is an iterable:
print "yes"
else:
print "no"
```
so that:
```
>>> iterable( ("f","f") )
yes
>>> iterable( ["f","f"] )
yes
>>> iterable("ff")
no
```
The problem is that ... | Use isinstance (I don't see why it's bad practice)
```
import types
if not isinstance(arg, types.StringTypes):
```
Note the use of StringTypes. It ensures that we don't forget about some obscure type of string.
On the upside, this also works for derived string classes.
```
class MyString(str):
pass
isinstance(... |
how to tell a variable is iterable but not a string | 1,055,360 | 37 | 2009-06-28T17:45:28Z | 1,055,540 | 14 | 2009-06-28T19:11:24Z | [
"python"
] | I have a function that take an argument which can be either a single item or a double item:
```
def iterable(arg)
if #arg is an iterable:
print "yes"
else:
print "no"
```
so that:
```
>>> iterable( ("f","f") )
yes
>>> iterable( ["f","f"] )
yes
>>> iterable("ff")
no
```
The problem is that ... | Since Python 2.6, with the introduction of abstract base classes, `isinstance` (used on ABCs, not concrete classes) is now considered perfectly acceptable. Specifically:
```
from abc import ABCMeta, abstractmethod
class NonStringIterable:
__metaclass__ = ABCMeta
@abstractmethod
def __iter__(self):
... |
How do I find out what Python libraries are installed on my Mac? | 1,055,443 | 7 | 2009-06-28T18:27:35Z | 1,055,453 | 31 | 2009-06-28T18:31:07Z | [
"python"
] | I'm just starting out with Python, and have found out that I can import various libraries. How do I find out what libraries exist on my Mac that I can import? How do I find out what functions they include?
I seem to remember using some web server type thing to browse through local help files, but I may have imagined t... | From the Python REPL (the command-line interpreter / Read-Eval-Print-Loop), type `help("modules")` to see a list of all your available libs.
Then to see functions within a module, do `help("posix")`, for example. If you haven't `import`ed the library yet, you have to put quotes around the library's name. |
item frequency in a python list of dictionaries | 1,055,646 | 7 | 2009-06-28T20:15:42Z | 1,055,662 | 13 | 2009-06-28T20:23:10Z | [
"python",
"dictionary"
] | Ok, so I have a list of dicts:
```
[{'name': 'johnny', 'surname': 'smith', 'age': 53},
{'name': 'johnny', 'surname': 'ryan', 'age': 13},
{'name': 'jakob', 'surname': 'smith', 'age': 27},
{'name': 'aaron', 'surname': 'specter', 'age': 22},
{'name': 'max', 'surname': 'headroom', 'age': 108},
]
```
and I want the 'f... | `collections.defaultdict` from the standard library to the rescue:
```
from collections import defaultdict
LofD = [{'name': 'johnny', 'surname': 'smith', 'age': 53},
{'name': 'johnny', 'surname': 'ryan', 'age': 13},
{'name': 'jakob', 'surname': 'smith', 'age': 27},
{'name': 'aaron', 'surname': 'specter', 'age': 22... |
Server Logging - in Database or Logfile? | 1,055,917 | 10 | 2009-06-28T22:23:18Z | 1,056,213 | 10 | 2009-06-29T01:21:13Z | [
"python",
"logging"
] | I've been working on a server and I'm starting to implement logging. However, I'm not sure whether I should use the db for logging, or just a plaintext file.
I'm planning on logging some basic information for every request (what type of request, ip address of request, session tracking). For some requests there will be... | First, use a logging library like SLF4J/Logback that allows you to make this decision dynamically. Then you can tweak a configuration file and route some or all of your log messages to each of several different destinations.
Be very careful before logging to your application database, you can easily overwhelm it if yo... |
Can two versions of the same library coexist in the same Python install? | 1,055,926 | 2 | 2009-06-28T22:30:09Z | 1,055,966 | 8 | 2009-06-28T22:52:20Z | [
"python",
"shared-libraries"
] | The C libraries have a nice form of late binding, where the exact version of the library that was used during linking is recorded, and thus an executable can find the correct file, even when several versions of the same library are installed.
Can the same be done in Python?
To be more specific, I work on a Python pro... | You may want to take a look at [virtualenv](http://pypi.python.org/pypi/virtualenv) |
How do you call Python code from C code? | 1,056,051 | 29 | 2009-06-28T23:37:19Z | 1,056,057 | 9 | 2009-06-28T23:42:27Z | [
"python",
"c",
"interop",
"cross-domain"
] | I want to extend a large C project with some new functionality, but I really want to write it in Python. Basically, I want to call Python code from C code. However, Python->C wrappers like SWIG allow for the OPPOSITE, that is writing C modules and calling C from Python.
I'm considering an approach involving IPC or RPC... | I recommend the [approaches detailed here](http://www.linuxjournal.com/article/8497). It starts by explaining how to execute strings of Python code, then from there details how to set up a Python environment to interact with your C program, call Python functions from your C code, manipulate Python objects from your C c... |
Random Python dictionary key, weighted by values | 1,056,151 | 31 | 2009-06-29T00:46:06Z | 1,056,154 | 32 | 2009-06-29T00:48:31Z | [
"python",
"random",
"dictionary"
] | I have a dictionary where each key has a list of variable length, eg:
```
d = {
'a': [1, 3, 2],
'b': [6],
'c': [0, 0]
}
```
Is there a clean way to get a random dictionary key, weighted by the length of its value?
`random.choice(d.keys())` will weight the keys equally, but in the case above I want `'a'` to be retu... | This would work:
```
random.choice([k for k in d for x in d[k]])
``` |
Random Python dictionary key, weighted by values | 1,056,151 | 31 | 2009-06-29T00:46:06Z | 1,056,187 | 17 | 2009-06-29T01:08:17Z | [
"python",
"random",
"dictionary"
] | I have a dictionary where each key has a list of variable length, eg:
```
d = {
'a': [1, 3, 2],
'b': [6],
'c': [0, 0]
}
```
Is there a clean way to get a random dictionary key, weighted by the length of its value?
`random.choice(d.keys())` will weight the keys equally, but in the case above I want `'a'` to be retu... | Do you always know the total number of values in the dictionary? If so, this might be easy to do with the following algorithm, which can be used whenever you want to make a probabilistic selection of some items from an ordered list:
1. Iterate over your list of keys.
2. Generate a uniformly distributed random value be... |
Random Python dictionary key, weighted by values | 1,056,151 | 31 | 2009-06-29T00:46:06Z | 2,321,466 | 8 | 2010-02-23T20:28:04Z | [
"python",
"random",
"dictionary"
] | I have a dictionary where each key has a list of variable length, eg:
```
d = {
'a': [1, 3, 2],
'b': [6],
'c': [0, 0]
}
```
Is there a clean way to get a random dictionary key, weighted by the length of its value?
`random.choice(d.keys())` will weight the keys equally, but in the case above I want `'a'` to be retu... | Without constructing a new, possibly big list with repeated values:
```
def select_weighted(d):
offset = random.randint(0, sum(d.itervalues())-1)
for k, v in d.iteritems():
if offset < v:
return k
offset -= v
``` |
Python Scrapy , how to define a pipeline for an item? | 1,056,651 | 12 | 2009-06-29T05:09:33Z | 1,330,564 | 14 | 2009-08-25T19:54:00Z | [
"python",
"screen-scraping",
"scrapy"
] | I am using scrapy to crawl different sites, for each site I have an Item (different information is extracted)
Well, for example I have a generic pipeline (most of information is the same) but now I am crawling some google search response and the pipeline must be different.
For example:
`GenericItem` uses `GenericPip... | Now only one way - check Item type in pipeline and process it or return "as is"
*pipelines.py*:
```
from grabbers.items import FeedItem
class StoreFeedPost(object):
def process_item(self, domain, item):
if isinstance(item, FeedItem):
#process it...
return item
```
*items.py*:
```
... |
How do I access the request object or any other variable in a form's clean() method? | 1,057,252 | 74 | 2009-06-29T08:49:45Z | 1,057,418 | 13 | 2009-06-29T09:34:58Z | [
"python",
"django"
] | I am trying to request.user for a form's clean method, but how can I access the request object? Can I modify the clean method to allow variables input? | The usual aproach is to store the request object in a thread-local reference using a middleware. Then you can access this from anywhere in you app, including the Form.clean() method.
Changing the signature of the Form.clean() method means you have you own, modified version of Django, which may not be what you want.
T... |
How do I access the request object or any other variable in a form's clean() method? | 1,057,252 | 74 | 2009-06-29T08:49:45Z | 1,057,640 | 128 | 2009-06-29T10:36:55Z | [
"python",
"django"
] | I am trying to request.user for a form's clean method, but how can I access the request object? Can I modify the clean method to allow variables input? | The answer by Ber - storing it in threadlocals - is a very bad idea. There's absolutely no reason to do it this way.
A much better way is to override the form's `__init__` method to take an extra keyword argument, `request`. This stores the request in the *form*, where it's required, and from where you can access it i... |
How do I access the request object or any other variable in a form's clean() method? | 1,057,252 | 74 | 2009-06-29T08:49:45Z | 6,062,628 | 24 | 2011-05-19T17:39:58Z | [
"python",
"django"
] | I am trying to request.user for a form's clean method, but how can I access the request object? Can I modify the clean method to allow variables input? | **UPDATED 10/25/2011**: I'm now using this with a metaclass instead of method, as Django 1.3 displays some weirdness otherwise.
```
class MyModelAdmin(admin.ModelAdmin):
form = MyCustomForm
def get_form(self, request, obj=None, **kwargs):
ModelForm = super(MyModelAdmin, self).get_form(request, obj, **k... |
How do I access the request object or any other variable in a form's clean() method? | 1,057,252 | 74 | 2009-06-29T08:49:45Z | 25,930,538 | 16 | 2014-09-19T09:20:59Z | [
"python",
"django"
] | I am trying to request.user for a form's clean method, but how can I access the request object? Can I modify the clean method to allow variables input? | For what it's worth, if you're using **Class Based Views**, instead of function based views, override [`get_form_kwargs`](https://docs.djangoproject.com/en/1.7/ref/class-based-views/mixins-editing/#django.views.generic.edit.FormMixin.get_form_kwargs) in your editing view. Example code for a custom [CreateView](https://... |
Loading all modules in a folder in Python | 1,057,431 | 122 | 2009-06-29T09:38:15Z | 1,057,446 | 69 | 2009-06-29T09:42:33Z | [
"python",
"python-import"
] | Could someone provide me with a good way of importing a whole directory of modules?
I have a structure like this:
```
/Foo
bar.py
spam.py
eggs.py
```
I tried just converting it to a package by adding `__init__.py` and doing `from Foo import *` but it didn't work the way I had hoped. | Add the `__all__` Variable to `__init__.py` containing:
```
__all__ = ["bar", "spam", "eggs"]
```
See also <http://docs.python.org/tutorial/modules.html> |
Loading all modules in a folder in Python | 1,057,431 | 122 | 2009-06-29T09:38:15Z | 1,057,534 | 215 | 2009-06-29T10:06:25Z | [
"python",
"python-import"
] | Could someone provide me with a good way of importing a whole directory of modules?
I have a structure like this:
```
/Foo
bar.py
spam.py
eggs.py
```
I tried just converting it to a package by adding `__init__.py` and doing `from Foo import *` but it didn't work the way I had hoped. | List all python (`.py`) files in the current folder and put them as `__all__` variable in `__init__.py`
```
from os.path import dirname, basename, isfile
import glob
modules = glob.glob(dirname(__file__)+"/*.py")
__all__ = [ basename(f)[:-3] for f in modules if isfile(f)]
``` |
Loading all modules in a folder in Python | 1,057,431 | 122 | 2009-06-29T09:38:15Z | 1,057,765 | 30 | 2009-06-29T11:10:40Z | [
"python",
"python-import"
] | Could someone provide me with a good way of importing a whole directory of modules?
I have a structure like this:
```
/Foo
bar.py
spam.py
eggs.py
```
I tried just converting it to a package by adding `__init__.py` and doing `from Foo import *` but it didn't work the way I had hoped. | Make the Foo directory a package by adding an `__init__.py`. In that `__init__.py` add:
```
import bar
import eggs
import spam
```
Since you want it dynamic (which may or may not be a good idea), list all py-files with list dir and import them with something like this:
```
import os
for module in os.listdir(os.path.... |
Loading all modules in a folder in Python | 1,057,431 | 122 | 2009-06-29T09:38:15Z | 8,556,471 | 27 | 2011-12-19T02:11:12Z | [
"python",
"python-import"
] | Could someone provide me with a good way of importing a whole directory of modules?
I have a structure like this:
```
/Foo
bar.py
spam.py
eggs.py
```
I tried just converting it to a package by adding `__init__.py` and doing `from Foo import *` but it didn't work the way I had hoped. | Expanding on Mihail's answer, I believe the non-hackish way (as in, not handling the file paths directly) is the following:
1. create an empty `__init__.py` file under `Foo/`
2. Execute
```
import pkgutil
import sys
def load_all_modules_from_dir(dirname):
for importer, package_name, _ in pkgutil.iter_modules([d... |
Loading all modules in a folder in Python | 1,057,431 | 122 | 2009-06-29T09:38:15Z | 9,560,906 | 14 | 2012-03-05T02:24:09Z | [
"python",
"python-import"
] | Could someone provide me with a good way of importing a whole directory of modules?
I have a structure like this:
```
/Foo
bar.py
spam.py
eggs.py
```
I tried just converting it to a package by adding `__init__.py` and doing `from Foo import *` but it didn't work the way I had hoped. | I got tired of this problem myself, so I wrote a package called automodinit to fix it. You can get it from <http://pypi.python.org/pypi/automodinit/>.
Usage is like this:
1. Include the `automodinit` package into your `setup.py` dependencies.
2. Replace all \_\_init\_\_.py files like this:
```
__all__ = ["I will get... |
Loading all modules in a folder in Python | 1,057,431 | 122 | 2009-06-29T09:38:15Z | 20,753,073 | 17 | 2013-12-24T00:08:56Z | [
"python",
"python-import"
] | Could someone provide me with a good way of importing a whole directory of modules?
I have a structure like this:
```
/Foo
bar.py
spam.py
eggs.py
```
I tried just converting it to a package by adding `__init__.py` and doing `from Foo import *` but it didn't work the way I had hoped. | ## Python, include all files under a directory:
For newbies who just can't get it to work who need their hands held.
1. Make a folder /home/el/foo and make a file `main.py` under /home/el/foo Put this code in there:
```
from hellokitty import *
spam.spamfunc()
ham.hamfunc()
```
2. Make a directory `/h... |
How to do windows API calls in Python 3.1? | 1,057,496 | 5 | 2009-06-29T09:56:42Z | 1,057,573 | 8 | 2009-06-29T10:14:52Z | [
"python",
"winapi",
"python-3.x"
] | Has anyone found a version of [pywin32](http://python.net/crew/mhammond/win32/) for python 3.x? The latest available appears to be for 2.6.
Alternatively, how would I "roll my own" windows API calls in Python 3.1? | You should be able to do everything with [ctypes](http://docs.python.org/library/ctypes.html), if a bit cumbersomely.
Here's an example of getting the "common application data" folder:
```
from ctypes import windll, wintypes
_SHGetFolderPath = windll.shell32.SHGetFolderPathW
path_buf = wintypes.create_unicode_buffer... |
How to call a data member of the base class if it is being overwritten as a property in the derived class? | 1,057,518 | 5 | 2009-06-29T10:03:17Z | 1,057,656 | 9 | 2009-06-29T10:41:40Z | [
"python",
"inheritance",
"overloading",
"descriptor"
] | This question is similar to [this other one](http://stackoverflow.com/questions/1021464/python-how-to-call-a-property-of-the-base-class-if-this-property-is-being-overwr), with the difference that the data member in the base class is *not* wrapped by the descriptor protocol.
In other words, how can I access a member of... | Life is simpler if you use delegation instead of inheritance. This is Python. You aren't obligated to inherit from `Base`.
```
class LooksLikeDerived( object ):
def __init__( self ):
self.base= Base()
@property
def foo(self):
return 1 + self.base.foo # always works
@foo.setter
def... |
Bad pipe filedescriptor when reading from stdin in python | 1,057,638 | 2 | 2009-06-29T10:36:37Z | 1,057,681 | 7 | 2009-06-29T10:48:54Z | [
"python",
"windows",
"pipe"
] | **Duplicate of [this](http://stackoverflow.com/questions/466801/python-piping-on-windows-why-does-this-not-work) question. Vote to close.**
Consider this at the windows commandline.
```
scriptA.py | scriptB.py
```
In scriptA.py:
```
sys.stdout.write( "hello" )
```
In scriptB.py:
```
print sys.stdin.read()
```
Th... | It seems that stdin/stdout redirect does not work when starting from a file association.
This is not specific to python, but a problem caused by win32 cmd.exe.
See: <http://mail.python.org/pipermail/python-bugs-list/2004-August/024920.html> |
Using Python to replace MATLAB: how to import data? | 1,057,666 | 11 | 2009-06-29T10:44:24Z | 1,057,748 | 11 | 2009-06-29T11:06:15Z | [
"python",
"excel",
"matlab",
"numpy"
] | I want to use some Python libraries to replace MATLAB. How could I import Excel data in Python (for example using [NumPy](http://en.wikipedia.org/wiki/NumPy)) to use them?
I don't know if Python is a credible alternative to MATLAB, but I want to try it. Is there a a tutorial? | Depending on what kind of computations you are doing with [MATLAB](http://en.wikipedia.org/wiki/MATLAB) (and on which toolboxes you are using), Python could be a good alternative to MATLAB.
Python + [NumPy](http://en.wikipedia.org/wiki/NumPy) + [SciPy](http://en.wikipedia.org/wiki/SciPy) + [Matplotlib](http://en.wikip... |
How can I import a package using __import__() when the package name is only known at runtime? | 1,057,843 | 13 | 2009-06-29T11:35:00Z | 1,057,891 | 13 | 2009-06-29T11:46:41Z | [
"python",
"python-import"
] | I have a messages folder(package) with `__init__.py` file and another module `messages_en.py` inside it. In `__init__.py` if I import `messages_en` it works, but `__import__` fails with "ImportError: No module named messages\_en"
```
import messages_en # it works
messages = __import__('messages_en') # it doesn't ?
```... | `__import__` is an internal function called by import statement. In everyday coding you don't need (or want) to call `__import__`
from python documentation:
For example, the statement `import spam` results in bytecode resembling the following code:
```
spam = __import__('spam', globals(), locals(), [], -1)
```
On t... |
How can I import a package using __import__() when the package name is only known at runtime? | 1,057,843 | 13 | 2009-06-29T11:35:00Z | 1,057,898 | 19 | 2009-06-29T11:49:01Z | [
"python",
"python-import"
] | I have a messages folder(package) with `__init__.py` file and another module `messages_en.py` inside it. In `__init__.py` if I import `messages_en` it works, but `__import__` fails with "ImportError: No module named messages\_en"
```
import messages_en # it works
messages = __import__('messages_en') # it doesn't ?
```... | If it is a path problem, you should use the `level` argument (from [docs](http://docs.python.org/2/library/functions.html?highlight=__import__#__import__)):
```
__import__(name, globals={}, locals={}, fromlist=[], level=-1) -> module
Level is used to determine whether to perform
absolute or relative imports. -1 is t... |
How can I import a package using __import__() when the package name is only known at runtime? | 1,057,843 | 13 | 2009-06-29T11:35:00Z | 13,175,052 | 14 | 2012-11-01T10:22:54Z | [
"python",
"python-import"
] | I have a messages folder(package) with `__init__.py` file and another module `messages_en.py` inside it. In `__init__.py` if I import `messages_en` it works, but `__import__` fails with "ImportError: No module named messages\_en"
```
import messages_en # it works
messages = __import__('messages_en') # it doesn't ?
```... | Adding the globals argument is sufficient for me:
```
__import__('messages_en', globals=globals())
```
In fact, only `__name__` is needed here:
```
__import__('messages_en', globals={"__name__": __name__})
``` |
Flags in Python | 1,058,434 | 4 | 2009-06-29T13:49:38Z | 1,058,466 | 7 | 2009-06-29T13:56:34Z | [
"python",
"matrix",
"numpy",
"flags"
] | I'm working with a large matrix (250x250x30 = 1,875,000 cells), and I'd like a way to set an arbitrary number of flags for each cell in this matrix, in some manner that's easy to use and reasonably space efficient.
My original plan was a 250x250x30 list array, where each element was something like: `["FLAG1","FLAG8","... | Your solution is fine if every single cell is going to have a flag. However if you are working with a sparse dataset where only a small subsection of your cells will have flags what you really want is a dictionary. You would want to set up the dictonary so the key is a tuple for the location of the cell and the value i... |
How to get a nested element in beautiful soup | 1,058,599 | 10 | 2009-06-29T14:22:55Z | 1,058,691 | 11 | 2009-06-29T14:37:15Z | [
"python",
"beautifulsoup"
] | I am struggling with the syntax required to grab some hrefs in a td.
The table, tr and td elements dont have any class's or id's.
If I wanted to grab the anchor in this example, what would I need?
< tr >
< td > < a >...
Thanks | Something like this?
```
from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup(html)
anchors = [td.find('a') for td in soup.findAll('td')]
```
That should find the first "a" inside each "td" in the html you provide. You can tweak `td.find` to be more specific or else use `findAll` if you have several links ins... |
How to get a nested element in beautiful soup | 1,058,599 | 10 | 2009-06-29T14:22:55Z | 1,058,693 | 12 | 2009-06-29T14:37:27Z | [
"python",
"beautifulsoup"
] | I am struggling with the syntax required to grab some hrefs in a td.
The table, tr and td elements dont have any class's or id's.
If I wanted to grab the anchor in this example, what would I need?
< tr >
< td > < a >...
Thanks | As per the docs, you first make a parse tree:
```
import BeautifulSoup
html = "<html><body><tr><td><a href='foo'/></td></tr></body></html>"
soup = BeautifulSoup.BeautifulSoup(html)
```
and then you search in it, for example for `<a>` tags whose immediate parent is a `<td>`:
```
for ana in soup.findAll('a'):
if ana... |
How do I select a random element from an array in Python? | 1,058,712 | 34 | 2009-06-29T14:42:22Z | 1,058,725 | 20 | 2009-06-29T14:44:32Z | [
"python",
"arrays",
"random"
] | The first examples that I googled didn't work. This should be trivial, right? | ```
import random
random.choice([1, 2, 3])
``` |
How do I select a random element from an array in Python? | 1,058,712 | 34 | 2009-06-29T14:42:22Z | 1,058,727 | 88 | 2009-06-29T14:44:38Z | [
"python",
"arrays",
"random"
] | The first examples that I googled didn't work. This should be trivial, right? | ```
import random
random.choice (mylist)
``` |
How do I select a random element from an array in Python? | 1,058,712 | 34 | 2009-06-29T14:42:22Z | 1,058,764 | 7 | 2009-06-29T14:50:57Z | [
"python",
"arrays",
"random"
] | The first examples that I googled didn't work. This should be trivial, right? | Here's the documentation link: <http://docs.python.org/library/random.html#random.choice> |
How to append two strings in Python? | 1,058,902 | 2 | 2009-06-29T15:22:32Z | 1,058,922 | 19 | 2009-06-29T15:26:25Z | [
"python",
"string"
] | I have done this operation millions of times, just using the `+` operator! I have no idea why it is not working this time, it is overwriting the first part of the string with the new one! I have a list of strings and just want to concatenate them in one single string! If I run the program from Eclipse it works, from th... | You should use the following and forget about this nightmare:
```
''.join(list_of_strings)
``` |
How to append two strings in Python? | 1,058,902 | 2 | 2009-06-29T15:22:32Z | 1,058,957 | 31 | 2009-06-29T15:32:26Z | [
"python",
"string"
] | I have done this operation millions of times, just using the `+` operator! I have no idea why it is not working this time, it is overwriting the first part of the string with the new one! I have a list of strings and just want to concatenate them in one single string! If I run the program from Eclipse it works, from th... | While the two answers are correct (use " ".join()), your problem (besides *very* ugly python code) is this:
Your strings end in "\r", which is a carriage return. Everything is fine, but when you print to the console, "\r" will make printing continue from the start *of the same line*, hence overwrite what was written o... |
How to append two strings in Python? | 1,058,902 | 2 | 2009-06-29T15:22:32Z | 1,058,974 | 11 | 2009-06-29T15:37:49Z | [
"python",
"string"
] | I have done this operation millions of times, just using the `+` operator! I have no idea why it is not working this time, it is overwriting the first part of the string with the new one! I have a list of strings and just want to concatenate them in one single string! If I run the program from Eclipse it works, from th... | The problem is not with the concatenation of the strings (although that could use some cleaning up), but in your printing. The \r in your string has a special meaning and will overwrite previously printed strings.
Use repr(), as such:
```
...
print "line value : ", repr(lineList[count])
temp = lineList[count]
ediMsg ... |
How to append two strings in Python? | 1,058,902 | 2 | 2009-06-29T15:22:32Z | 1,058,982 | 8 | 2009-06-29T15:39:59Z | [
"python",
"string"
] | I have done this operation millions of times, just using the `+` operator! I have no idea why it is not working this time, it is overwriting the first part of the string with the new one! I have a list of strings and just want to concatenate them in one single string! If I run the program from Eclipse it works, from th... | '\r' is the carriage return character. When you're printing out a string, a '\r' will cause the next characters to go at the start of the line.
Change this:
```
print "ediMsg : ",ediMsg
```
to:
```
print "ediMsg : ",repr(ediMsg)
```
and you will see the embedded `\r` values.
And while your code works, *pl... |
How to append two strings in Python? | 1,058,902 | 2 | 2009-06-29T15:22:32Z | 1,059,010 | 7 | 2009-06-29T15:44:39Z | [
"python",
"string"
] | I have done this operation millions of times, just using the `+` operator! I have no idea why it is not working this time, it is overwriting the first part of the string with the new one! I have a list of strings and just want to concatenate them in one single string! If I run the program from Eclipse it works, from th... | Your problem **is** printing, and it **is not** string manipulation. Try using '\n' as last char instead of '\r' in each string in:
```
lineList = [
"UNH+1+TCCARQ:08:2:1A+%CONVID%'&\r",
"ORG+1A+77499505:PARAF0103+++A+FR:EUR++11730788+1A'&\r",
"DUM'&\r",
"FPT+CC::::::::N'&\r",
"CCD+CA:51328390000000... |
Searching across multiple tables (best practices) | 1,059,253 | 2 | 2009-06-29T16:36:05Z | 1,059,280 | 7 | 2009-06-29T16:42:14Z | [
"python",
"sql",
"mysql",
"postgresql",
"pylons"
] | I have property management application consisting of tables:
```
tenants
landlords
units
properties
vendors-contacts
```
Basically I want one search field to search them all rather than having to select which category I am searching. Would this be an acceptable solution (technology wise?)
Will searching across 5 tab... | Why not create a view which is a union of the tables which aggregates the columns you want to search on into one, and then search on that aggregated column?
You could do something like this:
```
select 'tenants:' + ltrim(str(t.Id)), <shared fields> from Tenants as t union
select 'landlords:' + ltrim(str(l.Id)), <shar... |
Python - Split Strings with Multiple Delimiters | 1,059,559 | 334 | 2009-06-29T17:49:35Z | 1,059,596 | 271 | 2009-06-29T17:56:39Z | [
"python",
"string",
"split"
] | I think what I want to do is a fairly common task but I've found no reference on the web. I have text, with punctuation, and I want list of the words.
```
"Hey, you - what are you doing here!?"
```
should be
```
['hey', 'you', 'what', 'are', 'you', 'doing', 'here']
```
But Python's `str.split()` only works with one... | A case where regular expressions are justified:
```
import re
DATA = "Hey, you - what are you doing here!?"
print re.findall(r"[\w']+", DATA)
# Prints ['Hey', 'you', 'what', 'are', 'you', 'doing', 'here']
```
[Edited to include `'` in the word characters - thanks, Danosaure.] |
Python - Split Strings with Multiple Delimiters | 1,059,559 | 334 | 2009-06-29T17:49:35Z | 1,059,601 | 244 | 2009-06-29T17:57:49Z | [
"python",
"string",
"split"
] | I think what I want to do is a fairly common task but I've found no reference on the web. I have text, with punctuation, and I want list of the words.
```
"Hey, you - what are you doing here!?"
```
should be
```
['hey', 'you', 'what', 'are', 'you', 'doing', 'here']
```
But Python's `str.split()` only works with one... | [re.split()](http://docs.python.org/library/re.html#re.split)
> re.split(pattern, string[, maxsplit=0])
>
> Split string by the occurrences of pattern. If capturing parentheses are used in pattern, then the text of all groups in the pattern are also returned as part of the resulting list. If maxsplit is nonzero, at mo... |
Python - Split Strings with Multiple Delimiters | 1,059,559 | 334 | 2009-06-29T17:49:35Z | 1,157,498 | 40 | 2009-07-21T06:02:03Z | [
"python",
"string",
"split"
] | I think what I want to do is a fairly common task but I've found no reference on the web. I have text, with punctuation, and I want list of the words.
```
"Hey, you - what are you doing here!?"
```
should be
```
['hey', 'you', 'what', 'are', 'you', 'doing', 'here']
```
But Python's `str.split()` only works with one... | Another way, without regex
```
import string
punc = string.punctuation
thestring = "Hey, you - what are you doing here!?"
s = list(thestring)
''.join([o for o in s if not o in punc]).split()
``` |
Python - Split Strings with Multiple Delimiters | 1,059,559 | 334 | 2009-06-29T17:49:35Z | 2,911,664 | 20 | 2010-05-26T09:31:24Z | [
"python",
"string",
"split"
] | I think what I want to do is a fairly common task but I've found no reference on the web. I have text, with punctuation, and I want list of the words.
```
"Hey, you - what are you doing here!?"
```
should be
```
['hey', 'you', 'what', 'are', 'you', 'doing', 'here']
```
But Python's `str.split()` only works with one... | Kinda late answer :), but I had a similar dilemma and didn't want to use 're' module.
```
def my_split(s, seps):
res = [s]
for sep in seps:
s, res = res, []
for seq in s:
res += seq.split(sep)
return res
print my_split('1111 2222 3333;4444,5555;6666', [' ', ';', ','])
['1111',... |
Python - Split Strings with Multiple Delimiters | 1,059,559 | 334 | 2009-06-29T17:49:35Z | 5,894,804 | 8 | 2011-05-05T08:35:59Z | [
"python",
"string",
"split"
] | I think what I want to do is a fairly common task but I've found no reference on the web. I have text, with punctuation, and I want list of the words.
```
"Hey, you - what are you doing here!?"
```
should be
```
['hey', 'you', 'what', 'are', 'you', 'doing', 'here']
```
But Python's `str.split()` only works with one... | ```
join = lambda x: sum(x,[]) # a.k.a. flatten1([[1],[2,3],[4]]) -> [1,2,3,4]
# ...alternatively...
join = lambda lists: [x for l in lists for x in l]
```
Then this becomes a three-liner:
```
fragments = [text]
for token in tokens:
fragments = join(f.split(token) for f in fragments)
```
---
**Explanation**
T... |
Python - Split Strings with Multiple Delimiters | 1,059,559 | 334 | 2009-06-29T17:49:35Z | 7,215,696 | 147 | 2011-08-27T16:10:52Z | [
"python",
"string",
"split"
] | I think what I want to do is a fairly common task but I've found no reference on the web. I have text, with punctuation, and I want list of the words.
```
"Hey, you - what are you doing here!?"
```
should be
```
['hey', 'you', 'what', 'are', 'you', 'doing', 'here']
```
But Python's `str.split()` only works with one... | Another quick way to do this without a regexp is to replace the characters first, as below:
```
>>> 'a;bcd,ef g'.replace(';',' ').replace(',',' ').split()
['a', 'bcd', 'ef', 'g']
``` |
Python - Split Strings with Multiple Delimiters | 1,059,559 | 334 | 2009-06-29T17:49:35Z | 12,189,710 | 29 | 2012-08-30T04:05:54Z | [
"python",
"string",
"split"
] | I think what I want to do is a fairly common task but I've found no reference on the web. I have text, with punctuation, and I want list of the words.
```
"Hey, you - what are you doing here!?"
```
should be
```
['hey', 'you', 'what', 'are', 'you', 'doing', 'here']
```
But Python's `str.split()` only works with one... | Pro-Tip: Use `string.translate` for the fastest string operations Python has.
Some proof...
First, the slow way (sorry pprzemek):
```
>>> import timeit
>>> S = 'Hey, you - what are you doing here!?'
>>> def my_split(s, seps):
... res = [s]
... for sep in seps:
... s, res = res, []
... for seq... |
Python - Split Strings with Multiple Delimiters | 1,059,559 | 334 | 2009-06-29T17:49:35Z | 23,720,594 | 96 | 2014-05-18T09:43:54Z | [
"python",
"string",
"split"
] | I think what I want to do is a fairly common task but I've found no reference on the web. I have text, with punctuation, and I want list of the words.
```
"Hey, you - what are you doing here!?"
```
should be
```
['hey', 'you', 'what', 'are', 'you', 'doing', 'here']
```
But Python's `str.split()` only works with one... | So many answers, yet I can't find any solution that does efficiently what the *title* of the questions literally asks for (splitting with multiple separatorsâinstead, many answers remove anything that is not a word). So here is an answer to the question in the title ("string split with multiple separators") that reli... |
Python Memory Model | 1,059,674 | 7 | 2009-06-29T18:12:55Z | 1,059,716 | 14 | 2009-06-29T18:23:07Z | [
"python",
"arrays",
"memory",
"model"
] | I have a very large list
Suppose I do that (yeah, I know the code is very unpythonic, but for the example's sake..):
```
n = (2**32)**2
for i in xrange(10**7)
li[i] = n
```
works fine. however:
```
for i in xrange(10**7)
li[i] = i**2
```
consumes a significantly larger amount of memory. I don't understand why t... | Java special-cases a few value types (including integers) so that they're stored by value (instead of, by object reference like everything else). Python doesn't special-case such types, so that assigning n to many entries *in a list* (or other normal Python container) doesn't have to make copies.
Edit: note that the r... |
Python Decorator 3.0 and arguments to the decorator | 1,060,193 | 5 | 2009-06-29T20:00:53Z | 1,060,244 | 7 | 2009-06-29T20:11:15Z | [
"python",
"decorator"
] | I'm excited to see the latest version of the `decorator` python module (3.0). It looks a lot cleaner (e.g. the syntax is more sugary than ever) than previous iterations.
However, it seems to have lousy support (e.g. "sour" syntax, to horribly stretch the metaphor) for decorators that take arguments themselves. Does an... | In this case, you need to make your function return the decorator. (Anything can be solved by another level of indirection...)
```
from decorator import decorator
def substitute_args(arg_sub_dict):
@decorator
def wrapper(fun, arg):
new_arg = arg_sub_dict.get(arg, arg)
return fun(new_arg)
return wrapper
`... |
Iterating through a range of dates in Python | 1,060,279 | 172 | 2009-06-29T20:16:02Z | 1,060,330 | 235 | 2009-06-29T20:27:14Z | [
"python",
"datetime",
"iteration"
] | I have the following code to do this, but how can I do it better? Right now I think it's better than nested loops, but it starts to get Perl-one-linerish when you have a generator in a list comprehension.
```
day_count = (end_date - start_date).days + 1
for single_date in [d for d in (start_date + timedelta(n) for n i... | Why are there two nested iterations? For me it produces the same list of data with only one iteration:
```
for single_date in (start_date + timedelta(n) for n in range(day_count)):
print ...
```
And no list gets stored, only one generator is iterated over. Also the "if" in the generator seems to be unnecessary.
... |
Iterating through a range of dates in Python | 1,060,279 | 172 | 2009-06-29T20:16:02Z | 1,060,352 | 99 | 2009-06-29T20:31:43Z | [
"python",
"datetime",
"iteration"
] | I have the following code to do this, but how can I do it better? Right now I think it's better than nested loops, but it starts to get Perl-one-linerish when you have a generator in a list comprehension.
```
day_count = (end_date - start_date).days + 1
for single_date in [d for d in (start_date + timedelta(n) for n i... | This might be more clear:
```
d = start_date
delta = datetime.timedelta(days=1)
while d <= end_date:
print d.strftime("%Y-%m-%d")
d += delta
``` |
Iterating through a range of dates in Python | 1,060,279 | 172 | 2009-06-29T20:16:02Z | 1,060,376 | 12 | 2009-06-29T20:35:13Z | [
"python",
"datetime",
"iteration"
] | I have the following code to do this, but how can I do it better? Right now I think it's better than nested loops, but it starts to get Perl-one-linerish when you have a generator in a list comprehension.
```
day_count = (end_date - start_date).days + 1
for single_date in [d for d in (start_date + timedelta(n) for n i... | ```
import datetime
def daterange(start, stop, step=datetime.timedelta(days=1), inclusive=False):
# inclusive=False to behave like range by default
if step.days > 0:
while start < stop:
yield start
start = start + step
# not +=! don't modify object passed in if it's mutable
# since this... |
Iterating through a range of dates in Python | 1,060,279 | 172 | 2009-06-29T20:16:02Z | 1,061,779 | 91 | 2009-06-30T04:49:37Z | [
"python",
"datetime",
"iteration"
] | I have the following code to do this, but how can I do it better? Right now I think it's better than nested loops, but it starts to get Perl-one-linerish when you have a generator in a list comprehension.
```
day_count = (end_date - start_date).days + 1
for single_date in [d for d in (start_date + timedelta(n) for n i... | Use the [`dateutil`](http://labix.org/python-dateutil) library:
```
from datetime import date
from dateutil.rrule import rrule, DAILY
a = date(2009, 5, 30)
b = date(2009, 6, 9)
for dt in rrule(DAILY, dtstart=a, until=b):
print dt.strftime("%Y-%m-%d")
```
This python library has many more advanced features, some... |
Iterating through a range of dates in Python | 1,060,279 | 172 | 2009-06-29T20:16:02Z | 15,969,361 | 8 | 2013-04-12T10:47:11Z | [
"python",
"datetime",
"iteration"
] | I have the following code to do this, but how can I do it better? Right now I think it's better than nested loops, but it starts to get Perl-one-linerish when you have a generator in a list comprehension.
```
day_count = (end_date - start_date).days + 1
for single_date in [d for d in (start_date + timedelta(n) for n i... | Why not try:
```
import datetime as dt
start_date = dt.datetime(2012, 12,1)
end_date = dt.datetime(2012, 12,5)
total_days = (end_date - start_date).days + 1 #inclusive 5 days
for day_number in range(total_days):
current_date = (start_date + dt.timedelta(days = day_number)).date()
print current_date
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.