title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags list |
|---|---|---|---|---|---|---|---|---|---|
python ORM allowing for table creation and bulk inserting? | 1,013,282 | <p>I'm looking for an ORM that allows me to do bulk inserts, as well as create code based on python classes. I tried sqlobject, it worked fine for creating the tables but inserting was unacceptibly slow for the amount of data I wanted to insert. If such an ORM doesn't exist any pointers on classes that can help with things like sanitizing input and building SQL strings would be appreciated.</p>
| 1 | 2009-06-18T15:16:00Z | 1,013,315 | <p>I believe sqlalchemy has bulk inserts, but I haven't ever used it. However, it stacks up favorably in benchmark tests according to this <a href="http://pyinsci.blogspot.com/2007/07/fastest-python-database-interface.html" rel="nofollow">this reviewer</a>.</p>
<p>EDIT: It doesn't seem clear how he's using SQLAlchemy...whether it's the actual ORM or just query code. Reading the blog entry, I assumed the point was to play with the ORM, but a few commentors seem to assume that he's using query-code and that if it were the ORM it would be much slower.</p>
| 0 | 2009-06-18T15:20:31Z | [
"python",
"database",
"orm"
] |
python ORM allowing for table creation and bulk inserting? | 1,013,282 | <p>I'm looking for an ORM that allows me to do bulk inserts, as well as create code based on python classes. I tried sqlobject, it worked fine for creating the tables but inserting was unacceptibly slow for the amount of data I wanted to insert. If such an ORM doesn't exist any pointers on classes that can help with things like sanitizing input and building SQL strings would be appreciated.</p>
| 1 | 2009-06-18T15:16:00Z | 1,016,006 | <p>I'm not familiar with sqlobject, but for bulk inserts typically you want to make sure this is done in a transaction, so your not commiting for each manipulation.</p>
<p>In sqlobject it looks like you can do this by using the transactions object to control commits. You probably need to turn of the default AutoCommit flag as well for this to function properly.</p>
<p><a href="http://www.sqlobject.org/SQLObject.html#id45" rel="nofollow">http://www.sqlobject.org/SQLObject.html#id45</a></p>
| 0 | 2009-06-19T01:31:10Z | [
"python",
"database",
"orm"
] |
Windows error and python | 1,013,311 | <p>I'm working on a bit of code that is supposed to run an exe file inside a folder on my system and getting an error saying... </p>
<p>WindowsError: [Error 3] The system cannot find the path specified.
Here's a bit of the code:</p>
<pre><code>exepath = os.path.join(EXE file localtion)
exepath = '"' + os.path.normpath(exepath) + '"'
cmd = [exepath, '-el', str(el), '-n', str(z)]
print 'The python program is running this command:'
print cmd
process = Popen(cmd, stderr=STDOUT, stdout=PIPE)
outputstring = process.communicate()[0]
</code></pre>
<p>I have imported subprocess and also from subprocess import *</p>
<p>For example, This is how my exe file location looks like in the first line of the code I show:</p>
<pre><code> exepath= os.path.join('/Program Files','next folder','next folder','blah.exe')
</code></pre>
<p>Am I missing something?</p>
| 1 | 2009-06-18T15:20:11Z | 1,013,342 | <p>If I remember correctly, you don't need to quote your executuable file path, like you do in the second line.</p>
<p>EDIT: Well, just grabbed nearby Windows box and tested this. Popen works the same regardless the path is quoted or not. So this is not an issue.</p>
| 0 | 2009-06-18T15:23:54Z | [
"python",
"popen"
] |
Windows error and python | 1,013,311 | <p>I'm working on a bit of code that is supposed to run an exe file inside a folder on my system and getting an error saying... </p>
<p>WindowsError: [Error 3] The system cannot find the path specified.
Here's a bit of the code:</p>
<pre><code>exepath = os.path.join(EXE file localtion)
exepath = '"' + os.path.normpath(exepath) + '"'
cmd = [exepath, '-el', str(el), '-n', str(z)]
print 'The python program is running this command:'
print cmd
process = Popen(cmd, stderr=STDOUT, stdout=PIPE)
outputstring = process.communicate()[0]
</code></pre>
<p>I have imported subprocess and also from subprocess import *</p>
<p>For example, This is how my exe file location looks like in the first line of the code I show:</p>
<pre><code> exepath= os.path.join('/Program Files','next folder','next folder','blah.exe')
</code></pre>
<p>Am I missing something?</p>
| 1 | 2009-06-18T15:20:11Z | 1,013,345 | <p>You need to properly escape the space in the executable path</p>
| 3 | 2009-06-18T15:24:27Z | [
"python",
"popen"
] |
Windows error and python | 1,013,311 | <p>I'm working on a bit of code that is supposed to run an exe file inside a folder on my system and getting an error saying... </p>
<p>WindowsError: [Error 3] The system cannot find the path specified.
Here's a bit of the code:</p>
<pre><code>exepath = os.path.join(EXE file localtion)
exepath = '"' + os.path.normpath(exepath) + '"'
cmd = [exepath, '-el', str(el), '-n', str(z)]
print 'The python program is running this command:'
print cmd
process = Popen(cmd, stderr=STDOUT, stdout=PIPE)
outputstring = process.communicate()[0]
</code></pre>
<p>I have imported subprocess and also from subprocess import *</p>
<p>For example, This is how my exe file location looks like in the first line of the code I show:</p>
<pre><code> exepath= os.path.join('/Program Files','next folder','next folder','blah.exe')
</code></pre>
<p>Am I missing something?</p>
| 1 | 2009-06-18T15:20:11Z | 1,013,364 | <p>AFAIK, there is no need to surround the path in quotation marks unless <code>cmd.exe</code> is involved in running the program.</p>
<p>In addition, you might want to use the environment variable <code>ProgramFiles</code> to find out the actual location of 'Program Files' because that depends on regional settings and can also be tweaked using TweakUI.</p>
| 0 | 2009-06-18T15:28:53Z | [
"python",
"popen"
] |
Windows error and python | 1,013,311 | <p>I'm working on a bit of code that is supposed to run an exe file inside a folder on my system and getting an error saying... </p>
<p>WindowsError: [Error 3] The system cannot find the path specified.
Here's a bit of the code:</p>
<pre><code>exepath = os.path.join(EXE file localtion)
exepath = '"' + os.path.normpath(exepath) + '"'
cmd = [exepath, '-el', str(el), '-n', str(z)]
print 'The python program is running this command:'
print cmd
process = Popen(cmd, stderr=STDOUT, stdout=PIPE)
outputstring = process.communicate()[0]
</code></pre>
<p>I have imported subprocess and also from subprocess import *</p>
<p>For example, This is how my exe file location looks like in the first line of the code I show:</p>
<pre><code> exepath= os.path.join('/Program Files','next folder','next folder','blah.exe')
</code></pre>
<p>Am I missing something?</p>
| 1 | 2009-06-18T15:20:11Z | 1,013,379 | <p>Besides properly escaping spaces and other characters that could cause problems (such as /), you can also use the 8 character old DOS paths. </p>
<p>For example, Program Files would be:</p>
<p>Progra~1 , making sure to append ~1 for the last two characters.</p>
<p>EDIT: You could add an r to the front of the string, making it a raw literal. Python would read the string character for character. Like this:</p>
<p>r " \Program files"</p>
| 1 | 2009-06-18T15:31:21Z | [
"python",
"popen"
] |
How to link C lib against python for embedding under Windows? | 1,013,441 | <p>I am working on an application written in C. One part of the application should embed python and there is my current problem. I try to link my source to the Python library but it does not work.</p>
<p>As I use MinGW I have created the python26.a file from python26.lib with dlltool and put the *.a file in <code>C:/Program Files (x86)/python/2.6/libs</code>.</p>
<p>Therefore, I compile the file with this command:</p>
<pre><code>gcc -shared -o mod_python.dll mod_python.o "-LC:\Program Files (x86)\python\2.6\libs" -lpython26 -Wl,--out-implib,libmod_python.a -Wl,--output-def,mod_python.def
</code></pre>
<p>and I get those errors:</p>
<pre><code>Creating library file: libmod_python.a
mod_python.o: In function `module_init':
mod_python.c:34: undefined reference to `__imp__Py_Initialize'
mod_python.c:35: undefined reference to `__imp__PyEval_InitThreads'
... and so on ...
</code></pre>
<ul>
<li>My Python "root" folder is <code>C:\Program Files (x86)\python\2.6</code></li>
<li>The Devsystem is a Windows Server 2008</li>
<li>GCC Information: <code>Reading specs from C:/Program Files (x86)/MinGW/bin/../lib/gcc/mingw32/3.4.5/specs
Configured with: ../gcc-3.4.5-20060117-3/configure --with-gcc --with-gnu-ld --with-gnu-as --host=mingw32 --target=mingw32 --prefix=/mingw --enable-threads --disable-nls --enable-languages=c,c++,f77,ada,objc,java --disable-win32-registry --disable-shared --enable-sjlj-exceptions --enable-libgcj --disable-java-awt --without-x --enable-java-gc=boehm --disable-libgcj-debug --enable-interpreter --enable-hash-synchronization --enable-libstdcxx-debug
Thread model: win32
gcc version 3.4.5 (mingw-vista special r3)</code></li>
</ul>
<p>What I do wrong? How I get it compiled and linked :-)?</p>
<p>Cheers, gregor</p>
<p><hr /></p>
<p><strong>Edit:</strong>
I forgot to write information about my Python installation: It's the official python.org installation 2.6.1</p>
<p>... and how I created the python.a file:</p>
<pre><code>dlltool -z python.def --export-all-symbols -v c:\windows\system32\python26.dll
dlltool --dllname c:\Windows\system32\python26.dll --def python.def -v --output-lib python26.a
</code></pre>
| 1 | 2009-06-18T15:39:16Z | 1,013,523 | <p>Python (at least my distribution) comes with a "python-config" program that automatically creates the correct compiler and linker options for various situations. However, I have never used it on Windows. Perhaps this tool can help you though?</p>
| 1 | 2009-06-18T15:54:45Z | [
"python",
"c",
"windows",
"gcc",
"linker"
] |
How to link C lib against python for embedding under Windows? | 1,013,441 | <p>I am working on an application written in C. One part of the application should embed python and there is my current problem. I try to link my source to the Python library but it does not work.</p>
<p>As I use MinGW I have created the python26.a file from python26.lib with dlltool and put the *.a file in <code>C:/Program Files (x86)/python/2.6/libs</code>.</p>
<p>Therefore, I compile the file with this command:</p>
<pre><code>gcc -shared -o mod_python.dll mod_python.o "-LC:\Program Files (x86)\python\2.6\libs" -lpython26 -Wl,--out-implib,libmod_python.a -Wl,--output-def,mod_python.def
</code></pre>
<p>and I get those errors:</p>
<pre><code>Creating library file: libmod_python.a
mod_python.o: In function `module_init':
mod_python.c:34: undefined reference to `__imp__Py_Initialize'
mod_python.c:35: undefined reference to `__imp__PyEval_InitThreads'
... and so on ...
</code></pre>
<ul>
<li>My Python "root" folder is <code>C:\Program Files (x86)\python\2.6</code></li>
<li>The Devsystem is a Windows Server 2008</li>
<li>GCC Information: <code>Reading specs from C:/Program Files (x86)/MinGW/bin/../lib/gcc/mingw32/3.4.5/specs
Configured with: ../gcc-3.4.5-20060117-3/configure --with-gcc --with-gnu-ld --with-gnu-as --host=mingw32 --target=mingw32 --prefix=/mingw --enable-threads --disable-nls --enable-languages=c,c++,f77,ada,objc,java --disable-win32-registry --disable-shared --enable-sjlj-exceptions --enable-libgcj --disable-java-awt --without-x --enable-java-gc=boehm --disable-libgcj-debug --enable-interpreter --enable-hash-synchronization --enable-libstdcxx-debug
Thread model: win32
gcc version 3.4.5 (mingw-vista special r3)</code></li>
</ul>
<p>What I do wrong? How I get it compiled and linked :-)?</p>
<p>Cheers, gregor</p>
<p><hr /></p>
<p><strong>Edit:</strong>
I forgot to write information about my Python installation: It's the official python.org installation 2.6.1</p>
<p>... and how I created the python.a file:</p>
<pre><code>dlltool -z python.def --export-all-symbols -v c:\windows\system32\python26.dll
dlltool --dllname c:\Windows\system32\python26.dll --def python.def -v --output-lib python26.a
</code></pre>
| 1 | 2009-06-18T15:39:16Z | 1,013,585 | <p>IIRC, dlltool does not always work. Having python 2.6 + Wow makes things even more less likely to work. For numpy, here is how I <a href="http://github.com/cournape/numpy/blob/a069480e25d79b76e6da96e951cd3ac66828d75d/numpy/distutils/mingw32ccompiler.py" rel="nofollow">did it</a>. Basically, I use obdump.exe to build the table from the dll, which I parse to generate the .def. You should check whether your missing symbols are in the .def, or otherwise it won't work.</p>
| 1 | 2009-06-18T16:05:02Z | [
"python",
"c",
"windows",
"gcc",
"linker"
] |
How to link C lib against python for embedding under Windows? | 1,013,441 | <p>I am working on an application written in C. One part of the application should embed python and there is my current problem. I try to link my source to the Python library but it does not work.</p>
<p>As I use MinGW I have created the python26.a file from python26.lib with dlltool and put the *.a file in <code>C:/Program Files (x86)/python/2.6/libs</code>.</p>
<p>Therefore, I compile the file with this command:</p>
<pre><code>gcc -shared -o mod_python.dll mod_python.o "-LC:\Program Files (x86)\python\2.6\libs" -lpython26 -Wl,--out-implib,libmod_python.a -Wl,--output-def,mod_python.def
</code></pre>
<p>and I get those errors:</p>
<pre><code>Creating library file: libmod_python.a
mod_python.o: In function `module_init':
mod_python.c:34: undefined reference to `__imp__Py_Initialize'
mod_python.c:35: undefined reference to `__imp__PyEval_InitThreads'
... and so on ...
</code></pre>
<ul>
<li>My Python "root" folder is <code>C:\Program Files (x86)\python\2.6</code></li>
<li>The Devsystem is a Windows Server 2008</li>
<li>GCC Information: <code>Reading specs from C:/Program Files (x86)/MinGW/bin/../lib/gcc/mingw32/3.4.5/specs
Configured with: ../gcc-3.4.5-20060117-3/configure --with-gcc --with-gnu-ld --with-gnu-as --host=mingw32 --target=mingw32 --prefix=/mingw --enable-threads --disable-nls --enable-languages=c,c++,f77,ada,objc,java --disable-win32-registry --disable-shared --enable-sjlj-exceptions --enable-libgcj --disable-java-awt --without-x --enable-java-gc=boehm --disable-libgcj-debug --enable-interpreter --enable-hash-synchronization --enable-libstdcxx-debug
Thread model: win32
gcc version 3.4.5 (mingw-vista special r3)</code></li>
</ul>
<p>What I do wrong? How I get it compiled and linked :-)?</p>
<p>Cheers, gregor</p>
<p><hr /></p>
<p><strong>Edit:</strong>
I forgot to write information about my Python installation: It's the official python.org installation 2.6.1</p>
<p>... and how I created the python.a file:</p>
<pre><code>dlltool -z python.def --export-all-symbols -v c:\windows\system32\python26.dll
dlltool --dllname c:\Windows\system32\python26.dll --def python.def -v --output-lib python26.a
</code></pre>
| 1 | 2009-06-18T15:39:16Z | 1,017,194 | <p>Well on Windows the python distribution comes already with a <code>libpython26.a</code> in the libs subdir so there is no need to generate <code>.a</code> files using dll tools.</p>
<p>I did try a little example with a single C file toto.c:</p>
<pre><code>gcc -shared -o ./toto.dll ./toto.c -I/Python26/include/ -L/Python26/libs -lpython26
</code></pre>
<p>And it works like a charm. Hope it will help :-)</p>
| 2 | 2009-06-19T09:53:03Z | [
"python",
"c",
"windows",
"gcc",
"linker"
] |
Combining C and Python functions in a module | 1,013,449 | <p>I have a C extension module, to which I would like to add some Python utility functions. Is there a recommended way of doing this?</p>
<p>For example:</p>
<pre><code>import my_module
my_module.super_fast_written_in_C()
my_module.written_in_Python__easy_to_maintain()
</code></pre>
<p>I'm primarily interested in Python 2.x.</p>
| 0 | 2009-06-18T15:41:00Z | 1,013,508 | <p>Prefix your native extension with an underscore.
Then, in Python, create a wrapper module that imports that native extension and adds some other non-native routines on top of that.</p>
| 5 | 2009-06-18T15:52:28Z | [
"python",
"cpython"
] |
Combining C and Python functions in a module | 1,013,449 | <p>I have a C extension module, to which I would like to add some Python utility functions. Is there a recommended way of doing this?</p>
<p>For example:</p>
<pre><code>import my_module
my_module.super_fast_written_in_C()
my_module.written_in_Python__easy_to_maintain()
</code></pre>
<p>I'm primarily interested in Python 2.x.</p>
| 0 | 2009-06-18T15:41:00Z | 1,013,556 | <p>The usual way of doing this is: mymod.py contains the utility functions written in Python, and imports the goodies in the _mymod module which is written in C and is imported from _mymod.so or _mymod.pyd. For example, look at .../Lib/csv.py in your Python distribution.</p>
| 6 | 2009-06-18T16:00:29Z | [
"python",
"cpython"
] |
Combining C and Python functions in a module | 1,013,449 | <p>I have a C extension module, to which I would like to add some Python utility functions. Is there a recommended way of doing this?</p>
<p>For example:</p>
<pre><code>import my_module
my_module.super_fast_written_in_C()
my_module.written_in_Python__easy_to_maintain()
</code></pre>
<p>I'm primarily interested in Python 2.x.</p>
| 0 | 2009-06-18T15:41:00Z | 1,015,935 | <p>The existing answers describe the method most often used: it has the potential advantage of allowing pure-Python (or other-language) implementations on platforms in which the compiled C extension is not available (including Jython and IronPython).</p>
<p>In a few cases, however, it may not be worth splitting the module into a C layer and a Python layer just to provide a few extras that are more sensibly written in Python than in C. For example, <a href="http://code.google.com/p/gmpy/source/browse/trunk/src/gmpy.c" rel="nofollow">gmpy</a> (lines 7113 ff at this time), in order to enable pickling of instances of <code>gmpy</code>'s type, uses:</p>
<pre><code>copy_reg_module = PyImport_ImportModule("copy_reg");
if (copy_reg_module) {
char* enable_pickle =
"def mpz_reducer(an_mpz): return (gmpy.mpz, (an_mpz.binary(), 256))\n"
"def mpq_reducer(an_mpq): return (gmpy.mpq, (an_mpq.binary(), 256))\n"
"def mpf_reducer(an_mpf): return (gmpy.mpf, (an_mpf.binary(), 0, 256))\n"
"copy_reg.pickle(type(gmpy.mpz(0)), mpz_reducer)\n"
"copy_reg.pickle(type(gmpy.mpq(0)), mpq_reducer)\n"
"copy_reg.pickle(type(gmpy.mpf(0)), mpf_reducer)\n"
;
PyObject* namespace = PyDict_New();
PyObject* result = NULL;
if (options.debug)
fprintf(stderr, "gmpy_module imported copy_reg OK\n");
PyDict_SetItemString(namespace, "copy_reg", copy_reg_module);
PyDict_SetItemString(namespace, "gmpy", gmpy_module);
PyDict_SetItemString(namespace, "type", (PyObject*)&PyType_Type);
result = PyRun_String(enable_pickle, Py_file_input,
namespace, namespace);
</code></pre>
<p>If you want those few extra functions to "stick around" in your module (not necessary in this example case), you would of course use your module object as built by <code>Py_InitModule3</code> (or whatever other method) and its <code>PyModule_GetDict</code> rather than a transient dictionary as the namespace in which to <code>PyRun_String</code>. And of course there are more sophisticated approaches than to <code>PyRun_String</code> the <code>def</code> and <code>class</code> statements you need, but, for simple enough cases, this simple approach may in fact be sufficient.</p>
| 1 | 2009-06-19T00:59:43Z | [
"python",
"cpython"
] |
Stealing wheelEvents from a QScrollArea | 1,013,670 | <p>I wanna put my custom widget in a QScrollArea, but in my custom widget, i reimplemented wheelEvent(e) and it never gets called. Im fine with the scroll area not having its mouse wheel scrolling functionality, I just need those wheelEvents to call my handler. I tried handling the events out at the level of the main window but I only got them when the scroll widget was at one of its extremes and couldn't have moved any further anyways, i need all of them.</p>
<p>heres a simplified version of my code</p>
<pre><code>class custom(QWidget):
def __init__(self, parent=None):
super(custom, self).__init__(parent)
self.parent = parent
def wheelEvent(self,event):
print "Custom Widget's wheelEvent Handler"
class mainw(QMainWindow):
def __init__(self, parent=None):
super(mainw, self).__init__(parent)
scroll = QScrollArea()
self.tw = thread_widget(scroll)
scroll.setWidget(self.tw)
self.setCentralWidget(scroll)
def wheelEvent(self,event):
print "Main Window's wheelEvent Handler"
</code></pre>
<p>can someone explain to me how it is determined which event handler gets the events in this situation?</p>
| 1 | 2009-06-18T16:20:34Z | 1,014,898 | <p>I figured out that its got something to do with the installEventFilter method of QObject, but I couldn't get the example to work so I said to hell with this and changed my plan completely.</p>
<p>problem solved</p>
| 0 | 2009-06-18T20:06:22Z | [
"python",
"pyqt"
] |
Stealing wheelEvents from a QScrollArea | 1,013,670 | <p>I wanna put my custom widget in a QScrollArea, but in my custom widget, i reimplemented wheelEvent(e) and it never gets called. Im fine with the scroll area not having its mouse wheel scrolling functionality, I just need those wheelEvents to call my handler. I tried handling the events out at the level of the main window but I only got them when the scroll widget was at one of its extremes and couldn't have moved any further anyways, i need all of them.</p>
<p>heres a simplified version of my code</p>
<pre><code>class custom(QWidget):
def __init__(self, parent=None):
super(custom, self).__init__(parent)
self.parent = parent
def wheelEvent(self,event):
print "Custom Widget's wheelEvent Handler"
class mainw(QMainWindow):
def __init__(self, parent=None):
super(mainw, self).__init__(parent)
scroll = QScrollArea()
self.tw = thread_widget(scroll)
scroll.setWidget(self.tw)
self.setCentralWidget(scroll)
def wheelEvent(self,event):
print "Main Window's wheelEvent Handler"
</code></pre>
<p>can someone explain to me how it is determined which event handler gets the events in this situation?</p>
| 1 | 2009-06-18T16:20:34Z | 19,917,798 | <p>You can install a eventFilter in your custom class</p>
<pre><code>class custom(QWidget):
def __init__(self, parent=None):
super(custom, self).__init__(parent)
self.parent = parent
self.installEventFilter(self)
def eventFilter(self, qobject, qevent):
qtype = qevent.type()
if qtype == QEvent.Wheel:
... wheel event logic
return True
# parents event handler for all other events
return super(custom,self).eventFilter(qobject, qevent)
</code></pre>
| 0 | 2013-11-11T23:09:18Z | [
"python",
"pyqt"
] |
After writing to a file, why does os.path.getsize still return the previous size? | 1,013,778 | <p>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.</p>
<p>What would be a good way to get the filesize of a file that is changing in size.</p>
<p>Ive done something like this...</p>
<pre><code>import string
import os
f1 = open('VSERVICE.xml', 'r')
f2 = open('split.xml', 'w')
for line in f1:
if str(line) == '</Service>\n':
break
else:
f2.write(line)
size = os.path.getsize('split.xml')
print('size = ' + str(size))
</code></pre>
<p>running this prints 0 as the filesize for about 80 iterations and then 4176. Does Python store the output in a buffer before actually outputting it?</p>
| 12 | 2009-06-18T16:38:24Z | 1,013,799 | <p>Yes, Python is buffering your output. You'd be better off tracking the size yourself, something like this:</p>
<pre><code>size = 0
for line in f1:
if str(line) == '</Service>\n':
break
else:
f2.write(line)
size += len(line)
print('size = ' + str(size))
</code></pre>
<p>(That might not be 100% accurate, eg. on Windows each line will gain a byte because of the <code>\r\n</code> line separator, but it should be good enough for simple chunking.)</p>
| 9 | 2009-06-18T16:41:16Z | [
"python",
"filesize"
] |
After writing to a file, why does os.path.getsize still return the previous size? | 1,013,778 | <p>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.</p>
<p>What would be a good way to get the filesize of a file that is changing in size.</p>
<p>Ive done something like this...</p>
<pre><code>import string
import os
f1 = open('VSERVICE.xml', 'r')
f2 = open('split.xml', 'w')
for line in f1:
if str(line) == '</Service>\n':
break
else:
f2.write(line)
size = os.path.getsize('split.xml')
print('size = ' + str(size))
</code></pre>
<p>running this prints 0 as the filesize for about 80 iterations and then 4176. Does Python store the output in a buffer before actually outputting it?</p>
| 12 | 2009-06-18T16:38:24Z | 1,014,653 | <p>Tracking the size yourself will be fine for your case. A different way would be to flush the file buffers just before you check the size:</p>
<pre><code>f2.write(line)
f2.flush() # <-- buffers are written to disk
size = os.path.getsize('split.xml')
</code></pre>
<p>Doing that too often will slow down file I/O, of course.</p>
| 3 | 2009-06-18T19:16:56Z | [
"python",
"filesize"
] |
After writing to a file, why does os.path.getsize still return the previous size? | 1,013,778 | <p>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.</p>
<p>What would be a good way to get the filesize of a file that is changing in size.</p>
<p>Ive done something like this...</p>
<pre><code>import string
import os
f1 = open('VSERVICE.xml', 'r')
f2 = open('split.xml', 'w')
for line in f1:
if str(line) == '</Service>\n':
break
else:
f2.write(line)
size = os.path.getsize('split.xml')
print('size = ' + str(size))
</code></pre>
<p>running this prints 0 as the filesize for about 80 iterations and then 4176. Does Python store the output in a buffer before actually outputting it?</p>
| 12 | 2009-06-18T16:38:24Z | 1,239,240 | <p>Have you tried to replace os.path.getsize with os.tell, like this:</p>
<pre><code>f2.write(line)
size = f2.tell()
</code></pre>
| 5 | 2009-08-06T14:26:27Z | [
"python",
"filesize"
] |
After writing to a file, why does os.path.getsize still return the previous size? | 1,013,778 | <p>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.</p>
<p>What would be a good way to get the filesize of a file that is changing in size.</p>
<p>Ive done something like this...</p>
<pre><code>import string
import os
f1 = open('VSERVICE.xml', 'r')
f2 = open('split.xml', 'w')
for line in f1:
if str(line) == '</Service>\n':
break
else:
f2.write(line)
size = os.path.getsize('split.xml')
print('size = ' + str(size))
</code></pre>
<p>running this prints 0 as the filesize for about 80 iterations and then 4176. Does Python store the output in a buffer before actually outputting it?</p>
| 12 | 2009-06-18T16:38:24Z | 5,821,833 | <p>File size is different from file position. For example,</p>
<pre><code>os.path.getsize('sample.txt')
</code></pre>
<p>It exactly returns file size in bytes. </p>
<p>But </p>
<pre><code>f = open('sample.txt')
print f.readline()
f.tell()
</code></pre>
<p>Here f.tell() returns the current position of the file handler - i.e. where the next write will put its data. Since it is aware of the buffering, it should be accurate as long as you are simply appending to the output file.</p>
| 11 | 2011-04-28T16:22:11Z | [
"python",
"filesize"
] |
After writing to a file, why does os.path.getsize still return the previous size? | 1,013,778 | <p>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.</p>
<p>What would be a good way to get the filesize of a file that is changing in size.</p>
<p>Ive done something like this...</p>
<pre><code>import string
import os
f1 = open('VSERVICE.xml', 'r')
f2 = open('split.xml', 'w')
for line in f1:
if str(line) == '</Service>\n':
break
else:
f2.write(line)
size = os.path.getsize('split.xml')
print('size = ' + str(size))
</code></pre>
<p>running this prints 0 as the filesize for about 80 iterations and then 4176. Does Python store the output in a buffer before actually outputting it?</p>
| 12 | 2009-06-18T16:38:24Z | 8,268,816 | <p>To find the offset to the end of a file:</p>
<pre><code>file.seek(0,2)
print file.tell()
</code></pre>
<p>Real world example - read updates to a file and print them as they happen:</p>
<pre><code>file = open('log.txt', 'r')
#find inital End Of File offset
file.seek(0,2)
eof = file.tell()
while True:
#set the file size agian
file.seek(0,2)
neweof = file.tell()
#if the file is larger...
if neweof > eof:
#go back to last position...
file.seek(eof)
# print from last postion to current one
print file.read(neweof-eof),
eof = neweof
</code></pre>
| 1 | 2011-11-25T11:58:43Z | [
"python",
"filesize"
] |
How to write a Perl, Python, or Ruby program to change the memory of another process on Windows? | 1,013,828 | <p>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 <a href="http://www.cheatengine.org/">Cheat Engine</a>, which can do something like that on Windows.</p>
| 8 | 2009-06-18T16:45:46Z | 1,013,870 | <p>I initially thought this was not possible but after seeing Brian's comment, I searched CPAN and lo and behold, there is <a href="http://search.cpan.org/perldoc/Win32%3a%3aProcess%3a%3aMemory">Win32::Process::Memory</a>:</p>
<pre><code>C:\> ppm install Win32::Process::Info
C:\> ppm install Win32::Process::Memory
</code></pre>
<p>The module apparently uses the <a href="http://msdn.microsoft.com/en-us/library/ms680553.aspx"><code>ReadProcessMemory</code></a> function: Here is one of my attempts:</p>
<pre><code>#!/usr/bin/perl
use strict; use warnings;
use Win32;
use Win32::Process;
use Win32::Process::Memory;
my $process;
Win32::Process::Create(
$process,
'C:/opt/vim/vim72/gvim.exe',
q{},
0,
NORMAL_PRIORITY_CLASS,
q{.}
) or die ErrorReport();
my $mem = Win32::Process::Memory->new({
pid => $process->GetProcessID(),
access => 'read/query',
});
$mem->search_sub( 'VIM', sub {
print $mem->hexdump($_[0], 0x20), "\n";
});
sub ErrorReport{
Win32::FormatMessage( Win32::GetLastError() );
}
END { $process->Kill(0) if $process }
</code></pre>
<p>Output:</p>
<pre><code>C:\Temp> proc
0052A580 : 56 49 4D 20 2D 20 56 69 20 49 4D 70 72 6F 76 65 : VIM - Vi IMprove
0052A590 : 64 20 37 2E 32 20 28 32 30 30 38 20 41 75 67 20 : d 7.2 (2008 Aug
0052A5F0 : 56 49 4D 52 55 4E 54 49 4D 45 3A 20 22 00 : VIMRUNTIME: ".
0052A600 : 20 20 66 61 6C 6C 2D 62 61 63 6B 20 66 6F 72 20 : fall-back for
0052A610 : 24 56 : $V
</code></pre>
| 13 | 2009-06-18T16:52:57Z | [
"python",
"ruby",
"perl",
"winapi",
"readprocessmemory"
] |
How to write a Perl, Python, or Ruby program to change the memory of another process on Windows? | 1,013,828 | <p>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 <a href="http://www.cheatengine.org/">Cheat Engine</a>, which can do something like that on Windows.</p>
| 8 | 2009-06-18T16:45:46Z | 1,013,905 | <p>There are ways to do do this using Process injection, delay load library etc. </p>
<p>I don't see you doing it from the tools you have listed. This is C and assembler country and beginning to get you into virus writing territory. Once you get it to work, any anti-virus packages will veto it running and try and isolate it. So you better really want to do this. </p>
<p>"With power comes much ...."</p>
<p>Good luck</p>
| 4 | 2009-06-18T16:59:45Z | [
"python",
"ruby",
"perl",
"winapi",
"readprocessmemory"
] |
How to write a Perl, Python, or Ruby program to change the memory of another process on Windows? | 1,013,828 | <p>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 <a href="http://www.cheatengine.org/">Cheat Engine</a>, which can do something like that on Windows.</p>
| 8 | 2009-06-18T16:45:46Z | 1,013,941 | <p>Well, the fun part is getting access to the other process's memory. CheatEngine does it by running your entire OS under a virtual machine that allows memory protection to be defeated. There's also the 'running under a debugger' model, generally meaning start the target application as a child process of the modifying application, with elevated privileges. See the <a href="http://msdn.microsoft.com/en-us/library/ms684880%28VS.85%29.aspx" rel="nofollow">Win32 API</a> for lots of fun stuff about that.</p>
<p>In Perl, once you had the requisite access, you'd probably want to interact with it using <a href="http://search.cpan.org/~teverett/Win32-Security-0.50/lib/Win32/Security/Raw.pm" rel="nofollow">Win32::Security::Raw</a>.</p>
| 6 | 2009-06-18T17:07:15Z | [
"python",
"ruby",
"perl",
"winapi",
"readprocessmemory"
] |
How to write a Perl, Python, or Ruby program to change the memory of another process on Windows? | 1,013,828 | <p>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 <a href="http://www.cheatengine.org/">Cheat Engine</a>, which can do something like that on Windows.</p>
| 8 | 2009-06-18T16:45:46Z | 1,014,468 | <p>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-level language, since in higher level ones you'll have to be concerned with how to translate highlevel datatypes to lower ones etc.</p>
<p>Start by calling <a href="http://msdn.microsoft.com/en-us/library/ms684320(VS.85).aspx">OpenProcess</a> on the process to debug, with the appropriate access requested (you'll need to be an Admin on the machine / have fairly high privileges to gain access). You should then be able to call functions like <a href="http://msdn.microsoft.com/en-us/library/ms680553(VS.85).aspx">ReadProcessMemory</a> and <a href="http://msdn.microsoft.com/en-us/library/ms681674(VS.85).aspx">WriteProcessMemory</a> to read from and write to that process's memory.</p>
<p><strong>[Edit]</strong> Here's a quick python proof of concept of a function that successfully reads memory from another process's address space:</p>
<pre><code>import ctypes
import ctypes.wintypes
kernel32 = ctypes.wintypes.windll.kernel32
# Various access flag definitions:
class Access:
DELETE = 0x00010000
READ_CONTROL= 0x00020000
SYNCHRONIZE = 0x00100000
WRITE_DAC = 0x00040000
WRITE_OWNER = 0x00080000
PROCESS_VM_WRITE = 0x0020
PROCESS_VM_READ = 0x0010
PROCESS_VM_OPERATION = 0x0008
PROCESS_TERMINATE = 0x0001
PROCESS_SUSPEND_RESUME = 0x0800
PROCESS_SET_QUOTA = 0x0100
PROCESS_SET_INFORMATION = 0x0200
PROCESS_QUERY_LIMITED_INFORMATION = 0x1000
PROCESS_QUERY_INFORMATION = 0x0400
PROCESS_DUP_HANDLE = 0x0040
PROCESS_CREATE_THREAD = 0x0002
PROCESS_CREATE_PROCESS = 0x0080
def read_process_mem(pid, address, size):
"""Read memory of the specified process ID."""
buf = ctypes.create_string_buffer(size)
gotBytes = ctypes.c_ulong(0)
h = kernel32.OpenProcess(Access.PROCESS_VM_READ, False, pid)
try:
if kernel32.ReadProcessMemory(h, address, buf, size, ctypes.byref(gotBytes)):
return buf
else:
# TODO: report appropriate error GetLastError
raise Exception("Failed to access process memory.")
finally:
kernel32.CloseHandle(h)
</code></pre>
<p>Note that you'll need to determine where in memory to look for things - most of that address space is going to be unmapped, thought there are some standard offsets to look for things like the program code, dlls etc.</p>
| 8 | 2009-06-18T18:42:44Z | [
"python",
"ruby",
"perl",
"winapi",
"readprocessmemory"
] |
How to write a Perl, Python, or Ruby program to change the memory of another process on Windows? | 1,013,828 | <p>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 <a href="http://www.cheatengine.org/">Cheat Engine</a>, which can do something like that on Windows.</p>
| 8 | 2009-06-18T16:45:46Z | 1,216,456 | <p>It is possible to implement the entire process in one of the languages listed but a compiled language would be better for memory scanning (speed considerations if nothing else). There is a dll (with source) called SigScan available that, while tailored for a specific game, could probably be modified to suite your needs with minimal effort. </p>
<p>Building on Brian's correct answer here's a quick and dirty example of using a dll to get your address from within python.
This is, of course, specific to the DLLs implementation.
"Module name" would generally be the dll name as displayed in Cheat Engines "Enumerate DLLs and Symbols" dialog.</p>
<p>With Brian's example as a guideline and <a href="http://msdn.microsoft.com/en-us/library/ms681674%28VS.85%29.aspx" rel="nofollow" title="MSDN">MSDN</a> you could easily extend this with your own WriteProcessMemory method. </p>
<pre><code>import win32defines
import win32process
import win32gui
from ctypes import *
SigScan = cdll.SigScan
kernel32 = windll.kernel32
addresses = {"Value1" : {"sigArg1" : "b0015ec390518b4c24088d4424005068",
"sigArg2" : 36,
"address" : None,
"size" : 32
},
"Value2" :{"sigArg1" : "3b05XXXXXXXX741285c0",
"sigArg2" : None,
"address" : None,
"size" : 32
}
}
def read_process_mem(pid, address, size):
"""Read memory of the specified process ID."""
buf = create_string_buffer(size)
gotBytes = c_ulong(0)
h = kernel32.OpenProcess(win32defines.PROCESS_VM_READ, False, pid)
try:
if kernel32.ReadProcessMemory(h, address, buf, size, byref(gotBytes)):
return buf
else:
# TODO: report appropriate error GetLastError
raise Exception("Failed to access process memory.")
finally:
kernel32.CloseHandle(h)
if __name__ == "__main__":
pid, id = None, None
## HWND
hwnd = win32gui.FindWindowEx(0, 0, 0, "Window Name here")
## pid
pid = win32process.GetWindowThreadProcessId(hwnd)[-1]
## Initialize the sigscan dll
SigScan.InitializeSigScan(pid, "Module Name")
## Find all the addresses registered
for key in addresses.keys():
addresses[key]["address"] = SigScan.SigScan(addresses[key]["sigArg1"],
addresses[key]["sigArg2"])
## Allow the scanner to clean up
SigScan.FinalizeSigScan()
for key in addresses.keys():
if addresses[key]["address"] != None:
print repr(read_process_mem(pid, addresses[key]["address"],
addresses[key]["size"]).raw)</code></pre>
| 0 | 2009-08-01T11:49:49Z | [
"python",
"ruby",
"perl",
"winapi",
"readprocessmemory"
] |
What Can A 'TreeDict' (Or Treemap) Be Used For In Practice? | 1,014,247 | <p>I'm developing a 'TreeDict' class in Python. This is a basically a dict that allows you to retrieve its key-value pairs in sorted order, just like the Treemap collection class in Java.</p>
<p>I've implemented some functionality based on the way unique indexes in relational databases can be used, e.g. functions to let you retrieve values corresponding to a range of keys, keys greater than, less than or equal to a particular value in sorted order, strings or tuples that have a specific prefix in sorted order, etc.</p>
<p>Unfortunately, I can't think of any real life problem that will require a class like this. I suspect that the reason we don't have sorted dicts in Python is that in practice they aren't required often enough to be worth it, but I want to be proved wrong. </p>
<p>Can you think of any specific applications of a 'TreeDict'? Any real life problem that would be best solved by this data structure? I just want to know for sure whether this is worth it.</p>
| 2 | 2009-06-18T17:59:25Z | 1,014,274 | <p>I often use <code>Dict<DateTime, someClassOrValue></code> when working with industrial process data--
Valve open/close, machinery start/stop, etc.</p>
<p>Having the keys sorted is especially useful when I need to compare time intervals between start/stop or open/close events in a decent amount of time.</p>
<p>However, since I've been able to use linq in C# I've found that it's often easier to just work with IEnumerables and use the IQueryable extension methods to get the information I need.</p>
| 1 | 2009-06-18T18:06:45Z | [
"python",
"collections",
"dictionary",
"treemap",
"uses"
] |
What Can A 'TreeDict' (Or Treemap) Be Used For In Practice? | 1,014,247 | <p>I'm developing a 'TreeDict' class in Python. This is a basically a dict that allows you to retrieve its key-value pairs in sorted order, just like the Treemap collection class in Java.</p>
<p>I've implemented some functionality based on the way unique indexes in relational databases can be used, e.g. functions to let you retrieve values corresponding to a range of keys, keys greater than, less than or equal to a particular value in sorted order, strings or tuples that have a specific prefix in sorted order, etc.</p>
<p>Unfortunately, I can't think of any real life problem that will require a class like this. I suspect that the reason we don't have sorted dicts in Python is that in practice they aren't required often enough to be worth it, but I want to be proved wrong. </p>
<p>Can you think of any specific applications of a 'TreeDict'? Any real life problem that would be best solved by this data structure? I just want to know for sure whether this is worth it.</p>
| 2 | 2009-06-18T17:59:25Z | 1,014,281 | <p>The reason for keeping the elements in sorted order is for faster retrieval. Say I wanted all of the values in the dictionary in a sorted range. This is much faster with a TreeDict then with the regular hashmap. It basically allows you to keep everything in the dictionary in sorted order. I know in the application I'm currently working on uses a class like this to basically query the data structure.</p>
| 2 | 2009-06-18T18:08:03Z | [
"python",
"collections",
"dictionary",
"treemap",
"uses"
] |
What Can A 'TreeDict' (Or Treemap) Be Used For In Practice? | 1,014,247 | <p>I'm developing a 'TreeDict' class in Python. This is a basically a dict that allows you to retrieve its key-value pairs in sorted order, just like the Treemap collection class in Java.</p>
<p>I've implemented some functionality based on the way unique indexes in relational databases can be used, e.g. functions to let you retrieve values corresponding to a range of keys, keys greater than, less than or equal to a particular value in sorted order, strings or tuples that have a specific prefix in sorted order, etc.</p>
<p>Unfortunately, I can't think of any real life problem that will require a class like this. I suspect that the reason we don't have sorted dicts in Python is that in practice they aren't required often enough to be worth it, but I want to be proved wrong. </p>
<p>Can you think of any specific applications of a 'TreeDict'? Any real life problem that would be best solved by this data structure? I just want to know for sure whether this is worth it.</p>
| 2 | 2009-06-18T17:59:25Z | 1,014,282 | <p>They can make various algorithms easier to implement.</p>
| 0 | 2009-06-18T18:08:11Z | [
"python",
"collections",
"dictionary",
"treemap",
"uses"
] |
What Can A 'TreeDict' (Or Treemap) Be Used For In Practice? | 1,014,247 | <p>I'm developing a 'TreeDict' class in Python. This is a basically a dict that allows you to retrieve its key-value pairs in sorted order, just like the Treemap collection class in Java.</p>
<p>I've implemented some functionality based on the way unique indexes in relational databases can be used, e.g. functions to let you retrieve values corresponding to a range of keys, keys greater than, less than or equal to a particular value in sorted order, strings or tuples that have a specific prefix in sorted order, etc.</p>
<p>Unfortunately, I can't think of any real life problem that will require a class like this. I suspect that the reason we don't have sorted dicts in Python is that in practice they aren't required often enough to be worth it, but I want to be proved wrong. </p>
<p>Can you think of any specific applications of a 'TreeDict'? Any real life problem that would be best solved by this data structure? I just want to know for sure whether this is worth it.</p>
| 2 | 2009-06-18T17:59:25Z | 1,014,401 | <p>Almost all "GROUP BY" reporting requires a sorted dictionary.</p>
<pre><code>summary = sortedDefaultDict()
for row in somePileOfData:
summary[row.group_by] += row.balance
for k in sorted(summary.keys()):
print k, summary[k]
</code></pre>
<p>This is done so often in data warehousing applications, that it's difficult to express how central this is.</p>
<p>If the <code>sorted</code> function call does no work, it saves a ton of time in the long run.</p>
| 1 | 2009-06-18T18:31:13Z | [
"python",
"collections",
"dictionary",
"treemap",
"uses"
] |
What Can A 'TreeDict' (Or Treemap) Be Used For In Practice? | 1,014,247 | <p>I'm developing a 'TreeDict' class in Python. This is a basically a dict that allows you to retrieve its key-value pairs in sorted order, just like the Treemap collection class in Java.</p>
<p>I've implemented some functionality based on the way unique indexes in relational databases can be used, e.g. functions to let you retrieve values corresponding to a range of keys, keys greater than, less than or equal to a particular value in sorted order, strings or tuples that have a specific prefix in sorted order, etc.</p>
<p>Unfortunately, I can't think of any real life problem that will require a class like this. I suspect that the reason we don't have sorted dicts in Python is that in practice they aren't required often enough to be worth it, but I want to be proved wrong. </p>
<p>Can you think of any specific applications of a 'TreeDict'? Any real life problem that would be best solved by this data structure? I just want to know for sure whether this is worth it.</p>
| 2 | 2009-06-18T17:59:25Z | 1,014,601 | <p>It's useful when you need to go through a Dictionary in order of the keys; which comes up on occasion. I've actually found its infinitely more common in certain programming contests then anything else (think ACM, etc).</p>
<p>The most useful feature of a TreeMap is when you want to quickly find the min or max key; using a sorted dictionary this is often a single method call; and algorithmically can be done in O(log(n)) time, as opposed to iterating over each key looking for a min/max if the collection is unsorted. Basically, a much friendlier interface.</p>
<p>One of the more common times I run into it is when objects are identified by a specific name, and you want to print out the objects ordered according to the name; say a mapping from directory name to number of files in a directory.</p>
<p>One other place I've used it is in an excel spreadsheet wrapper; mapping from row number to row object. This lets you quickly find the last row index, without looping through each row.</p>
<p>Also, it's useful when you can easily define a comparison relation on keys, but not necessarily a hashing function, as needed for HashMaps. The best (though weak) example I can think of is case insensitive string keys.</p>
| 2 | 2009-06-18T19:04:30Z | [
"python",
"collections",
"dictionary",
"treemap",
"uses"
] |
What Can A 'TreeDict' (Or Treemap) Be Used For In Practice? | 1,014,247 | <p>I'm developing a 'TreeDict' class in Python. This is a basically a dict that allows you to retrieve its key-value pairs in sorted order, just like the Treemap collection class in Java.</p>
<p>I've implemented some functionality based on the way unique indexes in relational databases can be used, e.g. functions to let you retrieve values corresponding to a range of keys, keys greater than, less than or equal to a particular value in sorted order, strings or tuples that have a specific prefix in sorted order, etc.</p>
<p>Unfortunately, I can't think of any real life problem that will require a class like this. I suspect that the reason we don't have sorted dicts in Python is that in practice they aren't required often enough to be worth it, but I want to be proved wrong. </p>
<p>Can you think of any specific applications of a 'TreeDict'? Any real life problem that would be best solved by this data structure? I just want to know for sure whether this is worth it.</p>
| 2 | 2009-06-18T17:59:25Z | 1,015,901 | <p>I've seen several answers pointing to the "walk in ordered sequence" feature, which is indeed important, but none highlighting the other big feature, which is "find first entry with a key >= this". This has many uses even when there's no real need to "walk" from there.</p>
<p>For example (this came up in a recent SO answer), say you want to generate pseudo-random values with given relative frequencies -- i.e, you're given, say, a dict <code>d</code>:</p>
<pre><code>{'wolf': 42, 'sheep': 15, 'dog': 23, 'goat': 15, 'cat': 5}
</code></pre>
<p>and need a way to generate 'wolf' with a probability of 42 out of 100 (since 100 is the total of the relative frequencies given), 'sheep' 15 out of 100, and so on; and the number of distinct values can be quite large, as can the relative frequencies.</p>
<p>Then, store the given values (in whatever order) as the values in a tree map, with the corresponding keys being the "total cumulative frequency" up to that point. I.e.:</p>
<pre><code>def preprocess(d):
tot = 0
for v in d:
tot += d[v]
treemap.insert(key=tot, value=v)
return tot, treemap
</code></pre>
<p>Now, generating a value can be pretty fast (<code>O(log(len(d)))</code>), as follows:</p>
<pre><code>def generate(tot, treemap, r=random):
n = r.randrange(tot)
return treemap.firstGTkey(n).value
</code></pre>
<p>where <code>firstGTKey</code> is a method that returns the first entry (with <code>.key</code> and <code>.value</code> attributes, in this hypothetical example) with a key > the given argument. I've used this approach with large files stored as B-Trees, for example (using e.g. <code>bsddb.bt_open</code> and the <code>set_location</code> method).</p>
| 5 | 2009-06-19T00:38:22Z | [
"python",
"collections",
"dictionary",
"treemap",
"uses"
] |
What Can A 'TreeDict' (Or Treemap) Be Used For In Practice? | 1,014,247 | <p>I'm developing a 'TreeDict' class in Python. This is a basically a dict that allows you to retrieve its key-value pairs in sorted order, just like the Treemap collection class in Java.</p>
<p>I've implemented some functionality based on the way unique indexes in relational databases can be used, e.g. functions to let you retrieve values corresponding to a range of keys, keys greater than, less than or equal to a particular value in sorted order, strings or tuples that have a specific prefix in sorted order, etc.</p>
<p>Unfortunately, I can't think of any real life problem that will require a class like this. I suspect that the reason we don't have sorted dicts in Python is that in practice they aren't required often enough to be worth it, but I want to be proved wrong. </p>
<p>Can you think of any specific applications of a 'TreeDict'? Any real life problem that would be best solved by this data structure? I just want to know for sure whether this is worth it.</p>
| 2 | 2009-06-18T17:59:25Z | 2,613,165 | <p>Have you seen that: <a href="http://code.activestate.com/recipes/576998/" rel="nofollow">http://code.activestate.com/recipes/576998/</a> ?</p>
<p>zuo</p>
| 1 | 2010-04-10T11:17:33Z | [
"python",
"collections",
"dictionary",
"treemap",
"uses"
] |
How do I convert a nested tuple of tuples and lists to lists of lists in Python? | 1,014,352 | <p>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 <code>(1,2,[3,(4,5)])</code> to <code>[1,2,[3,[4,5]]]</code>.</p>
<p>How do I do this (in Python)?</p>
| 2 | 2009-06-18T18:20:54Z | 1,014,499 | <p>As a python newbie I would try this</p>
<pre><code>def f(t):
if type(t) == list or type(t) == tuple:
return [f(i) for i in t]
return t
t = (1,2,[3,(4,5)])
f(t)
>>> [1, 2, [3, [4, 5]]]
</code></pre>
<p>Or, if you like one liners:</p>
<pre><code>def f(t):
return [f(i) for i in t] if isinstance(t, (list, tuple)) else t
</code></pre>
| 6 | 2009-06-18T18:48:36Z | [
"python",
"list",
"tuples"
] |
How do I convert a nested tuple of tuples and lists to lists of lists in Python? | 1,014,352 | <p>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 <code>(1,2,[3,(4,5)])</code> to <code>[1,2,[3,[4,5]]]</code>.</p>
<p>How do I do this (in Python)?</p>
| 2 | 2009-06-18T18:20:54Z | 1,014,669 | <pre><code>def listit(t):
    return list(map(listit, t)) if isinstance(t, (list, tuple)) else t
</code></pre>
<p>The shortest solution I can imagine.</p>
| 12 | 2009-06-18T19:19:02Z | [
"python",
"list",
"tuples"
] |
How do I convert a nested tuple of tuples and lists to lists of lists in Python? | 1,014,352 | <p>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 <code>(1,2,[3,(4,5)])</code> to <code>[1,2,[3,[4,5]]]</code>.</p>
<p>How do I do this (in Python)?</p>
| 2 | 2009-06-18T18:20:54Z | 1,210,288 | <p>This is what I had come up with, but I like the other's better.</p>
<pre><code>def deep_list(x):
"""fully copies trees of tuples or lists to a tree of lists.
deep_list( (1,2,(3,4)) ) returns [1,2,[3,4]]
deep_list( (1,2,[3,(4,5)]) ) returns [1,2,[3,[4,5]]]"""
if not ( type(x) == type( () ) or type(x) == type( [] ) ):
return x
return map(deep_list,x)
</code></pre>
<p>I see <a href="http://stackoverflow.com/users/75280/aztek">aztek</a>'s answer can be shortened to:</p>
<pre><code>def deep_list(x):
return map(deep_list, x) if isinstance(x, (list, tuple)) else x
</code></pre>
<p><strong>Update</strong>: But now I see from <a href="http://stackoverflow.com/users/114920/dasich">DasIch</a>'s comment that this wouldn't work in Python 3.x since map() there returns a generator.</p>
| 0 | 2009-07-31T01:50:40Z | [
"python",
"list",
"tuples"
] |
How do I convert a nested tuple of tuples and lists to lists of lists in Python? | 1,014,352 | <p>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 <code>(1,2,[3,(4,5)])</code> to <code>[1,2,[3,[4,5]]]</code>.</p>
<p>How do I do this (in Python)?</p>
| 2 | 2009-06-18T18:20:54Z | 36,307,987 | <p>We can (ab)use the fact that <code>json.loads</code> always produces Python lists for JSON lists, while <code>json.dumps</code> turns any Python collection into a JSON list:</p>
<pre><code>import json
def nested_list(nested_collection):
return json.loads(json.dumps(nested_collection))
</code></pre>
| 0 | 2016-03-30T11:50:23Z | [
"python",
"list",
"tuples"
] |
What does : TypeError: cannot concatenate 'str' and 'list' objects mean? | 1,014,503 | <p>What does this error mean?</p>
<blockquote>
<p>TypeError: cannot concatenate 'str' and 'list' objects</p>
</blockquote>
<p>Here's part of the code:</p>
<pre><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.path.join(exe file location here)
exepath = '"' + os.path.normpath(exepath) + '"'
cmd = [exepath + '-j' + str(j) + '-n' + str(z)]
process=Popen('echo ' + cmd, shell=True, stderr=STDOUT )
print process
</code></pre>
| 8 | 2009-06-18T18:49:36Z | 1,014,519 | <p>string objects can only be concatenated with other strings. Python is a strongly-typed language. It will not coerce types for you.</p>
<p>you can do: </p>
<pre><code>'a' + '1'
</code></pre>
<p>but not: </p>
<pre><code>'a' + 1
</code></pre>
<p>in your case, you are trying to concat a string and a list. this won't work. you can append the item to the list though, if that is your desired result:</p>
<pre><code>my_list.append('a')
</code></pre>
| 3 | 2009-06-18T18:52:10Z | [
"python",
"string"
] |
What does : TypeError: cannot concatenate 'str' and 'list' objects mean? | 1,014,503 | <p>What does this error mean?</p>
<blockquote>
<p>TypeError: cannot concatenate 'str' and 'list' objects</p>
</blockquote>
<p>Here's part of the code:</p>
<pre><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.path.join(exe file location here)
exepath = '"' + os.path.normpath(exepath) + '"'
cmd = [exepath + '-j' + str(j) + '-n' + str(z)]
process=Popen('echo ' + cmd, shell=True, stderr=STDOUT )
print process
</code></pre>
| 8 | 2009-06-18T18:49:36Z | 1,014,596 | <p>I'm not sure you're aware that <code>cmd</code> is a one-element <code>list</code>, and not a string.</p>
<p>Changing that line to the below would construct a string, and the rest of your code will work:</p>
<pre><code># Just removing the square brackets
cmd = exepath + '-j' + str(j) + '-n' + str(z)
</code></pre>
<p>I assume you used brackets just to group the operations. That's not necessary if everything is on one line. If you wanted to break it up over two lines, you should use parentheses, not brackets:</p>
<pre><code># This returns a one-element list
cmd = [exepath + '-j' + str(j) +
'-n' + str(z)]
# This returns a string
cmd = (exepath + '-j' + str(j) +
'-n' + str(z))
</code></pre>
<p>Anything between square brackets in python is <em>always</em> a <code>list</code>. Expressions between parentheses are evaluated as normal, unless there is a comma in the expression, in which case the parentheses act as a <code>tuple</code> constructor:</p>
<pre><code># This is a string
str = ("I'm a string")
# This is a tuple
tup = ("I'm a string","me too")
# This is also a (one-element) tuple
tup = ("I'm a string",)
</code></pre>
| 11 | 2009-06-18T19:03:32Z | [
"python",
"string"
] |
What does : TypeError: cannot concatenate 'str' and 'list' objects mean? | 1,014,503 | <p>What does this error mean?</p>
<blockquote>
<p>TypeError: cannot concatenate 'str' and 'list' objects</p>
</blockquote>
<p>Here's part of the code:</p>
<pre><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.path.join(exe file location here)
exepath = '"' + os.path.normpath(exepath) + '"'
cmd = [exepath + '-j' + str(j) + '-n' + str(z)]
process=Popen('echo ' + cmd, shell=True, stderr=STDOUT )
print process
</code></pre>
| 8 | 2009-06-18T18:49:36Z | 1,015,817 | <p>There is ANOTHER problem in the OP's code:</p>
<p><code>z = ('0.')</code> then later <code>for k in z:</code></p>
<p>The parentheses in the first statement will be ignored, leading to the second statement binding <code>k</code> first to <code>'0'</code> and then <code>'.'</code> ... looks like <code>z = ('0.', )</code> was intended.</p>
| 2 | 2009-06-19T00:02:54Z | [
"python",
"string"
] |
Simple syntax for bringing a list element to the front in python? | 1,014,523 | <p>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?</p>
<p>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 could do.</p>
<pre><code> mylist = sorted(mylist,
key=lambda x: x == targetvalue,
reverse=True)
</code></pre>
<p>Cheers,
/YGA</p>
| 17 | 2009-06-18T18:52:58Z | 1,014,533 | <p>To bring (for example) the 5th element to the front, use:</p>
<pre><code>mylist.insert(0, mylist.pop(5))
</code></pre>
| 19 | 2009-06-18T18:55:17Z | [
"python"
] |
Simple syntax for bringing a list element to the front in python? | 1,014,523 | <p>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?</p>
<p>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 could do.</p>
<pre><code> mylist = sorted(mylist,
key=lambda x: x == targetvalue,
reverse=True)
</code></pre>
<p>Cheers,
/YGA</p>
| 17 | 2009-06-18T18:52:58Z | 1,014,544 | <p>I would go with:</p>
<pre><code>mylist.insert(0, mylist.pop(mylist.index(targetvalue)))
</code></pre>
| 41 | 2009-06-18T18:57:35Z | [
"python"
] |
Simple syntax for bringing a list element to the front in python? | 1,014,523 | <p>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?</p>
<p>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 could do.</p>
<pre><code> mylist = sorted(mylist,
key=lambda x: x == targetvalue,
reverse=True)
</code></pre>
<p>Cheers,
/YGA</p>
| 17 | 2009-06-18T18:52:58Z | 1,014,597 | <p>Note: the following code (and the sample code you offered) will put <em>all</em> matching elements at the front.</p>
<pre><code>x = targetvalue
for i in range(len(mylist)):
if(mylist[i] == x):
mylist = [mylist[i]] + mylist[:i] + mylist[i+1:]
</code></pre>
<p>For example, if mylist = [1, 2, 3, 4, 3] and x = 3, this will result in [3, 3, 1, 2, 4].</p>
| 0 | 2009-06-18T19:03:40Z | [
"python"
] |
Simple syntax for bringing a list element to the front in python? | 1,014,523 | <p>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?</p>
<p>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 could do.</p>
<pre><code> mylist = sorted(mylist,
key=lambda x: x == targetvalue,
reverse=True)
</code></pre>
<p>Cheers,
/YGA</p>
| 17 | 2009-06-18T18:52:58Z | 22,728,388 | <p>Using insertion design technique (which does exactly same as what Mike suggested):</p>
<pre><code>def move-to-front(key, mylist):
for i in range(len(mylist[:mylist.index(key)]), -1, -1):
mylist[i] = mylist[i - 1]
mylist[0] = key
</code></pre>
| 0 | 2014-03-29T07:38:54Z | [
"python"
] |
Simple syntax for bringing a list element to the front in python? | 1,014,523 | <p>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?</p>
<p>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 could do.</p>
<pre><code> mylist = sorted(mylist,
key=lambda x: x == targetvalue,
reverse=True)
</code></pre>
<p>Cheers,
/YGA</p>
| 17 | 2009-06-18T18:52:58Z | 28,370,695 | <p>This requires just two list operations (no index):
<code>
mylist.remove(targetvalue)
mylist.insert(0, targetvalue)
</code></p>
| 4 | 2015-02-06T16:48:56Z | [
"python"
] |
Python Authentication with urllib2 | 1,014,570 | <p>So I'm trying to download a file from a site called vsearch.cisco.com with python</p>
<p>[python]</p>
<pre><code>#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 connection
# Create a Handler -- Also could be where the error lies
handler = urllib2.HTTPDigestAuthHandler()
handler.add_password(realm,url,username,password)
# Create an Opener
opener = urllib2.build_opener(handler)
urllib2.install_opener(opener)
try:
urllib2.urlopen(url)
print f.read()
except urllib2.HTTPError, e:
print e.code
print e.header
</code></pre>
<p>[/python]</p>
<p>My error is ValueError: AbstractDigestAuthHandler doesn't know about basic</p>
<p>I've tried using Basic HTML Authorization handlers and even HTTPS handlers. Nothing gives me access. This error is different from all the other errors however. The other errors are simply 401 HTML errors</p>
<p>Any suggestions on how to do this?</p>
| 4 | 2009-06-18T19:00:28Z | 1,014,628 | <p>As for what I tried in my tests (<a href="http://devel.almad.net/trac/django-http-digest/browser/djangohttpdigest/tests/test_simple_digest.py" rel="nofollow">http://devel.almad.net/trac/django-http-digest/browser/djangohttpdigest/tests/test_simple_digest.py</a>), error is prabably in your url - To make it working, I've included http:// part, not only host.</p>
| 0 | 2009-06-18T19:09:54Z | [
"python"
] |
Python Authentication with urllib2 | 1,014,570 | <p>So I'm trying to download a file from a site called vsearch.cisco.com with python</p>
<p>[python]</p>
<pre><code>#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 connection
# Create a Handler -- Also could be where the error lies
handler = urllib2.HTTPDigestAuthHandler()
handler.add_password(realm,url,username,password)
# Create an Opener
opener = urllib2.build_opener(handler)
urllib2.install_opener(opener)
try:
urllib2.urlopen(url)
print f.read()
except urllib2.HTTPError, e:
print e.code
print e.header
</code></pre>
<p>[/python]</p>
<p>My error is ValueError: AbstractDigestAuthHandler doesn't know about basic</p>
<p>I've tried using Basic HTML Authorization handlers and even HTTPS handlers. Nothing gives me access. This error is different from all the other errors however. The other errors are simply 401 HTML errors</p>
<p>Any suggestions on how to do this?</p>
| 4 | 2009-06-18T19:00:28Z | 1,014,646 | <p>A "password manager" might help:</p>
<pre><code> mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
mgr.add_password(None, url, user, password)
urllib2.build_opener(urllib2.HTTPBasicAuthHandler(mgr),
urllib2.HTTPDigestAuthHandler(mgr))
</code></pre>
| 7 | 2009-06-18T19:13:13Z | [
"python"
] |
Traversing foreign key related tables in django templates | 1,014,591 | <h2>View</h2>
<pre><code>categories = Category.objects.all()
t = loader.get_template('index.html')
v = Context({
'categories': categories
})
return HttpResponse(t.render(v))
</code></pre>
<h2>Template</h2>
<pre><code>{% for category in categories %}
<h1>{{ category.name }}</h1>
{% endfor %}
</code></pre>
<p>this works great. now im trying to print each company in that category. the company table has a foreign key to the category table</p>
<p>ive tried</p>
<pre><code>{% for company in category.company_set.all() %}
</code></pre>
<p>seems django doesn't like () in templates</p>
<p>There's a maze of information on the django site i keep getting lost between the .96, 1.0 and dev version. im running django version 1.0.2</p>
| 27 | 2009-06-18T19:02:45Z | 1,014,610 | <p>Just get rid of the parentheses:</p>
<pre><code>{% for company in category.company_set.all %}
</code></pre>
<p>Here's the <a href="http://docs.djangoproject.com/en/dev/topics/templates/#variables">appropriate documentation</a>. You can call methods that take 0 parameters this way.</p>
| 43 | 2009-06-18T19:06:31Z | [
"python",
"django",
"django-models",
"django-templates"
] |
Logging All Exceptions in a pyqt4 app | 1,015,047 | <p>What's the best way to log all of the exceptions in a pyqt4 application using the standard python logging api?</p>
<p>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.</p>
<p>As a temporary solution, I wrapped the most important methods in try, except blocks, but that can't be the only way to do it.</p>
| 11 | 2009-06-18T20:34:23Z | 1,015,272 | <p>You need to override <a href="http://docs.python.org/library/sys.html"><code>sys.excepthook</code></a></p>
<pre><code>def my_excepthook(type, value, tback):
# log the exception here
# then call the default handler
sys.__excepthook__(type, value, tback)
sys.excepthook = my_excepthook
</code></pre>
| 15 | 2009-06-18T21:27:06Z | [
"python",
"logging",
"pyqt"
] |
Is it possible to override the method used to call Django's admin delete confirmation page? | 1,015,072 | <p>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.</p>
<p>I realize I could override the template page for this object, but I was hoping for something easier (i.e., override a method on the model or the form).</p>
<p>Any thoughts?</p>
| 4 | 2009-06-18T20:40:14Z | 1,015,332 | <p>You can override <code>ModelAdmin.delete_view()</code> method, like:</p>
<pre><code>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, self).delete_view(request, object_id, extra_context)
</code></pre>
| 7 | 2009-06-18T21:37:38Z | [
"python",
"django",
"django-admin"
] |
Is it possible to override the method used to call Django's admin delete confirmation page? | 1,015,072 | <p>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.</p>
<p>I realize I could override the template page for this object, but I was hoping for something easier (i.e., override a method on the model or the form).</p>
<p>Any thoughts?</p>
| 4 | 2009-06-18T20:40:14Z | 4,708,452 | <p>We can use django.shortcuts.redirect to interrupt deletion, like this:</p>
<pre><code>def check_del(self, object_id):
produkt = Produkt.objects.get(id = object_id)
if produkt.typsklepu_set.all():
return False
else:
return True
def delete_view(self, request, object_id, extra_context=None):
# if request.POST is set, the user already confirmed deletion
if not request.POST and self.check_del(object_id):
return super(ProduktAdmin, self).delete_view(request, object_id, extra_context)
elif request.POST:
return super(ProduktAdmin, self).delete_view(request, object_id, extra_context)
else:
msg = u'Can not delete this object.'
messages.error(request, msg)
return redirect('..')
</code></pre>
| 1 | 2011-01-16T22:16:36Z | [
"python",
"django",
"django-admin"
] |
Running Python code contained in a string | 1,015,142 | <p>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.</p>
<p>My plan was to have a text editor in the character builder that let you write code similar to:</p>
<pre><code>if key == K_a:
## Move left
pass
elif key == K_d:
## Move right
pass
</code></pre>
<p>I will retrieve the contents of the text editor as a string, and I want the code to be run in a method in this method of Character:</p>
<pre><code>def keydown(self, key):
## Run code from text editor
</code></pre>
<p>What's the best way to do that?</p>
| 7 | 2009-06-18T20:55:33Z | 1,015,147 | <p>You can use the <a href="http://docs.python.org/library/functions.html#eval"><code>eval(string)</code></a> method to do this. </p>
<h2>Definition</h2>
<p><code>eval(code, globals=None, locals=None)</code><br />
The code is just standard Python code - this means that it still needs to be properly indented. </p>
<p>The globals can have a custom <code>__builtins__</code> defined, which could be useful for security purposes.</p>
<h2>Example</h2>
<pre><code>eval("print('Hello')")
</code></pre>
<p>Would print <code>hello</code> to the console. You can also specify local and global variables for the code to use:</p>
<pre><code>eval("print('Hello, %s'%name)", {}, {'name':'person-b'})
</code></pre>
<h2>Security Concerns</h2>
<p>Be careful, though. Any user input will be executed. Consider:</p>
<pre><code>eval("import os;os.system('sudo rm -rf /')")
</code></pre>
<p>There are a number of ways around that. The easiest is to do something like:</p>
<pre><code>eval("import os;...", {'os':None})
</code></pre>
<p>Which will throw an exception, rather than erasing your hard drive. While your program is desktop, this could be a problem if people redistributed scripts, which I imagine is intended. </p>
<h2>Strange Example</h2>
<p>Here's an example of using <code>eval</code> rather strangely:</p>
<pre><code>def hello() : print('Hello')
def world() : print('world')
CURRENT_MOOD = 'happy'
eval(get_code(), {'contrivedExample':__main__}, {'hi':hello}.update(locals()))
</code></pre>
<p>What this does on the eval line is:</p>
<ol>
<li>Gives the current module another name (it becomes <code>contrivedExample</code> to the script). The consumer can call <code>contrivedExample.hello()</code> now.)</li>
<li>It defines <code>hi</code> as pointing to <code>hello</code></li>
<li>It combined that dictionary with the list of current globals in the executing module.</li>
</ol>
<h2>FAIL</h2>
<p>It turns out (thanks commenters!) that you actually need to use the <code>exec</code> statement. Big oops. The revised examples are as follows: </p>
<p><hr /></p>
<h2><code>exec</code> Definition</h2>
<p>(This looks familiar!)
Exec is a statement:<br />
<code>exec "code" [in scope]</code>
Where scope is a dictionary of both local and global variables. If this is not specified, it executes in the current scope.</p>
<p>The code is just standard Python code - this means that it still needs to be properly indented. </p>
<h2><code>exec</code> Example</h2>
<pre><code>exec "print('hello')"
</code></pre>
<p>Would print <code>hello</code> to the console. You can also specify local and global variables for the code to use:</p>
<pre><code>eval "print('hello, '+name)" in {'name':'person-b'}
</code></pre>
<h2><code>exec</code> Security Concerns</h2>
<p>Be careful, though. Any user input will be executed. Consider:</p>
<pre><code>exec "import os;os.system('sudo rm -rf /')"
</code></pre>
<p><hr /></p>
<h2>Print Statement</h2>
<p>As also noted by commenters, <code>print</code> is a statement in all versions of Python prior to 3.0. In 2.6, the behaviour can be changed by typing <code>from __future__ import print_statement</code>. Otherwise, use:</p>
<pre><code>print "hello"
</code></pre>
<p>Instead of :</p>
<pre><code>print("hello")
</code></pre>
| 22 | 2009-06-18T20:57:11Z | [
"python",
"pygame",
"exec",
"eval"
] |
Running Python code contained in a string | 1,015,142 | <p>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.</p>
<p>My plan was to have a text editor in the character builder that let you write code similar to:</p>
<pre><code>if key == K_a:
## Move left
pass
elif key == K_d:
## Move right
pass
</code></pre>
<p>I will retrieve the contents of the text editor as a string, and I want the code to be run in a method in this method of Character:</p>
<pre><code>def keydown(self, key):
## Run code from text editor
</code></pre>
<p>What's the best way to do that?</p>
| 7 | 2009-06-18T20:55:33Z | 1,015,154 | <p>You can use <a href="http://docs.python.org/library/functions.html#eval" rel="nofollow"><code>eval()</code></a></p>
| 0 | 2009-06-18T20:58:18Z | [
"python",
"pygame",
"exec",
"eval"
] |
Running Python code contained in a string | 1,015,142 | <p>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.</p>
<p>My plan was to have a text editor in the character builder that let you write code similar to:</p>
<pre><code>if key == K_a:
## Move left
pass
elif key == K_d:
## Move right
pass
</code></pre>
<p>I will retrieve the contents of the text editor as a string, and I want the code to be run in a method in this method of Character:</p>
<pre><code>def keydown(self, key):
## Run code from text editor
</code></pre>
<p>What's the best way to do that?</p>
| 7 | 2009-06-18T20:55:33Z | 1,015,156 | <p>eval or exec. You should definitely read Python library reference before programming.</p>
| 0 | 2009-06-18T20:58:38Z | [
"python",
"pygame",
"exec",
"eval"
] |
Running Python code contained in a string | 1,015,142 | <p>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.</p>
<p>My plan was to have a text editor in the character builder that let you write code similar to:</p>
<pre><code>if key == K_a:
## Move left
pass
elif key == K_d:
## Move right
pass
</code></pre>
<p>I will retrieve the contents of the text editor as a string, and I want the code to be run in a method in this method of Character:</p>
<pre><code>def keydown(self, key):
## Run code from text editor
</code></pre>
<p>What's the best way to do that?</p>
| 7 | 2009-06-18T20:55:33Z | 1,015,198 | <p>As others have pointed out, you can load the text into a string and use <code>exec "codestring"</code>. If contained in a file already, using <a href="http://docs.python.org/library/functions.html#execfile" rel="nofollow">execfile</a> will avoid having to load it.</p>
<p>One performance note: You should avoid execing the code multiple times, as parsing and compiling the python source is a slow process. ie. don't have:</p>
<pre><code>def keydown(self, key):
exec user_code
</code></pre>
<p>You can improve this a little by compiling the source into a code object (with <code>compile()</code> and exec that, or better, by constructing a function that you keep around, and only build once. Either require the user to write "def my_handler(args...)", or prepend it yourself, and do something like:</p>
<pre><code>user_source = "def user_func(args):\n" + '\n'.join(" "+line for line in user_source.splitlines())
d={}
exec user_source in d
user_func = d['user_func']
</code></pre>
<p>Then later:</p>
<pre><code>if key == K_a:
user_func(args)
</code></pre>
| 2 | 2009-06-18T21:12:28Z | [
"python",
"pygame",
"exec",
"eval"
] |
Python: Bind an Unbound Method? | 1,015,307 | <p>In Python, is there a way to bind an unbound method without calling it?</p>
<p>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:</p>
<pre><code>class MyWidget(wx.Window):
buttons = [("OK", OnOK),
("Cancel", OnCancel)]
# ...
def Setup(self):
for text, handler in MyWidget.buttons:
# This following line is the problem line.
b = wx.Button(parent, label=text).Bind(wx.EVT_BUTTON, handler)
</code></pre>
<p>The problem is, since all of the values of <code>handler</code> are unbound methods, my program explodes in a spectacular blaze and I weep.</p>
<p>I was looking around online for a solution to what seems like should be a relatively straightforward, solvable problem. Unfortunately I couldn't find anything. Right now, I'm using <code>functools.partial</code> to work around this, but does anyone know if there's a clean-feeling, healthy, Pythonic way to bind an unbound method to an instance and continue passing it around without calling it?</p>
| 82 | 2009-06-18T21:33:18Z | 1,015,355 | <p>This will bind <code>self</code> to <code>handler</code>:</p>
<pre><code>bound_handler = lambda *args, **kwargs: handler(self, *args, **kwargs)
</code></pre>
<p>This works by passing <code>self</code> as the first argument to the function. <code>object.function()</code> is just syntactic sugar for <code>function(object)</code>. </p>
| 2 | 2009-06-18T21:41:13Z | [
"python",
"class",
"methods",
"bind"
] |
Python: Bind an Unbound Method? | 1,015,307 | <p>In Python, is there a way to bind an unbound method without calling it?</p>
<p>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:</p>
<pre><code>class MyWidget(wx.Window):
buttons = [("OK", OnOK),
("Cancel", OnCancel)]
# ...
def Setup(self):
for text, handler in MyWidget.buttons:
# This following line is the problem line.
b = wx.Button(parent, label=text).Bind(wx.EVT_BUTTON, handler)
</code></pre>
<p>The problem is, since all of the values of <code>handler</code> are unbound methods, my program explodes in a spectacular blaze and I weep.</p>
<p>I was looking around online for a solution to what seems like should be a relatively straightforward, solvable problem. Unfortunately I couldn't find anything. Right now, I'm using <code>functools.partial</code> to work around this, but does anyone know if there's a clean-feeling, healthy, Pythonic way to bind an unbound method to an instance and continue passing it around without calling it?</p>
| 82 | 2009-06-18T21:33:18Z | 1,015,389 | <p>This can be done cleanly with <a href="http://docs.python.org/library/types.html#types.MethodType">types.MethodType</a>. Example:</p>
<pre><code>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 0x01255E90>>
</code></pre>
| 65 | 2009-06-18T21:50:36Z | [
"python",
"class",
"methods",
"bind"
] |
Python: Bind an Unbound Method? | 1,015,307 | <p>In Python, is there a way to bind an unbound method without calling it?</p>
<p>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:</p>
<pre><code>class MyWidget(wx.Window):
buttons = [("OK", OnOK),
("Cancel", OnCancel)]
# ...
def Setup(self):
for text, handler in MyWidget.buttons:
# This following line is the problem line.
b = wx.Button(parent, label=text).Bind(wx.EVT_BUTTON, handler)
</code></pre>
<p>The problem is, since all of the values of <code>handler</code> are unbound methods, my program explodes in a spectacular blaze and I weep.</p>
<p>I was looking around online for a solution to what seems like should be a relatively straightforward, solvable problem. Unfortunately I couldn't find anything. Right now, I'm using <code>functools.partial</code> to work around this, but does anyone know if there's a clean-feeling, healthy, Pythonic way to bind an unbound method to an instance and continue passing it around without calling it?</p>
| 82 | 2009-06-18T21:33:18Z | 1,015,405 | <p>All functions are also <em>descriptors</em>, so you can bind them by calling their <code>__get__</code> method:</p>
<pre><code>bound_handler = handler.__get__(self, MyWidget)
</code></pre>
<p>Here's R. Hettinger's excellent <a href="http://users.rcn.com/python/download/Descriptor.htm">guide</a> to descriptors.</p>
| 119 | 2009-06-18T21:54:29Z | [
"python",
"class",
"methods",
"bind"
] |
Python: Bind an Unbound Method? | 1,015,307 | <p>In Python, is there a way to bind an unbound method without calling it?</p>
<p>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:</p>
<pre><code>class MyWidget(wx.Window):
buttons = [("OK", OnOK),
("Cancel", OnCancel)]
# ...
def Setup(self):
for text, handler in MyWidget.buttons:
# This following line is the problem line.
b = wx.Button(parent, label=text).Bind(wx.EVT_BUTTON, handler)
</code></pre>
<p>The problem is, since all of the values of <code>handler</code> are unbound methods, my program explodes in a spectacular blaze and I weep.</p>
<p>I was looking around online for a solution to what seems like should be a relatively straightforward, solvable problem. Unfortunately I couldn't find anything. Right now, I'm using <code>functools.partial</code> to work around this, but does anyone know if there's a clean-feeling, healthy, Pythonic way to bind an unbound method to an instance and continue passing it around without calling it?</p>
| 82 | 2009-06-18T21:33:18Z | 7,312,062 | <p>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:</p>
<pre><code>self.method = (lambda self: lambda args: self.do(args))(self)
</code></pre>
| 7 | 2011-09-05T19:31:03Z | [
"python",
"class",
"methods",
"bind"
] |
Continuous unit testing with Pydev (Python and Eclipse) | 1,015,581 | <p>Is there a way to integrate background unit tests with the Pydev Eclipse environment?</p>
<p>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 trace log view).</p>
<p>No, a command prompt running nose on the side does not count.</p>
<p>I have had this Eclipse integration when developing RoR stuff.</p>
<p>Thanks,</p>
<p>Tal.</p>
<p><strong>EDIT:</strong> Check out the new Pydev (1.6.4) <a href="http://pydev.org/manual_adv_pyunit.html">http://pydev.org/manual_adv_pyunit.html</a></p>
| 42 | 2009-06-18T22:46:50Z | 1,039,552 | <p>Pydev does have some unit-test integration, but that's only as a run configuration...so...</p>
<p>This is not a very elegant way, but if you:</p>
<ol>
<li>Enable Project->Build Automatically</li>
<li>In your project properties, add a new builder of type Program</li>
<li>Configure it to run your tests and select 'during auto builds'</li>
</ol>
<p>Then at least you will get something that outputs the test results to the console on resource saves.</p>
| 9 | 2009-06-24T16:44:23Z | [
"python",
"unit-testing",
"pydev"
] |
Continuous unit testing with Pydev (Python and Eclipse) | 1,015,581 | <p>Is there a way to integrate background unit tests with the Pydev Eclipse environment?</p>
<p>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 trace log view).</p>
<p>No, a command prompt running nose on the side does not count.</p>
<p>I have had this Eclipse integration when developing RoR stuff.</p>
<p>Thanks,</p>
<p>Tal.</p>
<p><strong>EDIT:</strong> Check out the new Pydev (1.6.4) <a href="http://pydev.org/manual_adv_pyunit.html">http://pydev.org/manual_adv_pyunit.html</a></p>
| 42 | 2009-06-18T22:46:50Z | 1,040,367 | <p>I just realized that PyDev has rather powerful scripting support. Unfortunately I don't have the time to do it all for you (but if you complete this, please post it here :)</p>
<p>If you create a file named <code>pyedit_nose.py</code> that looks like this in an otherwise empty folder :</p>
<pre><code>assert cmd is not None
assert editor is not None
if cmd == 'onSave':
from java.lang import Runtime
from java.io import BufferedReader
from java.io import InputStreamReader
from org.eclipse.core.resources import ResourcesPlugin
from org.eclipse.core.resources import IMarker
from org.eclipse.core.resources import IResource
proc = Runtime.getRuntime().exec('ls -al')
extra_message = BufferedReader(InputStreamReader(proc.inputStream)).readLine()
r = ResourcesPlugin.getWorkspace().getRoot()
for marker in r.findMarkers(IMarker.PROBLEM, False, IResource.DEPTH_INFINITE):
if marker.getAttribute(IMarker.MESSAGE).startsWith("Some test failed!"):
marker.delete()
for rr in r.getProjects():
marker = rr.createMarker(IMarker.PROBLEM)
marker.setAttribute(IMarker.MESSAGE, "Some test failed! " + extra_message)
marker.setAttribute(IMarker.PRIORITY, IMarker.PRIORITY_HIGH)
marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_ERROR)
</code></pre>
<p>and set up Preferences->PyDev->Scripting Pydev to point to this directory you will get all projects in your workspace marked with an error every time a file is saved.</p>
<p>By executing a script that returns the test results in some easy to parse format rather than <code>ls</code> and parsing the output you should be able to put your markers in the right places.</p>
<p>See this for some starting points:</p>
<ul>
<li><a href="http://fabioz.com/pydev/manual%5Farticles%5Fscripting.html">Jython Scripting in Pydev</a></li>
<li><a href="http://help.eclipse.org/stable/index.jsp?topic=/org.eclipse.platform.doc.isv/reference/api/org/eclipse/core/resources/IMarker.html">IMarker</a> is what represents a marker.</li>
<li><a href="http://help.eclipse.org/stable/index.jsp?topic=/org.eclipse.platform.doc.isv/reference/api/org/eclipse/core/resources/IResource.html">IResource</a> is what you attach your markers to. Can be workspaces, projects, files, directories etc. <code>resource.createMarker(IMarker.PROBLEM)</code> creates a problem marker.</li>
<li><a href="http://help.eclipse.org/stable/index.jsp?topic=/org.eclipse.platform.doc.isv/reference/api/org/eclipse/core/resources/IProject.html">IProject</a> is a type of <code>IResource</code> that represents a project. Use the <code>members()</code> method to get the contents.</li>
</ul>
| 5 | 2009-06-24T19:16:37Z | [
"python",
"unit-testing",
"pydev"
] |
Continuous unit testing with Pydev (Python and Eclipse) | 1,015,581 | <p>Is there a way to integrate background unit tests with the Pydev Eclipse environment?</p>
<p>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 trace log view).</p>
<p>No, a command prompt running nose on the side does not count.</p>
<p>I have had this Eclipse integration when developing RoR stuff.</p>
<p>Thanks,</p>
<p>Tal.</p>
<p><strong>EDIT:</strong> Check out the new Pydev (1.6.4) <a href="http://pydev.org/manual_adv_pyunit.html">http://pydev.org/manual_adv_pyunit.html</a></p>
| 42 | 2009-06-18T22:46:50Z | 2,597,280 | <p>I use <a href="http://pypi.python.org/pypi/nosy" rel="nofollow">Nosy</a> (available on pypi): </p>
<blockquote>
<p>Run the nose test discovery and execution tool whenever a source file
is changed.</p>
</blockquote>
| 0 | 2010-04-08T02:51:10Z | [
"python",
"unit-testing",
"pydev"
] |
Continuous unit testing with Pydev (Python and Eclipse) | 1,015,581 | <p>Is there a way to integrate background unit tests with the Pydev Eclipse environment?</p>
<p>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 trace log view).</p>
<p>No, a command prompt running nose on the side does not count.</p>
<p>I have had this Eclipse integration when developing RoR stuff.</p>
<p>Thanks,</p>
<p>Tal.</p>
<p><strong>EDIT:</strong> Check out the new Pydev (1.6.4) <a href="http://pydev.org/manual_adv_pyunit.html">http://pydev.org/manual_adv_pyunit.html</a></p>
| 42 | 2009-06-18T22:46:50Z | 4,338,466 | <p>I enhanced the "nosy" script to automatically build documentation and runs tests
continuously. Nothing stellar, but gets the job done. Posting it here because the original
link went down. Unlike the original nosy script, this one scans the directory recursively
and allows looking for multiple patterns.</p>
<pre><code>import os
import os.path
import sys
import stat
import time
import subprocess
from fnmatch import fnmatch
def match_patterns(pathname, patterns):
"""Returns True if the pathname matches any of the given patterns."""
for pattern in patterns:
if fnmatch(pathname, pattern):
return True
return False
def filter_paths(pathnames, patterns=["*"], ignore_patterns=[]):
"""Filters from a set of paths based on acceptable patterns and
ignorable patterns."""
result = []
if patterns is None:
patterns = []
if ignore_patterns is None:
ignore_patterns = []
for path in pathnames:
if match_patterns(path, patterns) and not match_patterns(path, ignore_patterns):
result.append(path)
return result
def absolute_walker(path, recursive):
if recursive:
walk = os.walk
else:
def walk(path):
return os.walk(path).next()
for root, directories, filenames in walk(path):
yield root
for directory in directories:
yield os.path.abspath(os.path.join(root, directory))
for filename in filenames:
yield os.path.abspath(os.path.join(root, filename))
def glob_recursive(path, patterns=["*"], ignore_patterns=[]):
full_paths = []
for root, directories, filenames in os.walk(path):
for filename in filenames:
full_path = os.path.abspath(os.path.join(root, filename))
full_paths.append(full_path)
filepaths = filter_paths(full_paths, patterns, ignore_patterns)
return filepaths
def check_sum(path='.', patterns=["*"], ignore_patterns=[]):
sum = 0
for f in glob_recursive(path, patterns, ignore_patterns):
stats = os.stat(f)
sum += stats[stat.ST_SIZE] + stats[stat.ST_MTIME]
return sum
if __name__ == "__main__":
if len(sys.argv) > 1:
path = sys.argv[1]
else:
path = '.'
if len(sys.argv) > 2:
command = sys.argv[2]
else:
command = "make -C docs html; bin/python tests/run_tests.py"
previous_checksum = 0
while True:
calculated_checksum = check_sum(path, patterns=['*.py', '*.rst', '*.rst.inc'])
if calculated_checksum != previous_checksum:
previous_checksum = calculated_checksum
subprocess.Popen(command, shell=True)
time.sleep(2)
</code></pre>
<p>Hope this helps.</p>
<p>=)</p>
| 0 | 2010-12-02T18:29:34Z | [
"python",
"unit-testing",
"pydev"
] |
Continuous unit testing with Pydev (Python and Eclipse) | 1,015,581 | <p>Is there a way to integrate background unit tests with the Pydev Eclipse environment?</p>
<p>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 trace log view).</p>
<p>No, a command prompt running nose on the side does not count.</p>
<p>I have had this Eclipse integration when developing RoR stuff.</p>
<p>Thanks,</p>
<p>Tal.</p>
<p><strong>EDIT:</strong> Check out the new Pydev (1.6.4) <a href="http://pydev.org/manual_adv_pyunit.html">http://pydev.org/manual_adv_pyunit.html</a></p>
| 42 | 2009-06-18T22:46:50Z | 5,071,787 | <p>I run the test by hand the first time (<em>Run > Run As > Python unit test</em>). After that, I use
<code>Ctrl+Shift+F9</code> to have the files saved and the tests executed, instead of saving with <code>Ctrl+S</code> and expecting some magic to happen. </p>
<p>The <code>Ctrl+Shift+F9</code> key combination relaunches the last run configuration.</p>
<p><strong>Disclaimer</strong>: I'm new to Eclipse and to PyDev, so I may be suggesting something silly/obvious/wrong</p>
| 0 | 2011-02-21T22:04:19Z | [
"python",
"unit-testing",
"pydev"
] |
Continuous unit testing with Pydev (Python and Eclipse) | 1,015,581 | <p>Is there a way to integrate background unit tests with the Pydev Eclipse environment?</p>
<p>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 trace log view).</p>
<p>No, a command prompt running nose on the side does not count.</p>
<p>I have had this Eclipse integration when developing RoR stuff.</p>
<p>Thanks,</p>
<p>Tal.</p>
<p><strong>EDIT:</strong> Check out the new Pydev (1.6.4) <a href="http://pydev.org/manual_adv_pyunit.html">http://pydev.org/manual_adv_pyunit.html</a></p>
| 42 | 2009-06-18T22:46:50Z | 5,650,640 | <p>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 final launch for the whole suite is done (then you can move on to another task).</p>
<p>The current nightly build has this feature incorporated.</p>
<p><img src="http://i.stack.imgur.com/ZZgWk.png" alt="Picture with new action"></p>
| 34 | 2011-04-13T14:09:41Z | [
"python",
"unit-testing",
"pydev"
] |
Why is `self` in Python objects immutable? | 1,015,592 | <p>Why can't I perform an action like the following:</p>
<pre><code>class Test(object):
def __init__(self):
self = 5
t = Test()
print t
</code></pre>
<p>I would expect it to print <code>5</code> 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.</p>
<p>I understand that there would be hardly any situations where one would want to do that, but it still seems odd that you can't.</p>
<p><strong>Update:</strong> I now understand <em>why</em> it doesn't work, but I'd still like to know if there is any way of replacing an instance from within the instance.</p>
| 24 | 2009-06-18T22:51:21Z | 1,015,599 | <p>Dr. Egon Spengler: It would be bad.<br />
Dr. Peter Venkman: I'm fuzzy on the whole good/bad thing. What do you mean, "bad"?<br />
Dr. Egon Spengler: Try to imagine all life as you know it stopping instantaneously and every molecule in your body exploding at the speed of light.</p>
| 0 | 2009-06-18T22:54:10Z | [
"python",
"object"
] |
Why is `self` in Python objects immutable? | 1,015,592 | <p>Why can't I perform an action like the following:</p>
<pre><code>class Test(object):
def __init__(self):
self = 5
t = Test()
print t
</code></pre>
<p>I would expect it to print <code>5</code> 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.</p>
<p>I understand that there would be hardly any situations where one would want to do that, but it still seems odd that you can't.</p>
<p><strong>Update:</strong> I now understand <em>why</em> it doesn't work, but I'd still like to know if there is any way of replacing an instance from within the instance.</p>
| 24 | 2009-06-18T22:51:21Z | 1,015,602 | <p><em>Any</em> simple assignment to <em>any</em> argument of <em>any</em> 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!-)</p>
<p>So, far from it being odd (that simply=assigning to a specific argument in a specific function has no externally visible effect whatsoever), it would be utterly <em>astonishing</em> if this specific case worked in any other way, just because of the names of the function and argument in question.</p>
<p>Should you ever want to make a class that constructs an object of a different type than itself, such behavior is of course quite possible -- but it's obtained by overriding the special method <code>__new__</code>, <strong>not</strong> <code>__init__</code>:</p>
<pre><code>class Test(object):
def __new__(cls):
return 5
t = Test()
print t
</code></pre>
<p>This <em>does</em> emit <code>5</code>. The <code>__new__</code> / <code>__init__</code> behavior in Python is an example of the "two-step construction" design pattern: the "constructor" proper is <code>__new__</code> (it builds and returns a (normally uninitialized) object (normally a new one of the type/class in question); <code>__init__</code> is the "initializer" which properly initializes the new object.</p>
<p>This allows, for example, the construction of objects that are immutable once constructed: in this case everything must be done in <code>__new__</code>, before the immutable object is constructed, since, given that the object is immutable, <code>__init__</code> cannot mutate it in order to initialize it.</p>
| 58 | 2009-06-18T22:55:06Z | [
"python",
"object"
] |
Why is `self` in Python objects immutable? | 1,015,592 | <p>Why can't I perform an action like the following:</p>
<pre><code>class Test(object):
def __init__(self):
self = 5
t = Test()
print t
</code></pre>
<p>I would expect it to print <code>5</code> 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.</p>
<p>I understand that there would be hardly any situations where one would want to do that, but it still seems odd that you can't.</p>
<p><strong>Update:</strong> I now understand <em>why</em> it doesn't work, but I'd still like to know if there is any way of replacing an instance from within the instance.</p>
| 24 | 2009-06-18T22:51:21Z | 1,015,604 | <p>It doesnt "ignore" the assignment. The assignment works just fine, you created a local name that points to the data 5.</p>
<p>If you <em>really</em> want to do what you are doing...</p>
<pre><code>class Test(object):
def __new__(*args):
return 5
</code></pre>
| 9 | 2009-06-18T22:55:28Z | [
"python",
"object"
] |
Why is `self` in Python objects immutable? | 1,015,592 | <p>Why can't I perform an action like the following:</p>
<pre><code>class Test(object):
def __init__(self):
self = 5
t = Test()
print t
</code></pre>
<p>I would expect it to print <code>5</code> 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.</p>
<p>I understand that there would be hardly any situations where one would want to do that, but it still seems odd that you can't.</p>
<p><strong>Update:</strong> I now understand <em>why</em> it doesn't work, but I'd still like to know if there is any way of replacing an instance from within the instance.</p>
| 24 | 2009-06-18T22:51:21Z | 1,015,615 | <p>I just ran a quick test, and you can assign to self. Inside your <strong>init</strong>() method, print out the value of self. You'll see that it's 5.</p>
<p>What you're missing here is that parameters are passed by value in Python. So, changing the value of a variable in a function or method won't change it for the outside world.</p>
<p>All that being said, I would strongly advise against ever changing self.</p>
| 3 | 2009-06-18T22:57:57Z | [
"python",
"object"
] |
Why is `self` in Python objects immutable? | 1,015,592 | <p>Why can't I perform an action like the following:</p>
<pre><code>class Test(object):
def __init__(self):
self = 5
t = Test()
print t
</code></pre>
<p>I would expect it to print <code>5</code> 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.</p>
<p>I understand that there would be hardly any situations where one would want to do that, but it still seems odd that you can't.</p>
<p><strong>Update:</strong> I now understand <em>why</em> it doesn't work, but I'd still like to know if there is any way of replacing an instance from within the instance.</p>
| 24 | 2009-06-18T22:51:21Z | 1,015,645 | <p>Sometimes you want to do this, though not with immutable types like <code>int</code>:</p>
<pre><code>>>> class Test(list):
... def __init__(self):
... list.__init__(self, [1,2,3]) # self = [1,2,3] seems right, but isn't
>> t = Test()
>> print t
[1, 2, 3]
</code></pre>
| 1 | 2009-06-18T23:06:41Z | [
"python",
"object"
] |
Why is `self` in Python objects immutable? | 1,015,592 | <p>Why can't I perform an action like the following:</p>
<pre><code>class Test(object):
def __init__(self):
self = 5
t = Test()
print t
</code></pre>
<p>I would expect it to print <code>5</code> 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.</p>
<p>I understand that there would be hardly any situations where one would want to do that, but it still seems odd that you can't.</p>
<p><strong>Update:</strong> I now understand <em>why</em> it doesn't work, but I'd still like to know if there is any way of replacing an instance from within the instance.</p>
| 24 | 2009-06-18T22:51:21Z | 1,015,670 | <pre><code>class Test(object):
def __init__(self):
self = 5
t = Test()
print t
</code></pre>
<p>is like having this PHP (only other lang i know, sorry)</p>
<pre><code>class Test {
function __construct() {
$this = 5;
}
}
</code></pre>
<p>I don't see how it makes sense. replacing the instance with a value?</p>
| -3 | 2009-06-18T23:12:50Z | [
"python",
"object"
] |
How do I compile Python C extensions using MinGW inside a virtualenv? | 1,015,605 | <p>When using virtualenv in combination with the MinGW compiler on Windows, compiling a C extension results in the following error:</p>
<pre>
C:\MinGW\bin\..\lib\gcc\mingw32\3.4.5\..\..\..\..\mingw32\bin\ld.exe: cannot find -lpython25
collect2: ld returned 1 exit status
error: Setup script exited with error: command 'gcc' failed with exit status 1
</pre>
<p>What should one do to successfully compile C extensions?</p>
| 2 | 2009-06-18T22:55:29Z | 1,015,628 | <p>Set the <code>LIBRARY_PATH</code> environment variable so MinGW knows where to find the system-wide Python <code>libpython25.a</code>.</p>
<p>Place a line in your virtualenv's <code>activate.bat</code>:</p>
<pre><code>set LIBRARY_PATH=c:\python25\libs
</code></pre>
<p>Or set a global environment variable in Windows.</p>
<p>Be sure to change <code>25</code> to correspond to your version of Python if you're not using version 2.5.</p>
| 6 | 2009-06-18T23:01:38Z | [
"python",
"mingw",
"virtualenv"
] |
Passing Formatted Text Through XSLT | 1,015,816 | <p>I have formatted text (with newlines, tabs, etc.) coming in from a Telnet connection. I have a python script that manages the Telnet connection and embeds the Telnet response in XML that then gets passed through an XSLT transform. How do I pass that XML through the transform without losing the original formatting? I have access to the transformation script and the python script but not the transform invocation itself.</p>
| 0 | 2009-06-19T00:02:53Z | 1,015,827 | <p>You could embed the text you want to be untouched in a <a href="http://www.w3schools.com/Xml/xml%5Fcdata.asp" rel="nofollow">CDATA section</a>.</p>
| 0 | 2009-06-19T00:07:37Z | [
"python",
"xslt"
] |
Passing Formatted Text Through XSLT | 1,015,816 | <p>I have formatted text (with newlines, tabs, etc.) coming in from a Telnet connection. I have a python script that manages the Telnet connection and embeds the Telnet response in XML that then gets passed through an XSLT transform. How do I pass that XML through the transform without losing the original formatting? I have access to the transformation script and the python script but not the transform invocation itself.</p>
| 0 | 2009-06-19T00:02:53Z | 1,016,919 | <p>Data stored in XML comes out the same way it goes in. So if you store the text in an element, no whitespace and newlines are lost unless you tamper with the data in the XSLT. </p>
<p>Enclosing the text in CDATA is unnecessary <em>unless</em> there is some formatting that is invalid in XML (pointy brackets, ampersands, quotes) <em>and</em> you don't want to XML-escape the text under any circumstances. This is up to you, but in any case XML-escaping is completely transparent when the XML is handled with an XML-aware tool chain.</p>
<p>To answer your question more specifically, you need to show some input, the essential part of the transformation, and some output.</p>
| 0 | 2009-06-19T08:33:52Z | [
"python",
"xslt"
] |
python importing relative modules | 1,016,105 | <p>I have the Python modules a.py and b.py in the same directory.
How can I reliably import b.py from a.py, given that a.py may have been imported from another directory or executed directly? This module will be distributed so I can't hardcode a single path.</p>
<p>I've been playing around with <code>__file__</code>, sys.path and os.chdir, but it feels messy. And <code>__file__</code> is not always available.</p>
<p>thanks</p>
| 0 | 2009-06-19T02:29:29Z | 1,016,121 | <p>Actually, <code>__file__</code> is available for an imported module, but only if it was imported from a .py/.pyc file. It won't be available if the module is built in. For example:</p>
<pre><code>>>> import sys, os
>>> hasattr(os, '__file__')
True
>>> hasattr(sys, '__file__')
False
</code></pre>
| 6 | 2009-06-19T02:37:02Z | [
"python",
"path",
"module",
"relative",
"python-import"
] |
python importing relative modules | 1,016,105 | <p>I have the Python modules a.py and b.py in the same directory.
How can I reliably import b.py from a.py, given that a.py may have been imported from another directory or executed directly? This module will be distributed so I can't hardcode a single path.</p>
<p>I've been playing around with <code>__file__</code>, sys.path and os.chdir, but it feels messy. And <code>__file__</code> is not always available.</p>
<p>thanks</p>
| 0 | 2009-06-19T02:29:29Z | 1,016,185 | <p>Using the <a href="http://docs.python.org/library/inspect.html" rel="nofollow">inspect</a> module will make the builtin modules more obvious:</p>
<pre><code>>>> import os
>>> import sys
>>> inspect.getfile(os)
'/usr/local/lib/python2.6/os.pyc'
>>> inspect.getfile(sys)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.6/inspect.py", line 407, in getfile
raise TypeError('arg is a built-in module')
TypeError: arg is a built-in module
</code></pre>
| 1 | 2009-06-19T03:05:03Z | [
"python",
"path",
"module",
"relative",
"python-import"
] |
python importing relative modules | 1,016,105 | <p>I have the Python modules a.py and b.py in the same directory.
How can I reliably import b.py from a.py, given that a.py may have been imported from another directory or executed directly? This module will be distributed so I can't hardcode a single path.</p>
<p>I've been playing around with <code>__file__</code>, sys.path and os.chdir, but it feels messy. And <code>__file__</code> is not always available.</p>
<p>thanks</p>
| 0 | 2009-06-19T02:29:29Z | 1,036,276 | <p>Put the directory that contains both in your python path... or vice versa.</p>
| -1 | 2009-06-24T03:37:49Z | [
"python",
"path",
"module",
"relative",
"python-import"
] |
Cross-platform subprocess with hidden window | 1,016,384 | <p>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:</p>
<blockquote>
<p>ValueError: startupinfo is only supported on Windows platforms</p>
</blockquote>
<p>Is there a simpler way than creating a separate Popen command for each OS?</p>
<pre><code>if os.name == 'nt':
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
proc = subprocess.Popen(command, startupinfo=startupinfo)
if os.name == 'posix':
proc = subprocess.Popen(command)
</code></pre>
| 25 | 2009-06-19T04:52:50Z | 1,016,400 | <p>I'm not sure you can get much simpler than what you've done. You're talking about optimising out maybe 5 lines of code. For the money I would just get on with my project and accept this as a consquence of cross-platform development. If you do it a lot then create a specialised class or function to encapsulate the logic and import it.</p>
| 3 | 2009-06-19T05:00:22Z | [
"python",
"windows",
"linux",
"cross-platform",
"subprocess"
] |
Cross-platform subprocess with hidden window | 1,016,384 | <p>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:</p>
<blockquote>
<p>ValueError: startupinfo is only supported on Windows platforms</p>
</blockquote>
<p>Is there a simpler way than creating a separate Popen command for each OS?</p>
<pre><code>if os.name == 'nt':
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
proc = subprocess.Popen(command, startupinfo=startupinfo)
if os.name == 'posix':
proc = subprocess.Popen(command)
</code></pre>
| 25 | 2009-06-19T04:52:50Z | 1,016,633 | <p>You can turn your code into:</p>
<pre><code>params = dict()
if os.name == 'nt':
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
params['startupinfo'] = startupinfo
proc = subprocess.Popen(command, **params)
</code></pre>
<p>but that's not much better.</p>
| 1 | 2009-06-19T06:38:02Z | [
"python",
"windows",
"linux",
"cross-platform",
"subprocess"
] |
Cross-platform subprocess with hidden window | 1,016,384 | <p>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:</p>
<blockquote>
<p>ValueError: startupinfo is only supported on Windows platforms</p>
</blockquote>
<p>Is there a simpler way than creating a separate Popen command for each OS?</p>
<pre><code>if os.name == 'nt':
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
proc = subprocess.Popen(command, startupinfo=startupinfo)
if os.name == 'posix':
proc = subprocess.Popen(command)
</code></pre>
| 25 | 2009-06-19T04:52:50Z | 1,016,651 | <p>You can reduce one line :)</p>
<pre><code>startupinfo = None
if os.name == 'nt':
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
proc = subprocess.Popen(command, startupinfo=startupinfo)
</code></pre>
| 27 | 2009-06-19T06:48:07Z | [
"python",
"windows",
"linux",
"cross-platform",
"subprocess"
] |
Cross-platform subprocess with hidden window | 1,016,384 | <p>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:</p>
<blockquote>
<p>ValueError: startupinfo is only supported on Windows platforms</p>
</blockquote>
<p>Is there a simpler way than creating a separate Popen command for each OS?</p>
<pre><code>if os.name == 'nt':
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
proc = subprocess.Popen(command, startupinfo=startupinfo)
if os.name == 'posix':
proc = subprocess.Popen(command)
</code></pre>
| 25 | 2009-06-19T04:52:50Z | 3,443,174 | <p>Just a note: for <strong>Python 2.7</strong> I have to use <code>subprocess._subprocess.STARTF_USESHOWWINDOW</code> instead of <code>subprocess.STARTF_USESHOWWINDOW</code>.</p>
| 12 | 2010-08-09T18:49:16Z | [
"python",
"windows",
"linux",
"cross-platform",
"subprocess"
] |
finding firefox version | 1,016,609 | <p>How to find Firefox version using python?</p>
| 1 | 2009-06-19T06:30:56Z | 1,016,637 | <p>Try the following code snippet:</p>
<pre><code>import os
firefox_version = os.popen("firefox --version").read()
</code></pre>
| 2 | 2009-06-19T06:39:53Z | [
"python",
"firefox"
] |
finding firefox version | 1,016,609 | <p>How to find Firefox version using python?</p>
| 1 | 2009-06-19T06:30:56Z | 1,024,846 | <p>I tried Alan's code snippet and it didn't work for me. One problem with it is that in order for the "-v or -version" flags to work, you must have a debug version firefox. See <a href="https://developer.mozilla.org/En/Command%5FLine%5FOptions" rel="nofollow">here</a> under "Miscellaneous" for details.</p>
<p>Try the following, which uses the win32 library to read the Product Version string directly from the .exe file:</p>
<pre><code>import win32api
def get_version(filename):
info = win32api.GetFileVersionInfo(filename, "\\")
ms = info['ProductVersionMS']
ls = info['ProductVersionLS']
return win32api.HIWORD(ms), win32api.LOWORD(ms), win32api.HIWORD(ls), win32api.LOWORD(ls)
if __name__ == '__main__':
print ".".join([str (i) for i in get_version(r"C:\Program Files\Mozilla Firefox\firefox.exe")])
</code></pre>
| 3 | 2009-06-21T22:05:49Z | [
"python",
"firefox"
] |
How to "keep-alive" with cookielib and httplib in python? | 1,016,765 | <p>In python, I'm using httplib because it "keep-alive" the http connection (as oppose to urllib(2)). Now, I want to use cookielib with httplib but they seem to hate each other!! (no way to interface them together). </p>
<p>Does anyone know of a solution to that problem?</p>
| 1 | 2009-06-19T07:32:11Z | 1,016,898 | <p><a href="http://urlgrabber.baseurl.org/help/urlgrabber.keepalive.html" rel="nofollow">HTTP handler for urllib2 that supports keep-alive</a></p>
| 2 | 2009-06-19T08:26:38Z | [
"python",
"cookies",
"urllib2",
"httplib"
] |
How to "keep-alive" with cookielib and httplib in python? | 1,016,765 | <p>In python, I'm using httplib because it "keep-alive" the http connection (as oppose to urllib(2)). Now, I want to use cookielib with httplib but they seem to hate each other!! (no way to interface them together). </p>
<p>Does anyone know of a solution to that problem?</p>
| 1 | 2009-06-19T07:32:11Z | 1,053,602 | <p>You should consider using the <a href="http://docs.python-requests.org/en/latest/" rel="nofollow"><code>Requests</code></a> library instead at the earliest chance you have to refactor your code. In the mean time;</p>
<p>HACK ALERT! :)</p>
<p>I'd go other suggested way, but I've done a hack (done for different reasons though), which does create an interface between <a href="https://docs.python.org/2/library/httplib.html" rel="nofollow">httplib</a> and <a href="https://docs.python.org/2/library/cookielib.html" rel="nofollow">cookielib</a>.</p>
<p>What I did was creating a fake <code>HTTPRequest</code> with minimal required set of methods, so that <a href="https://docs.python.org/2/library/cookielib.html#cookielib.CookieJar" rel="nofollow"><code>CookieJar</code></a> would recognize it and process cookies as needed. I've used that fake request object, setting all the data needed for cookielib.</p>
<p>Here is the code of the class:</p>
<pre><code>class HTTPRequest( object ):
"""
Data container for HTTP request (used for cookie processing).
"""
def __init__( self, host, url, headers={}, secure=False ):
self._host = host
self._url = url
self._secure = secure
self._headers = {}
for key, value in headers.items():
self.add_header(key, value)
def has_header( self, name ):
return name in self._headers
def add_header( self, key, val ):
self._headers[key.capitalize()] = val
def add_unredirected_header(self, key, val):
self._headers[key.capitalize()] = val
def is_unverifiable( self ):
return True
def get_type( self ):
return 'https' if self._secure else 'http'
def get_full_url( self ):
port_str = ""
port = str(self._host[1])
if self._secure:
if port != 443:
port_str = ":"+port
else:
if port != 80:
port_str = ":"+port
return self.get_type() + '://' + self._host[0] + port_str + self._url
def get_header( self, header_name, default=None ):
return self._headers.get( header_name, default )
def get_host( self ):
return self._host[0]
get_origin_req_host = get_host
def get_headers( self ):
return self._headers
</code></pre>
<p>Please note, the class has support for HTTPS protocol only (all I needed at the moment).</p>
<p>The code, which used this class was (please note another hack to make response compatible with cookielib):</p>
<pre><code>cookies = CookieJar()
headers = {
# headers that you wish to set
}
# construct fake request
fake_request = HTTPRequest( host, request_url, headers )
# add cookies to fake request
cookies.add_cookie_header(fake_request)
# issue an httplib.HTTPConnection based request using cookies and headers from the fake request
http_connection.request(type, request_url, body, fake_request.get_headers())
response = http_connection.getresponse()
if response.status == httplib.OK:
# HACK: pretend we're urllib2 response
response.info = lambda : response.msg
# read and store cookies from response
cookies.extract_cookies(response, fake_request)
# process response...
</code></pre>
| 2 | 2009-06-27T20:51:39Z | [
"python",
"cookies",
"urllib2",
"httplib"
] |
What to do with "Unexpected indent" in python? | 1,016,814 | <p>How do I rectify the error "unexpected indent" in python?</p>
| 60 | 2009-06-19T07:53:20Z | 1,016,829 | <p>By using correct indentation. Python is whitespace aware, so you need to follow its indentation guidlines for blocks or you'll get indentation errors.</p>
| 8 | 2009-06-19T07:58:22Z | [
"python",
"syntax-error"
] |
What to do with "Unexpected indent" in python? | 1,016,814 | <p>How do I rectify the error "unexpected indent" in python?</p>
| 60 | 2009-06-19T07:53:20Z | 1,016,836 | <p>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 :</p>
<pre><code>def test_function() :
if 5 > 3 :
print "hello"
</code></pre>
<p>You may also have a mix of tabs and spaces in your file.</p>
<p>I suggest you use a python syntax aware editor like <a href="http://code.google.com/p/pyscripter/">PyScripter</a>, or <a href="http://www.netbeans.org/">Netbeans</a></p>
| 21 | 2009-06-19T08:00:08Z | [
"python",
"syntax-error"
] |
What to do with "Unexpected indent" in python? | 1,016,814 | <p>How do I rectify the error "unexpected indent" in python?</p>
| 60 | 2009-06-19T07:53:20Z | 1,017,404 | <p>Python uses spacing at the start of the line to determine when code blocks start and end. Errors you can get are:</p>
<p><strong>Unexpected indent.</strong> 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 start with exactly the same string of whitespace. For instance:</p>
<pre><code>>>> def a():
... print "foo"
... print "bar"
IndentationError: unexpected indent
</code></pre>
<p>This one is especially common when running python interactively: make sure you don't put any extra spaces before your commands. (Very annoying when copy-and-pasting example code!)</p>
<pre><code>>>> print "hello"
IndentationError: unexpected indent
</code></pre>
<p><strong>Unindent does not match any outer indentation level.</strong> This line of code has fewer spaces at the start than the one before, but equally it does not match any other block it could be part of. Python cannot decide where it goes. For instance, in the following, is the final print supposed to be part of the if clause, or not?</p>
<pre><code>>>> if user == "Joey":
... print "Super secret powers enabled!"
... print "Revealing super secrets"
IndendationError: unindent does not match any outer indentation level
</code></pre>
<p><strong>Expected an indented block.</strong> This line of code has the same number of spaces at the start as the one before, but the last line was expected to start a block (e.g. if/while/for statement, function definition).</p>
<pre><code>>>> def foo():
... print "Bar"
IndentationError: expected an indented block
</code></pre>
<p>If you want a function that doesn't do anything, use the "no-op" command <em>pass</em>:</p>
<pre><code>>>> def foo():
... pass
</code></pre>
<p>Mixing tabs and spaces is allowed (at least on my version of Python), but Python assumes tabs are 8 characters long, which may not match your editor. Just say "no" to tabs. Most editors allow them to be automatically replaced by spaces.</p>
<p>The best way to avoid these issues is to always use a consistent number of spaces when you indent a subblock, and ideally use a good IDE that solves the problem for you. This will also make your code more readable.</p>
| 85 | 2009-06-19T11:03:01Z | [
"python",
"syntax-error"
] |
What to do with "Unexpected indent" in python? | 1,016,814 | <p>How do I rectify the error "unexpected indent" in python?</p>
| 60 | 2009-06-19T07:53:20Z | 1,017,428 | <p>If the indentation looks ok then have a look to see if your editor has a "View Whitespace" option. Enabling this should allow to find where spaces and tabs are mixed.</p>
| 1 | 2009-06-19T11:15:26Z | [
"python",
"syntax-error"
] |
What to do with "Unexpected indent" in python? | 1,016,814 | <p>How do I rectify the error "unexpected indent" in python?</p>
| 60 | 2009-06-19T07:53:20Z | 1,017,449 | <p>There is a trick that always worked for me:</p>
<p>If you got and unexpected indent and you see that all the code is perfectly indented, try opening it with another editor and you will see what line of code is not indented.</p>
<p>It happened to me when used vim, gedit or editors like that.</p>
<p>Try to use only 1 editor for your code.</p>
| 2 | 2009-06-19T11:21:56Z | [
"python",
"syntax-error"
] |
What to do with "Unexpected indent" in python? | 1,016,814 | <p>How do I rectify the error "unexpected indent" in python?</p>
| 60 | 2009-06-19T07:53:20Z | 1,017,458 | <p><strong>Turn on visible whitespace in whatever editor you are using and turn on replace tabs with spaces.</strong></p>
<p>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.</p>
| 8 | 2009-06-19T11:25:47Z | [
"python",
"syntax-error"
] |
What to do with "Unexpected indent" in python? | 1,016,814 | <p>How do I rectify the error "unexpected indent" in python?</p>
| 60 | 2009-06-19T07:53:20Z | 7,499,004 | <p>Run your code with the -tt option to find out if you are using tabs and spaces inconsistently </p>
| 8 | 2011-09-21T11:31:51Z | [
"python",
"syntax-error"
] |
What to do with "Unexpected indent" in python? | 1,016,814 | <p>How do I rectify the error "unexpected indent" in python?</p>
| 60 | 2009-06-19T07:53:20Z | 18,830,607 | <p>Make sure you use the option "insert spaces instead of tabs" in your editor. Then you can choose you want a tab width of, for example 4. You can find those options in gedit under edit-->preferences-->editor.</p>
<p>bottom line: USE SPACES not tabs</p>
| 3 | 2013-09-16T14:33:24Z | [
"python",
"syntax-error"
] |
What to do with "Unexpected indent" in python? | 1,016,814 | <p>How do I rectify the error "unexpected indent" in python?</p>
| 60 | 2009-06-19T07:53:20Z | 25,902,014 | <p>Notepad++ was giving the tab space correct but the indentation problem was finally found in Sublime text editor.</p>
<p>Use Sublime text editor and go line by line</p>
| 1 | 2014-09-17T23:38:25Z | [
"python",
"syntax-error"
] |
What to do with "Unexpected indent" in python? | 1,016,814 | <p>How do I rectify the error "unexpected indent" in python?</p>
| 60 | 2009-06-19T07:53:20Z | 35,339,628 | <p>Simply copy your script and put under """ your entire code """ ...</p>
<p>specify this line in a variable.. like,</p>
<pre><code>a = """ your python script """
print a.replace('here please press tab button it will insert some space"," here simply press space bar four times")
# here we replacing tab space by four char space as per pep 8 style guide..
</code></pre>
<p>now execute this code, in Sublime Editor using ctrl+b, now it will print indented code in console. that's it</p>
| 1 | 2016-02-11T12:40:59Z | [
"python",
"syntax-error"
] |
Generate from generators | 1,016,997 | <p>I have a generator that takes a number as an argument and yields other numbers.
I want to use the numbers yielded by this generator and pass them as arguments to the same generator, creating a chain of some length.</p>
<p>For example, mygenerator(2) yields 5, 4 and 6. Apply mygenerator to each of these numbers, over and over again to the numbers yielded. The generator always yields bigger numbers than the one passed as argument, and for 2 different numbers will never yield the same number.</p>
<p>mygenerator(2): 4 5
mygenerator(4) : 10 11 12
mygenerator(5): 9 300 500</p>
<p>So the set (9,10,11,12,300,500) has "distance" 2 from the original number, 2. If I apply it to the number 9, I will get a set of numbers with distance "3" from the original 2.</p>
<p>Essentially what I want is to create a set that has a specified distance from a given number and I have problems figuring out how to do that in Python. Help much appreciated :)</p>
| 2 | 2009-06-19T09:00:33Z | 1,017,014 | <p>I have just started learning Python so bear with me if my answer seems a tad amateurish. What you could do is use a list of lists to populate the values returned from the myGenerator function.</p>
<p>So for eg. with 2 as the starting argument your data-structure would resemble something like </p>
<pre><code>resDataSet = [[2],
[4, 5],
[9, 10, 11, 12, 300 , 500]
...
]
</code></pre>
<p>The row index should give you the distance and you can use methods like extend to add on more data to your list.</p>
| 0 | 2009-06-19T09:06:58Z | [
"python",
"generator"
] |
Generate from generators | 1,016,997 | <p>I have a generator that takes a number as an argument and yields other numbers.
I want to use the numbers yielded by this generator and pass them as arguments to the same generator, creating a chain of some length.</p>
<p>For example, mygenerator(2) yields 5, 4 and 6. Apply mygenerator to each of these numbers, over and over again to the numbers yielded. The generator always yields bigger numbers than the one passed as argument, and for 2 different numbers will never yield the same number.</p>
<p>mygenerator(2): 4 5
mygenerator(4) : 10 11 12
mygenerator(5): 9 300 500</p>
<p>So the set (9,10,11,12,300,500) has "distance" 2 from the original number, 2. If I apply it to the number 9, I will get a set of numbers with distance "3" from the original 2.</p>
<p>Essentially what I want is to create a set that has a specified distance from a given number and I have problems figuring out how to do that in Python. Help much appreciated :)</p>
| 2 | 2009-06-19T09:00:33Z | 1,017,035 | <p>Suppose our generator yields square and cube of given number that way it will output unique
so if we want to get numbers at dist D in simplest case we can recursively get numbers at dist D-1 and then apply generator to them</p>
<pre><code>def mygen(N):
yield N**2
yield N**3
def getSet(N, dist):
if dist == 0:
return [N]
numbers = []
for n in getSet(N, dist-1):
numbers += list(mygen(n))
return numbers
print getSet(2,0)
print getSet(2,1)
print getSet(2,2)
print getSet(2,3)
</code></pre>
<p>output is</p>
<pre><code>[2]
[4, 8]
[16, 64, 64, 512]
[256, 4096, 4096, 262144, 4096, 262144, 262144, 134217728]
</code></pre>
| 3 | 2009-06-19T09:13:34Z | [
"python",
"generator"
] |
Generate from generators | 1,016,997 | <p>I have a generator that takes a number as an argument and yields other numbers.
I want to use the numbers yielded by this generator and pass them as arguments to the same generator, creating a chain of some length.</p>
<p>For example, mygenerator(2) yields 5, 4 and 6. Apply mygenerator to each of these numbers, over and over again to the numbers yielded. The generator always yields bigger numbers than the one passed as argument, and for 2 different numbers will never yield the same number.</p>
<p>mygenerator(2): 4 5
mygenerator(4) : 10 11 12
mygenerator(5): 9 300 500</p>
<p>So the set (9,10,11,12,300,500) has "distance" 2 from the original number, 2. If I apply it to the number 9, I will get a set of numbers with distance "3" from the original 2.</p>
<p>Essentially what I want is to create a set that has a specified distance from a given number and I have problems figuring out how to do that in Python. Help much appreciated :)</p>
| 2 | 2009-06-19T09:00:33Z | 1,017,105 | <p>This solution does not require to keep all results in memory: (in case it doesn't fit in memory etc)</p>
<pre><code>def grandKids(generation, kidsFunc, val):
layer = [val]
for i in xrange(generation):
layer = itertools.chain.from_iterable(itertools.imap(kidsFunc, layer))
return layer
</code></pre>
<p>Example:</p>
<pre><code>def kids(x): # children indices in a 1-based binary heap
yield x*2
yield x*2+1
>>> list(grandKids(3, kids, 2))
[16, 17, 18, 19, 20, 21, 22, 23]
</code></pre>
<p>Btw, solution in Haskell:</p>
<pre><code>grandKids generation kidsFunc val =
iterate (concatMap kidsFunc) [val] !! generation
</code></pre>
| 2 | 2009-06-19T09:29:45Z | [
"python",
"generator"
] |
Python cgi performance | 1,017,087 | <p>I own a legacy python application written as CGI. Until now this works OK, but the number of concurrent users will increment largely in the very near future.
Here on SO I read: "CGI is great for low-traffic websites, but it has some performance problems for anything else". I know it would have been better to start in another way, but CGI is what is is now. </p>
<p>Could someone point me a direction on to how to keep the CGI performing, without having to rewrite all code? </p>
| 2 | 2009-06-19T09:26:02Z | 1,017,103 | <p>Use <a href="http://www.fastcgi.com/drupal/" rel="nofollow">FastCGI</a>. If I understand FastCGI correctly, you can do what you want by writing a very simple Python program that sits between the web server and your legacy code.</p>
| 3 | 2009-06-19T09:29:14Z | [
"python",
"performance",
"cgi"
] |
Python cgi performance | 1,017,087 | <p>I own a legacy python application written as CGI. Until now this works OK, but the number of concurrent users will increment largely in the very near future.
Here on SO I read: "CGI is great for low-traffic websites, but it has some performance problems for anything else". I know it would have been better to start in another way, but CGI is what is is now. </p>
<p>Could someone point me a direction on to how to keep the CGI performing, without having to rewrite all code? </p>
| 2 | 2009-06-19T09:26:02Z | 1,017,354 | <p>CGI doesn't scale because each request forks a brand new server process. It's a lot of overhead. mod_wsgi avoid the overhead by forking one process and handing requests to that one running process.</p>
<p>Let's assume the application is the worst kind of cgi.</p>
<p>The worst case is that it has files like this.</p>
<p><code>my_cgi.py</code></p>
<pre><code>import cgi
print "status: 200 OK"
print "content-type: text/html"
print
print "<!doctype...>"
print "<html>"
etc.
</code></pre>
<p>You can try to "wrap" the original CGI files to make it wsgi.</p>
<p><code>wsgi.py</code></p>
<pre><code>import cStringIO
def my_cgi( environ, start_response ):
page = cStringIO.StringIO()
sys.stdout= page
os.environ.update( environ )
# you may have to do something like execfile( "my_cgi.py", globals=environ )
execfile( "my_cgi.py" )
status = '200 OK' # HTTP Status
headers = [('Content-type', 'text/html')] # HTTP Headers
start_response(status, headers)
return page.getvalue()
</code></pre>
<p>This a first step to rewriting your CGI application into a proper framework. This requires very little work, and will make your CGI's much more scalable, since you won't be starting a fresh CGI process for each request.</p>
<p>The second step is to create a <code>mod_wsgi</code> server that Apache uses instead of all the CGI scripts. This server must (1) parse the URL's, (2) call various function like the <code>my_cgi</code> example function. Each function will <code>execfile</code> the old CGI script without forking a new process.</p>
<p>Look at <a href="http://werkzeug.pocoo.org/" rel="nofollow">werkzeug</a> for helpful libraries.</p>
<p>If your application CGI scripts have some structure (functions, classes, etc.) you can probably import those and do something much, much smarter than the above. A better way is this. </p>
<p><code>wsgi.py</code></p>
<pre><code>from my_cgi import this_func, that_func
def my_cgi( environ, start_response ):
result= this_func( some_args )
page_text= that_func( result, some_other_args )
status = '200 OK' # HTTP Status
headers = [('Content-type', 'text/html')] # HTTP Headers
start_response(status, headers)
return page_text
</code></pre>
<p>This requires more work because you have to understand the legacy application. However, this has two advantages.</p>
<ol>
<li><p>It makes your CGI's more scalable because you're not starting a fresh process for each request.</p></li>
<li><p>It allows you to rethink your application, possibly changing it to a proper framework. Once you've done this, it's not very hard to take the next step and move to <a href="http://turbogears.org/" rel="nofollow">TurboGears</a> or <a href="http://pylonshq.com/" rel="nofollow">Pylons</a> or <a href="http://webpy.org/" rel="nofollow">web.py</a> for a very simple framework.</p></li>
</ol>
| 6 | 2009-06-19T10:46:31Z | [
"python",
"performance",
"cgi"
] |
UnicodeDecodeError when reading dictionary words file with simple Python script | 1,017,334 | <p>First time doing Python in a while, and I'm having trouble doing a simple scan of a file when I run the following script with Python 3.0.1,</p>
<pre><code>with open("/usr/share/dict/words", 'r') as f:
for line in f:
pass
</code></pre>
<p>I get this exception:</p>
<pre><code>Traceback (most recent call last):
File "/home/matt/install/test.py", line 2, in <module>
for line in f:
File "/home/matt/install/root/lib/python3.0/io.py", line 1744, in __next__
line = self.readline()
File "/home/matt/install/root/lib/python3.0/io.py", line 1817, in readline
while self._read_chunk():
File "/home/matt/install/root/lib/python3.0/io.py", line 1565, in _read_chunk
self._set_decoded_chars(self._decoder.decode(input_chunk, eof))
File "/home/matt/install/root/lib/python3.0/io.py", line 1299, in decode
output = self.decoder.decode(input, final=final)
File "/home/matt/install/root/lib/python3.0/codecs.py", line 300, in decode
(result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf8' codec can't decode bytes in position 1689-1692: invalid data
</code></pre>
<p>The line in the file it blows up on is "Argentinian", which doesn't seem to be unusual in any way.</p>
<p><strong>Update</strong>: I added,</p>
<pre><code>encoding="iso-8559-1"
</code></pre>
<p>to the open() call, and it fixed the problem.</p>
| 0 | 2009-06-19T10:35:22Z | 1,017,346 | <p>Can you check to make sure it is valid UTF-8? A way to do that is given at <a href="http://stackoverflow.com/questions/115210/utf-8-validation">this SO question</a>:</p>
<pre><code>iconv -f UTF-8 /usr/share/dict/words -o /dev/null
</code></pre>
<p>There are other ways to do the same thing.</p>
| 1 | 2009-06-19T10:42:29Z | [
"python"
] |
UnicodeDecodeError when reading dictionary words file with simple Python script | 1,017,334 | <p>First time doing Python in a while, and I'm having trouble doing a simple scan of a file when I run the following script with Python 3.0.1,</p>
<pre><code>with open("/usr/share/dict/words", 'r') as f:
for line in f:
pass
</code></pre>
<p>I get this exception:</p>
<pre><code>Traceback (most recent call last):
File "/home/matt/install/test.py", line 2, in <module>
for line in f:
File "/home/matt/install/root/lib/python3.0/io.py", line 1744, in __next__
line = self.readline()
File "/home/matt/install/root/lib/python3.0/io.py", line 1817, in readline
while self._read_chunk():
File "/home/matt/install/root/lib/python3.0/io.py", line 1565, in _read_chunk
self._set_decoded_chars(self._decoder.decode(input_chunk, eof))
File "/home/matt/install/root/lib/python3.0/io.py", line 1299, in decode
output = self.decoder.decode(input, final=final)
File "/home/matt/install/root/lib/python3.0/codecs.py", line 300, in decode
(result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf8' codec can't decode bytes in position 1689-1692: invalid data
</code></pre>
<p>The line in the file it blows up on is "Argentinian", which doesn't seem to be unusual in any way.</p>
<p><strong>Update</strong>: I added,</p>
<pre><code>encoding="iso-8559-1"
</code></pre>
<p>to the open() call, and it fixed the problem.</p>
| 0 | 2009-06-19T10:35:22Z | 1,017,376 | <p>How have you determined from "position 1689-1692" what line in the file it has blown up on? Those numbers would be offsets in the chunk that it's trying to decode. You would have had to determine what chunk it was -- how?</p>
<p>Try this at the interactive prompt:</p>
<pre><code>buf = open('the_file', 'rb').read()
len(buf)
ubuf = buf.decode('utf8')
# splat ... but it will give you the byte offset into the file
buf[offset-50:60] # should show you where/what the problem is
# By the way, from the error message, looks like a bad
# FOUR-byte UTF-8 character ... interesting
</code></pre>
| 1 | 2009-06-19T10:55:12Z | [
"python"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.