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
sequence |
---|---|---|---|---|---|---|---|---|---|
How to get a row-by-row MySQL ResultSet in python | 337,479 | <p>MySQL ResultSets are by default retrieved completely from the server before any work can be done. In cases of huge result sets this becomes unusable. I would like instead to actually retrieve the rows one by one from the server.</p>
<p>In Java, following the instructions <a href="http://dev.mysql.com/doc/refman/5.1/en/connector-j-reference-implementation-notes.html">here</a> (under "ResultSet"), I create a statement like this:</p>
<pre><code>stmt = conn.createStatement(java.sql.ResultSet.TYPE_FORWARD_ONLY,
java.sql.ResultSet.CONCUR_READ_ONLY);
stmt.setFetchSize(Integer.MIN_VALUE);
</code></pre>
<p>This works nicely in Java. My question is: is there a way to do the same in python?</p>
<p>One thing I tried is to limit the query to a 1000 rows at a time, like this:</p>
<pre><code>start_row = 0
while True:
cursor = conn.cursor()
cursor.execute("SELECT item FROM items LIMIT %d,1000" % start_row)
rows = cursor.fetchall()
if not rows:
break
start_row += 1000
# Do something with rows...
</code></pre>
<p>However, this seems to get slower the higher start_row is.</p>
<p>And no, using <code>fetchone()</code> instead of <code>fetchall()</code> doesn't change anything.</p>
<h2>Clarification:</h2>
<p>The naive code I use to reproduce this problem looks like this:</p>
<pre><code>import MySQLdb
conn = MySQLdb.connect(user="user", passwd="password", db="mydb")
cur = conn.cursor()
print "Executing query"
cur.execute("SELECT * FROM bigtable");
print "Starting loop"
row = cur.fetchone()
while row is not None:
print ", ".join([str(c) for c in row])
row = cur.fetchone()
cur.close()
conn.close()
</code></pre>
<p>On a ~700,000 rows table, this code runs quickly. But on a ~9,000,000 rows table it prints "Executing Query" and then hangs for a long long time. That is why it makes no difference if I use <code>fetchone()</code> or <code>fetchall()</code>.</p>
| 41 | 2008-12-03T15:23:49Z | 18,712,314 | <p>Try to use <strong>MySQLdb.cursors.SSDictCursor</strong></p>
<pre><code>con = MySQLdb.connect(host=host,
user=user,
passwd=pwd,
charset=charset,
port=port,
cursorclass=MySQLdb.cursors.SSDictCursor);
cur = con.cursor()
cur.execute("select f1, f2 from table")
for row in cur:
print row['f1'], row['f2']
</code></pre>
| 1 | 2013-09-10T06:49:18Z | [
"python",
"mysql"
] |
How to get a row-by-row MySQL ResultSet in python | 337,479 | <p>MySQL ResultSets are by default retrieved completely from the server before any work can be done. In cases of huge result sets this becomes unusable. I would like instead to actually retrieve the rows one by one from the server.</p>
<p>In Java, following the instructions <a href="http://dev.mysql.com/doc/refman/5.1/en/connector-j-reference-implementation-notes.html">here</a> (under "ResultSet"), I create a statement like this:</p>
<pre><code>stmt = conn.createStatement(java.sql.ResultSet.TYPE_FORWARD_ONLY,
java.sql.ResultSet.CONCUR_READ_ONLY);
stmt.setFetchSize(Integer.MIN_VALUE);
</code></pre>
<p>This works nicely in Java. My question is: is there a way to do the same in python?</p>
<p>One thing I tried is to limit the query to a 1000 rows at a time, like this:</p>
<pre><code>start_row = 0
while True:
cursor = conn.cursor()
cursor.execute("SELECT item FROM items LIMIT %d,1000" % start_row)
rows = cursor.fetchall()
if not rows:
break
start_row += 1000
# Do something with rows...
</code></pre>
<p>However, this seems to get slower the higher start_row is.</p>
<p>And no, using <code>fetchone()</code> instead of <code>fetchall()</code> doesn't change anything.</p>
<h2>Clarification:</h2>
<p>The naive code I use to reproduce this problem looks like this:</p>
<pre><code>import MySQLdb
conn = MySQLdb.connect(user="user", passwd="password", db="mydb")
cur = conn.cursor()
print "Executing query"
cur.execute("SELECT * FROM bigtable");
print "Starting loop"
row = cur.fetchone()
while row is not None:
print ", ".join([str(c) for c in row])
row = cur.fetchone()
cur.close()
conn.close()
</code></pre>
<p>On a ~700,000 rows table, this code runs quickly. But on a ~9,000,000 rows table it prints "Executing Query" and then hangs for a long long time. That is why it makes no difference if I use <code>fetchone()</code> or <code>fetchall()</code>.</p>
| 41 | 2008-12-03T15:23:49Z | 26,559,000 | <p>I found the best results mixing a bit from some of the other answers. </p>
<p>This included setting <code>cursorclass=MySQLdb.cursors.SSDictCursor</code> (for MySQLdb) or <code>pymysql.cursors.SSDictCursor</code> (for PyMySQL) as part of the connection settings. This will let the server hold the query/results (the "SS" stands for server side as opposed to the default cursor which brings the results client side) and build a dictionary out of each row (e.g. {'id': 1, 'name': 'Cookie Monster'}). </p>
<p>Then to loop through the rows, there was an infinite loop in both Python 2.7 and 3.4 caused by <code>while rows is not None</code> because even when <code>cur.fetchmany(size=10000)</code> was called and there were no results left, the method returned an empty list (<code>[]</code>) instead of None. </p>
<p>Actual example:</p>
<pre><code>query = """SELECT * FROM my_table"""
conn = pymysql.connect(host=MYSQL_CREDENTIALS['host'], user=MYSQL_CREDENTIALS['user'],
passwd=MYSQL_CREDENTIALS['passwd'], charset='utf8', cursorclass = pymysql.cursors.SSDictCursor)
cur = conn.cursor()
results = cur.execute(query)
rows = cur.fetchmany(size=100)
while rows:
for row in rows:
process(row)
rows = cur.fetchmany(size=100)
cur.close()
conn.close()
</code></pre>
| 0 | 2014-10-25T03:16:23Z | [
"python",
"mysql"
] |
Dynamic Keyword Arguments in Python? | 337,688 | <p>Does python have the ability to create dynamic keywords?</p>
<p>For example:</p>
<pre><code>qset.filter(min_price__usd__range=(min_price, max_price))
</code></pre>
<p>I want to be able to change the <strong>usd</strong> part based on a selected currency.</p>
| 25 | 2008-12-03T16:12:22Z | 337,714 | <p>Yes, It does. Use <code>**kwargs</code> in a function definition.</p>
<p>Example:</p>
<pre><code>def f(**kwargs):
print kwargs.keys()
f(a=2, b="b") # -> ['a', 'b']
f(**{'d'+'e': 1}) # -> ['de']
</code></pre>
<p>But why do you need that?</p>
| 30 | 2008-12-03T16:19:03Z | [
"python"
] |
Dynamic Keyword Arguments in Python? | 337,688 | <p>Does python have the ability to create dynamic keywords?</p>
<p>For example:</p>
<pre><code>qset.filter(min_price__usd__range=(min_price, max_price))
</code></pre>
<p>I want to be able to change the <strong>usd</strong> part based on a selected currency.</p>
| 25 | 2008-12-03T16:12:22Z | 337,727 | <p>Yes, sort of.
In your filter method you can declare a wildcard variable that collects all the unknown <a href="http://www.python.org/doc/2.5.2/tut/node6.html#SECTION006720000000000000000" rel="nofollow">keyword arguments</a>. Your method might look like this:</p>
<pre><code>def filter(self, **kwargs):
for key,value in kwargs:
if key.startswith('min_price__') and key.endswith('__range'):
currency = key.replace('min_price__', '').replace('__range','')
rate = self.current_conversion_rates[currency]
self.setCurrencyRange(value[0]*rate, value[1]*rate)
</code></pre>
| 0 | 2008-12-03T16:21:43Z | [
"python"
] |
Dynamic Keyword Arguments in Python? | 337,688 | <p>Does python have the ability to create dynamic keywords?</p>
<p>For example:</p>
<pre><code>qset.filter(min_price__usd__range=(min_price, max_price))
</code></pre>
<p>I want to be able to change the <strong>usd</strong> part based on a selected currency.</p>
| 25 | 2008-12-03T16:12:22Z | 337,733 | <p>You can easily do this by declaring your function like this:</p>
<pre><code>def filter(**kwargs):
</code></pre>
<p>your function will now be passed a dictionary called kwargs that contains the keywords and values passed to your function. Note that, syntactically, the word <code>kwargs</code> is meaningless; the <code>**</code> is what causes the dynamic keyword behavior.</p>
<p>You can also do the reverse. If you are calling a function, and you have a dictionary that corresponds to the arguments, you can do</p>
<pre><code>someFunction(**theDictionary)
</code></pre>
<p>There is also the lesser used *foo variant, which causes you to receive an array of arguments. This is similar to normal C vararg arrays.</p>
| 10 | 2008-12-03T16:22:38Z | [
"python"
] |
Dynamic Keyword Arguments in Python? | 337,688 | <p>Does python have the ability to create dynamic keywords?</p>
<p>For example:</p>
<pre><code>qset.filter(min_price__usd__range=(min_price, max_price))
</code></pre>
<p>I want to be able to change the <strong>usd</strong> part based on a selected currency.</p>
| 25 | 2008-12-03T16:12:22Z | 337,735 | <p>If I understand what you're asking correctly,</p>
<pre><code>qset.filter(**{
'min_price_' + selected_currency + '_range' :
(min_price, max_price)})
</code></pre>
<p>does what you need.</p>
| 19 | 2008-12-03T16:22:51Z | [
"python"
] |
Python, Popen and select - waiting for a process to terminate or a timeout | 337,863 | <p>I run a subprocess using:</p>
<pre><code> p = subprocess.Popen("subprocess",
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
stdin=subprocess.PIPE)
</code></pre>
<p>This subprocess could either exit immediately with an error on stderr, or keep running. I want to detect either of these conditions - the latter by waiting for several seconds.</p>
<p>I tried this:</p>
<pre><code> SECONDS_TO_WAIT = 10
select.select([],
[p.stdout, p.stderr],
[p.stdout, p.stderr],
SECONDS_TO_WAIT)
</code></pre>
<p>but it just returns:</p>
<pre><code> ([],[],[])
</code></pre>
<p>on either condition. What can I do?</p>
| 21 | 2008-12-03T16:53:17Z | 337,912 | <p>Have you tried using the Popen.Poll() method. You could just do this:</p>
<pre><code>p = subprocess.Popen("subprocess",
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
stdin=subprocess.PIPE)
time.sleep(SECONDS_TO_WAIT)
retcode = p.poll()
if retcode is not None:
# process has terminated
</code></pre>
<p>This will cause you to always wait 10 seconds, but if the failure case is rare this would be amortized over all the success cases.</p>
<hr>
<p>Edit:</p>
<p>How about:</p>
<pre><code>t_nought = time.time()
seconds_passed = 0
while(p.poll() is not None and seconds_passed < 10):
seconds_passed = time.time() - t_nought
if seconds_passed >= 10:
#TIMED OUT
</code></pre>
<p>This has the ugliness of being a busy wait, but I think it accomplishes what you want.</p>
<p>Additionally looking at the select call documentation again I think you may want to change it as follows:</p>
<pre><code>SECONDS_TO_WAIT = 10
select.select([p.stderr],
[],
[p.stdout, p.stderr],
SECONDS_TO_WAIT)
</code></pre>
<p>Since you would typically want to read from stderr, you want to know when it has something available to read (ie the failure case).</p>
<p>I hope this helps.</p>
| 15 | 2008-12-03T17:06:30Z | [
"python",
"select",
"timeout",
"subprocess",
"popen"
] |
Python, Popen and select - waiting for a process to terminate or a timeout | 337,863 | <p>I run a subprocess using:</p>
<pre><code> p = subprocess.Popen("subprocess",
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
stdin=subprocess.PIPE)
</code></pre>
<p>This subprocess could either exit immediately with an error on stderr, or keep running. I want to detect either of these conditions - the latter by waiting for several seconds.</p>
<p>I tried this:</p>
<pre><code> SECONDS_TO_WAIT = 10
select.select([],
[p.stdout, p.stderr],
[p.stdout, p.stderr],
SECONDS_TO_WAIT)
</code></pre>
<p>but it just returns:</p>
<pre><code> ([],[],[])
</code></pre>
<p>on either condition. What can I do?</p>
| 21 | 2008-12-03T16:53:17Z | 338,079 | <p>Using <em>select</em> and sleeping doesn't really make much sense. <em>select</em> (or any kernel polling mechanism) is inherently useful for asynchronous programming, but your example is synchronous. So either rewrite your code to use the normal blocking fashion or consider using Twisted:</p>
<pre><code>from twisted.internet.utils import getProcessOutputAndValue
from twisted.internet import reactor
def stop(r):
reactor.stop()
def eb(reason):
reason.printTraceback()
def cb(result):
stdout, stderr, exitcode = result
# do something
getProcessOutputAndValue('/bin/someproc', []
).addCallback(cb).addErrback(eb).addBoth(stop)
reactor.run()
</code></pre>
<p>Incidentally, there is a safer way of doing this with Twisted by writing your own ProcessProtocol:</p>
<p><a href="http://twistedmatrix.com/projects/core/documentation/howto/process.html" rel="nofollow">http://twistedmatrix.com/projects/core/documentation/howto/process.html</a></p>
| 1 | 2008-12-03T17:52:16Z | [
"python",
"select",
"timeout",
"subprocess",
"popen"
] |
Python, Popen and select - waiting for a process to terminate or a timeout | 337,863 | <p>I run a subprocess using:</p>
<pre><code> p = subprocess.Popen("subprocess",
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
stdin=subprocess.PIPE)
</code></pre>
<p>This subprocess could either exit immediately with an error on stderr, or keep running. I want to detect either of these conditions - the latter by waiting for several seconds.</p>
<p>I tried this:</p>
<pre><code> SECONDS_TO_WAIT = 10
select.select([],
[p.stdout, p.stderr],
[p.stdout, p.stderr],
SECONDS_TO_WAIT)
</code></pre>
<p>but it just returns:</p>
<pre><code> ([],[],[])
</code></pre>
<p>on either condition. What can I do?</p>
| 21 | 2008-12-03T16:53:17Z | 339,655 | <p>If, as you said in the comments above, you're just tweaking the output each time and re-running the command, would something like the following work?</p>
<pre><code>from threading import Timer
import subprocess
WAIT_TIME = 10.0
def check_cmd(cmd):
p = subprocess.Popen(cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
def _check():
if p.poll()!=0:
print cmd+" did not quit within the given time period."
# check whether the given process has exited WAIT_TIME
# seconds from now
Timer(WAIT_TIME, _check).start()
check_cmd('echo')
check_cmd('python')
</code></pre>
<p>The code above, when run, outputs:</p>
<pre><code>python did not quit within the given time period.
</code></pre>
<p>The only downside of the above code that I can think of is the potentially overlapping processes as you keep running check_cmd.</p>
| 1 | 2008-12-04T05:19:41Z | [
"python",
"select",
"timeout",
"subprocess",
"popen"
] |
Python, Popen and select - waiting for a process to terminate or a timeout | 337,863 | <p>I run a subprocess using:</p>
<pre><code> p = subprocess.Popen("subprocess",
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
stdin=subprocess.PIPE)
</code></pre>
<p>This subprocess could either exit immediately with an error on stderr, or keep running. I want to detect either of these conditions - the latter by waiting for several seconds.</p>
<p>I tried this:</p>
<pre><code> SECONDS_TO_WAIT = 10
select.select([],
[p.stdout, p.stderr],
[p.stdout, p.stderr],
SECONDS_TO_WAIT)
</code></pre>
<p>but it just returns:</p>
<pre><code> ([],[],[])
</code></pre>
<p>on either condition. What can I do?</p>
| 21 | 2008-12-03T16:53:17Z | 1,035,488 | <p>This is what i came up with. Works when you need and don't need to timeout on thep process, but with a semi-busy loop.</p>
<pre><code>def runCmd(cmd, timeout=None):
'''
Will execute a command, read the output and return it back.
@param cmd: command to execute
@param timeout: process timeout in seconds
@return: a tuple of three: first stdout, then stderr, then exit code
@raise OSError: on missing command or if a timeout was reached
'''
ph_out = None # process output
ph_err = None # stderr
ph_ret = None # return code
p = subprocess.Popen(cmd, shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
# if timeout is not set wait for process to complete
if not timeout:
ph_ret = p.wait()
else:
fin_time = time.time() + timeout
while p.poll() == None and fin_time > time.time():
time.sleep(1)
# if timeout reached, raise an exception
if fin_time < time.time():
# starting 2.6 subprocess has a kill() method which is preferable
# p.kill()
os.kill(p.pid, signal.SIGKILL)
raise OSError("Process timeout has been reached")
ph_ret = p.returncode
ph_out, ph_err = p.communicate()
return (ph_out, ph_err, ph_ret)
</code></pre>
| 8 | 2009-06-23T21:58:58Z | [
"python",
"select",
"timeout",
"subprocess",
"popen"
] |
Python, Popen and select - waiting for a process to terminate or a timeout | 337,863 | <p>I run a subprocess using:</p>
<pre><code> p = subprocess.Popen("subprocess",
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
stdin=subprocess.PIPE)
</code></pre>
<p>This subprocess could either exit immediately with an error on stderr, or keep running. I want to detect either of these conditions - the latter by waiting for several seconds.</p>
<p>I tried this:</p>
<pre><code> SECONDS_TO_WAIT = 10
select.select([],
[p.stdout, p.stderr],
[p.stdout, p.stderr],
SECONDS_TO_WAIT)
</code></pre>
<p>but it just returns:</p>
<pre><code> ([],[],[])
</code></pre>
<p>on either condition. What can I do?</p>
| 21 | 2008-12-03T16:53:17Z | 5,955,784 | <p>Here is a nice example:</p>
<pre><code>from threading import Timer
from subprocess import Popen, PIPE
def kill_proc():
proc.kill()
proc = Popen("ping 127.0.0.1", shell=True)
t = Timer(60, kill_proc)
t.start()
proc.wait()
</code></pre>
| 2 | 2011-05-10T20:03:53Z | [
"python",
"select",
"timeout",
"subprocess",
"popen"
] |
Python, Popen and select - waiting for a process to terminate or a timeout | 337,863 | <p>I run a subprocess using:</p>
<pre><code> p = subprocess.Popen("subprocess",
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
stdin=subprocess.PIPE)
</code></pre>
<p>This subprocess could either exit immediately with an error on stderr, or keep running. I want to detect either of these conditions - the latter by waiting for several seconds.</p>
<p>I tried this:</p>
<pre><code> SECONDS_TO_WAIT = 10
select.select([],
[p.stdout, p.stderr],
[p.stdout, p.stderr],
SECONDS_TO_WAIT)
</code></pre>
<p>but it just returns:</p>
<pre><code> ([],[],[])
</code></pre>
<p>on either condition. What can I do?</p>
| 21 | 2008-12-03T16:53:17Z | 13,335,270 | <h2>Python 3.3</h2>
<pre><code>import subprocess as sp
try:
sp.check_call(["/subprocess"], timeout=10,
stdin=sp.DEVNULL, stdout=sp.DEVNULL, stderr=sp.DEVNULL)
except sp.TimeoutError:
# timeout (the subprocess is killed at this point)
except sp.CalledProcessError:
# subprocess failed before timeout
else:
# subprocess ended successfully before timeout
</code></pre>
<p>See <a href="http://docs.python.org/3/library/subprocess.html#subprocess.TimeoutExpired" rel="nofollow">TimeoutExpired docs</a>.</p>
| 0 | 2012-11-11T20:44:32Z | [
"python",
"select",
"timeout",
"subprocess",
"popen"
] |
Python, Popen and select - waiting for a process to terminate or a timeout | 337,863 | <p>I run a subprocess using:</p>
<pre><code> p = subprocess.Popen("subprocess",
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
stdin=subprocess.PIPE)
</code></pre>
<p>This subprocess could either exit immediately with an error on stderr, or keep running. I want to detect either of these conditions - the latter by waiting for several seconds.</p>
<p>I tried this:</p>
<pre><code> SECONDS_TO_WAIT = 10
select.select([],
[p.stdout, p.stderr],
[p.stdout, p.stderr],
SECONDS_TO_WAIT)
</code></pre>
<p>but it just returns:</p>
<pre><code> ([],[],[])
</code></pre>
<p>on either condition. What can I do?</p>
| 21 | 2008-12-03T16:53:17Z | 15,342,597 | <p>This is a paraphrase on Evan's answer, but it takes into account the following :</p>
<ol>
<li>Explicitly canceling the Timer object : if the Timer interval would be long and the process will exit by its "own will" , this could hang your script :(</li>
<li><p>There is an intrinsic race in the Timer approach (the timer attempt killing the process <em>just after</em> the process has died and this on Windows will raise an exception). </p>
<pre><code> DEVNULL = open(os.devnull, "wb")
process = Popen("c:/myExe.exe", stdout=DEVNULL) # no need for stdout
def kill_process():
""" Kill process helper"""
try:
process.kill()
except OSError:
pass # Swallow the error
timer = Timer(timeout_in_sec, kill_process)
timer.start()
process.wait()
timer.cancel()
</code></pre></li>
</ol>
| 0 | 2013-03-11T15:36:08Z | [
"python",
"select",
"timeout",
"subprocess",
"popen"
] |
Python subprocess.call() fails when using pythonw.exe | 337,870 | <p>I have some Python code that works correctly when I use python.exe to run it, but fails if I use pythonw.exe.</p>
<pre>
def runStuff(commandLine):
outputFileName = 'somefile.txt'
outputFile = open(outputFileName, "w")
try:
result = subprocess.call(commandLine, shell=True, stdout=outputFile)
except:
print 'Exception thrown:', str(sys.exc_info()[1])
myThread = threading.Thread(None, target=runStuff, commandLine=['whatever...'])
myThread.start()
</pre>
<p>The message I get is:</p>
<pre>
Exception thrown: [Error 6] The handle is invalid
</pre>
<p>However, if I don't specify the 'stdout' parameter, subprocess.call() starts okay.</p>
<p>I can see that pythonw.exe might be redirecting output itself, but I can't see why I'm blocked from specifying stdout for a new thread.</p>
| 5 | 2008-12-03T16:54:17Z | 337,990 | <p><code>sys.stdin</code> and <code>sys.stdout</code> handles are invalid because pythonw does not provide console support as it runs as a deamon, so default arguments of <code>subprocess.call()</code> are failing.</p>
<p>Deamon programs close stdin/stdout/stderr purposedly and use logging instead, so that you have to manage this yourself: I would suggest to use subprocess.PIPE.</p>
<p>If you <em>really</em> don't care about what the sub process says for errors and all, you could use <code>os.devnull</code> (I'm not really sure how portable it is?) but I wouldn't recommend that.</p>
| 7 | 2008-12-03T17:26:53Z | [
"python",
"multithreading",
"subprocess"
] |
Python subprocess.call() fails when using pythonw.exe | 337,870 | <p>I have some Python code that works correctly when I use python.exe to run it, but fails if I use pythonw.exe.</p>
<pre>
def runStuff(commandLine):
outputFileName = 'somefile.txt'
outputFile = open(outputFileName, "w")
try:
result = subprocess.call(commandLine, shell=True, stdout=outputFile)
except:
print 'Exception thrown:', str(sys.exc_info()[1])
myThread = threading.Thread(None, target=runStuff, commandLine=['whatever...'])
myThread.start()
</pre>
<p>The message I get is:</p>
<pre>
Exception thrown: [Error 6] The handle is invalid
</pre>
<p>However, if I don't specify the 'stdout' parameter, subprocess.call() starts okay.</p>
<p>I can see that pythonw.exe might be redirecting output itself, but I can't see why I'm blocked from specifying stdout for a new thread.</p>
| 5 | 2008-12-03T16:54:17Z | 386,343 | <p>For the record, my code now looks like this:</p>
<pre><code>def runStuff(commandLine):
outputFileName = 'somefile.txt'
outputFile = open(outputFileName, "w")
if guiMode:
result = subprocess.call(commandLine, shell=True, stdout=outputFile, stderr=subprocess.STDOUT)
else:
proc = subprocess.Popen(commandLine, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.PIPE)
proc.stdin.close()
proc.wait()
result = proc.returncode
outputFile.write(proc.stdout.read())
</code></pre>
<p>Note that, due to an apparent bug in the subprocess module, the call to Popen() has to specify a pipe for stdin as well, which we close immediately afterwards.</p>
| 6 | 2008-12-22T14:19:21Z | [
"python",
"multithreading",
"subprocess"
] |
Python subprocess.call() fails when using pythonw.exe | 337,870 | <p>I have some Python code that works correctly when I use python.exe to run it, but fails if I use pythonw.exe.</p>
<pre>
def runStuff(commandLine):
outputFileName = 'somefile.txt'
outputFile = open(outputFileName, "w")
try:
result = subprocess.call(commandLine, shell=True, stdout=outputFile)
except:
print 'Exception thrown:', str(sys.exc_info()[1])
myThread = threading.Thread(None, target=runStuff, commandLine=['whatever...'])
myThread.start()
</pre>
<p>The message I get is:</p>
<pre>
Exception thrown: [Error 6] The handle is invalid
</pre>
<p>However, if I don't specify the 'stdout' parameter, subprocess.call() starts okay.</p>
<p>I can see that pythonw.exe might be redirecting output itself, but I can't see why I'm blocked from specifying stdout for a new thread.</p>
| 5 | 2008-12-03T16:54:17Z | 25,453,133 | <p>This is an old question, but the same problem happened with pyInstaller too. </p>
<p>In the truth, this will happen with any framework that converts code in python for exe without console.</p>
<p>In my tests, I observed that if I use the flag "console=True" into my spec file (pyInstaller) the error no longer occurs. .</p>
<p>The solution was follow the tip of Piotr Lesnicki.</p>
| 2 | 2014-08-22T18:09:19Z | [
"python",
"multithreading",
"subprocess"
] |
Windows build for PyLucene+JCC on python 2.6 | 338,008 | <p>Where can I download a PyLucene+JCC Windows build compiled for python 2.6?</p>
<p>Jose</p>
| 6 | 2008-12-03T17:31:46Z | 749,783 | <p>you might want to see <a href="http://mail-archives.apache.org/mod%5Fmbox/lucene-pylucene-dev/200902.mbox/%[email protected]%3E" rel="nofollow">this recent mailing list post</a> and the related thread. There's also a <a href="http://markmail.org/message/d6tfni5sdqywwfoy" rel="nofollow">pylucene-dev</a> thread that seems apropos. Unfortunately, none of these things have what you want; you'll still have to build it yourself. </p>
<p>If you're really feeling charitable, you can publish the steps + binaries once you figure it out, but I don't know. </p>
| 1 | 2009-04-14T23:57:55Z | [
"python",
"windows",
"pylucene",
"jcc"
] |
Windows build for PyLucene+JCC on python 2.6 | 338,008 | <p>Where can I download a PyLucene+JCC Windows build compiled for python 2.6?</p>
<p>Jose</p>
| 6 | 2008-12-03T17:31:46Z | 1,108,426 | <p>Not tested but there appears to be an egg here:</p>
<p><a href="http://code.google.com/p/pylucene-win32-binary/" rel="nofollow">http://code.google.com/p/pylucene-win32-binary/</a></p>
| 2 | 2009-07-10T08:40:48Z | [
"python",
"windows",
"pylucene",
"jcc"
] |
Windows build for PyLucene+JCC on python 2.6 | 338,008 | <p>Where can I download a PyLucene+JCC Windows build compiled for python 2.6?</p>
<p>Jose</p>
| 6 | 2008-12-03T17:31:46Z | 1,201,943 | <p>I ended up using <a href="http://lucene.apache.org/solr/" rel="nofollow">solr</a> and interfacing it using XML/JSON.</p>
| 3 | 2009-07-29T17:51:26Z | [
"python",
"windows",
"pylucene",
"jcc"
] |
How do I use IPython as my Emacs Python interpreter? | 338,103 | <p>I'm running Emacs 22.1.1 and IPython 0.9.1 on OS X and I'd like to be able to run lines/methods/snippets of Python code from my current buffer on demand inside an IPython interpreter.</p>
<p>What do I need to do to get this working?</p>
| 11 | 2008-12-03T17:56:57Z | 1,607,236 | <p>also ipython wont load with the official python.el being used with emacs 23.1.1</p>
| 4 | 2009-10-22T13:31:59Z | [
"python",
"osx",
"configuration",
"emacs",
"ipython"
] |
How do I use IPython as my Emacs Python interpreter? | 338,103 | <p>I'm running Emacs 22.1.1 and IPython 0.9.1 on OS X and I'd like to be able to run lines/methods/snippets of Python code from my current buffer on demand inside an IPython interpreter.</p>
<p>What do I need to do to get this working?</p>
| 11 | 2008-12-03T17:56:57Z | 26,383,574 | <p>This version of emacs for mac:</p>
<p><a href="http://emacsformacosx.com" rel="nofollow">http://emacsformacosx.com</a></p>
<p>comes with package.el pre-installed. This allows you to automatically install emacs packages. There is a package called ein:</p>
<p><a href="http://tkf.github.io/emacs-ipython-notebook/" rel="nofollow">http://tkf.github.io/emacs-ipython-notebook/</a></p>
<p>which makes it easy to interact with ipython from emacs (including notebooks). </p>
<p>However, as of version 24.3 of the emacs above, ein is not in the default package repository. If you add more repositories, as per:</p>
<p><a href="http://www.emacswiki.org/emacs/ELPA" rel="nofollow">http://www.emacswiki.org/emacs/ELPA</a></p>
<p>i.e., add this to your ~/.emacs file:</p>
<pre><code>(setq package-archives '(("gnu" . "http://elpa.gnu.org/packages/")
("marmalade" . "http://marmalade-repo.org/packages/")
("melpa" . "http://melpa.milkbox.net/packages/")))
</code></pre>
<p>then call</p>
<pre><code>M-x package-refresh-contents
</code></pre>
<p>you will now be able to add ein with:</p>
<pre><code>M-x package-install <ret> ein
</code></pre>
<p>alas the MELPA version of ein does not work with ipython > 1.x so if you are using ipython 2.x, you need a newer build of ein:</p>
<p><a href="https://github.com/tkf/emacs-ipython-notebook/issues/137" rel="nofollow">https://github.com/tkf/emacs-ipython-notebook/issues/137</a></p>
<p>so clone that:</p>
<pre><code>git clone https://github.com/millejoh/emacs-ipython-notebook.git
</code></pre>
<p>copy the lisp sub directory somewhere sensible:</p>
<pre><code>cp -r emacs-ipython-notebook/lisp ~/.emacs.d/einv2
</code></pre>
<p>then add it to your emacs load path and load it, by adding this to your ~/.emacs:</p>
<pre><code>(add-to-list 'load-path "~/.emacs.d/einv2")
(require 'ein)
</code></pre>
<p>finally, get rid of the old ein, which will leave the dependencies in place:</p>
<pre><code>M-x package-list-packages
</code></pre>
<p>scroll to ein in the package list, then:</p>
<pre><code>M-x package-menu-mark-delete
M-x package-menu-execute
</code></pre>
<p>Restart emacs and you can connect to your ipython notebook server:</p>
<pre><code>M-x ein:notebooklist-open
</code></pre>
| 2 | 2014-10-15T13:16:17Z | [
"python",
"osx",
"configuration",
"emacs",
"ipython"
] |
How do I use IPython as my Emacs Python interpreter? | 338,103 | <p>I'm running Emacs 22.1.1 and IPython 0.9.1 on OS X and I'd like to be able to run lines/methods/snippets of Python code from my current buffer on demand inside an IPython interpreter.</p>
<p>What do I need to do to get this working?</p>
| 11 | 2008-12-03T17:56:57Z | 26,387,688 | <p>python-mode.el supports IPython natively.</p>
<p>Just make sure shebang doesn't point to another interpreter. </p>
<p>In this case:</p>
<ul>
<li>either call a command with ending "-ipython", which will override shebang</li>
<li>customize "ipython" as default interpreter and set `py-force-py-shell-name-p'. This might be done also via menu
Python/.../Switches</li>
</ul>
| 0 | 2014-10-15T16:38:54Z | [
"python",
"osx",
"configuration",
"emacs",
"ipython"
] |
Setting the width of a wxPython TextCtrl in number of characters | 338,217 | <p>I have a <code>TextCtrl</code> in my wxPython program and I'd like to set its width to exactly 3 characters. However, the only way to set its size manually accepts only numbers of pixels. Is there any way to specify characters instead of pixels?</p>
| 7 | 2008-12-03T18:27:25Z | 338,275 | <p>Realize that most fonts are proportional, which means that each character may take a different width. WWW and lll are both 3 characters, but they will require vastly different sizes of text box. Some fonts, such as Courier, are designed to be fixed width and will not have this problem. Unfortunately you may not have any control over which font is selected in the text box.</p>
<p>If you still want to try this, the key is to get the width of a character in pixels, multiply it by the number of characters, then add some padding for the borders around the characters. You may find this to be a good starting point:</p>
<p><a href="http://docs.wxwidgets.org/stable/wx_wxdc.html#wxdcgetpartialtextextents" rel="nofollow">http://docs.wxwidgets.org/stable/wx_wxdc.html#wxdcgetpartialtextextents</a></p>
<p>or, as litb suggests:</p>
<p><a href="http://docs.wxwidgets.org/2.4/wx_wxwindow.html#wxwindowgettextextent" rel="nofollow">http://docs.wxwidgets.org/2.4/wx_wxwindow.html#wxwindowgettextextent</a></p>
| 2 | 2008-12-03T18:42:41Z | [
"python",
"wxpython"
] |
Setting the width of a wxPython TextCtrl in number of characters | 338,217 | <p>I have a <code>TextCtrl</code> in my wxPython program and I'd like to set its width to exactly 3 characters. However, the only way to set its size manually accepts only numbers of pixels. Is there any way to specify characters instead of pixels?</p>
| 7 | 2008-12-03T18:27:25Z | 338,287 | <p>There doesn't seem to be a way. You can, however, use <code>wxWindow::GetTextExtent</code>. This is C++ code, but can be easily adapted to wxPython:</p>
<pre><code>int x, y;
textCtrl->GetTextExtent(wxT("T"), &x, &y);
textCtrl->SetMinSize(wxSize(x * N + 10, -1));
textCtrl->SetMaxSize(wxSize(x * N + 10, -1));
/* re-layout the children*/
this->Layout();
/* alternative to Layout, will resize the parent to fit around the new
* size of the text control. */
this->GetSizer()->SetSizeHints(this);
this->Fit();
</code></pre>
<p>This is, you take the size of a reasonable width character (fonts may have variable width characters) and multiply it properly, adding some small value to account for native padding (say, 10px).</p>
| 3 | 2008-12-03T18:44:38Z | [
"python",
"wxpython"
] |
TimedRotatingFileHandler Changing File Name? | 338,450 | <p>I am trying to implement the python logging handler called TimedRotatingFileHandler. </p>
<p>When it rolls over to midnight it appends the current day in the form: "YYYY-MM-DD".</p>
<pre><code>LOGGING_MSG_FORMAT = '%(name)-14s > [%(levelname)s] [%(asctime)s] : %(message)s'
LOGGING_DATE_FORMAT = '%Y-%m-%d %H:%M:%S'
logging.basicConfig(
level=logging.DEBUG,
format=LOGGING_MSG_FORMAT,
datefmt=LOGGING_DATE_FORMAT
)
root_logger = logging.getLogger('')
logger = logging.handlers.TimedRotatingFileHandler("C:\\logs\\Rotate_Test",'midnight',1)
root_logger.addHandler(logger)
while True:
daemon_logger = logging.getLogger('TEST')
daemon_logger.info("SDFKLDSKLFFJKLSDD")
time.sleep(60)
</code></pre>
<p>The first log file created is called just "Rotate_Test" then once it rolls over to the next day it changes the file name to: "Rotate_Test.YYYY-MM-DD" Where YYYY-MM-DD is the current day.</p>
<p>How can i change how it alters the filename? I googled and looked at the API and found pretty much nothing.</p>
| 5 | 2008-12-03T19:37:51Z | 338,566 | <p>"How can i change how it alters the filename?"</p>
<p>Since it isn't documented, I elected to read the source. This is what I concluded from reading the source of <code>logging/handlers.py</code></p>
<pre><code>handler = logging.handlers.TimedRotatingFileHandler("C:\\isis_ops\\logs\\Rotate_Test",'midnight',1)
handler.suffix = "%Y-%m-%d" # or anything else that strftime will allow
root_logger.addHandler(handler)
</code></pre>
<p>The suffix is the formatting string.</p>
| 15 | 2008-12-03T20:21:41Z | [
"python",
"logging"
] |
TimedRotatingFileHandler Changing File Name? | 338,450 | <p>I am trying to implement the python logging handler called TimedRotatingFileHandler. </p>
<p>When it rolls over to midnight it appends the current day in the form: "YYYY-MM-DD".</p>
<pre><code>LOGGING_MSG_FORMAT = '%(name)-14s > [%(levelname)s] [%(asctime)s] : %(message)s'
LOGGING_DATE_FORMAT = '%Y-%m-%d %H:%M:%S'
logging.basicConfig(
level=logging.DEBUG,
format=LOGGING_MSG_FORMAT,
datefmt=LOGGING_DATE_FORMAT
)
root_logger = logging.getLogger('')
logger = logging.handlers.TimedRotatingFileHandler("C:\\logs\\Rotate_Test",'midnight',1)
root_logger.addHandler(logger)
while True:
daemon_logger = logging.getLogger('TEST')
daemon_logger.info("SDFKLDSKLFFJKLSDD")
time.sleep(60)
</code></pre>
<p>The first log file created is called just "Rotate_Test" then once it rolls over to the next day it changes the file name to: "Rotate_Test.YYYY-MM-DD" Where YYYY-MM-DD is the current day.</p>
<p>How can i change how it alters the filename? I googled and looked at the API and found pretty much nothing.</p>
| 5 | 2008-12-03T19:37:51Z | 338,783 | <p>Thanks.</p>
<p>I looked at the source.</p>
<p>There isn't really a way to change its form. Since manipulating suffix, only appends to the end of the file name. Ether way, there is no way real way to manipulate the full file name, what i was hoping for was where you can declare a file mask, and when it does the "RollOver" it will create a new file name based on the file mask. I am just going to go back to my original idea, was to just kill the whole logging subsystem and reinitialize it with the new file name when it RollsOver.</p>
<p>Thanks Tho.</p>
| 1 | 2008-12-03T21:29:57Z | [
"python",
"logging"
] |
TimedRotatingFileHandler Changing File Name? | 338,450 | <p>I am trying to implement the python logging handler called TimedRotatingFileHandler. </p>
<p>When it rolls over to midnight it appends the current day in the form: "YYYY-MM-DD".</p>
<pre><code>LOGGING_MSG_FORMAT = '%(name)-14s > [%(levelname)s] [%(asctime)s] : %(message)s'
LOGGING_DATE_FORMAT = '%Y-%m-%d %H:%M:%S'
logging.basicConfig(
level=logging.DEBUG,
format=LOGGING_MSG_FORMAT,
datefmt=LOGGING_DATE_FORMAT
)
root_logger = logging.getLogger('')
logger = logging.handlers.TimedRotatingFileHandler("C:\\logs\\Rotate_Test",'midnight',1)
root_logger.addHandler(logger)
while True:
daemon_logger = logging.getLogger('TEST')
daemon_logger.info("SDFKLDSKLFFJKLSDD")
time.sleep(60)
</code></pre>
<p>The first log file created is called just "Rotate_Test" then once it rolls over to the next day it changes the file name to: "Rotate_Test.YYYY-MM-DD" Where YYYY-MM-DD is the current day.</p>
<p>How can i change how it alters the filename? I googled and looked at the API and found pretty much nothing.</p>
| 5 | 2008-12-03T19:37:51Z | 340,429 | <p>Just an update, i ended up going a different approach.</p>
<p>The easiest way i found to modify the file output, was to simply use a FileHandler, then when it is time to do a roll over.</p>
<p>I do this:</p>
<pre><code>if(current_time > old_time):
for each in logging.getLogger('Debug').handlers:
each.stream = open("C:\\NewOutput", 'a')
</code></pre>
<p>Thats the gist of it. It took alot of poking and looking around but modifying the stream is the easiest way to do so.</p>
<p>:)</p>
| 1 | 2008-12-04T12:26:26Z | [
"python",
"logging"
] |
TimedRotatingFileHandler Changing File Name? | 338,450 | <p>I am trying to implement the python logging handler called TimedRotatingFileHandler. </p>
<p>When it rolls over to midnight it appends the current day in the form: "YYYY-MM-DD".</p>
<pre><code>LOGGING_MSG_FORMAT = '%(name)-14s > [%(levelname)s] [%(asctime)s] : %(message)s'
LOGGING_DATE_FORMAT = '%Y-%m-%d %H:%M:%S'
logging.basicConfig(
level=logging.DEBUG,
format=LOGGING_MSG_FORMAT,
datefmt=LOGGING_DATE_FORMAT
)
root_logger = logging.getLogger('')
logger = logging.handlers.TimedRotatingFileHandler("C:\\logs\\Rotate_Test",'midnight',1)
root_logger.addHandler(logger)
while True:
daemon_logger = logging.getLogger('TEST')
daemon_logger.info("SDFKLDSKLFFJKLSDD")
time.sleep(60)
</code></pre>
<p>The first log file created is called just "Rotate_Test" then once it rolls over to the next day it changes the file name to: "Rotate_Test.YYYY-MM-DD" Where YYYY-MM-DD is the current day.</p>
<p>How can i change how it alters the filename? I googled and looked at the API and found pretty much nothing.</p>
| 5 | 2008-12-03T19:37:51Z | 1,876,171 | <p>There is another approach to this problem: for example, I need to rotate logs on a daily basis but they must be named with a suffix in the %m%d%Y format...</p>
<p>So I wrote a TimedRotatingFileHandler remix!</p>
<pre><code>try:
import codecs
except ImportError:
codecs = None
import logging.handlers
import time
import os
class MyTimedRotatingFileHandler(logging.handlers.TimedRotatingFileHandler):
def __init__(self,dir_log):
self.dir_log = dir_log
filename = self.dir_log+time.strftime("%m%d%Y")+".txt" #dir_log here MUST be with os.sep on the end
logging.handlers.TimedRotatingFileHandler.__init__(self,filename, when='midnight', interval=1, backupCount=0, encoding=None)
def doRollover(self):
"""
TimedRotatingFileHandler remix - rotates logs on daily basis, and filename of current logfile is time.strftime("%m%d%Y")+".txt" always
"""
self.stream.close()
# get the time that this sequence started at and make it a TimeTuple
t = self.rolloverAt - self.interval
timeTuple = time.localtime(t)
self.baseFilename = self.dir_log+time.strftime("%m%d%Y")+".txt"
if self.encoding:
self.stream = codecs.open(self.baseFilename, 'w', self.encoding)
else:
self.stream = open(self.baseFilename, 'w')
self.rolloverAt = self.rolloverAt + self.interval
</code></pre>
| 2 | 2009-12-09T19:18:05Z | [
"python",
"logging"
] |
TimedRotatingFileHandler Changing File Name? | 338,450 | <p>I am trying to implement the python logging handler called TimedRotatingFileHandler. </p>
<p>When it rolls over to midnight it appends the current day in the form: "YYYY-MM-DD".</p>
<pre><code>LOGGING_MSG_FORMAT = '%(name)-14s > [%(levelname)s] [%(asctime)s] : %(message)s'
LOGGING_DATE_FORMAT = '%Y-%m-%d %H:%M:%S'
logging.basicConfig(
level=logging.DEBUG,
format=LOGGING_MSG_FORMAT,
datefmt=LOGGING_DATE_FORMAT
)
root_logger = logging.getLogger('')
logger = logging.handlers.TimedRotatingFileHandler("C:\\logs\\Rotate_Test",'midnight',1)
root_logger.addHandler(logger)
while True:
daemon_logger = logging.getLogger('TEST')
daemon_logger.info("SDFKLDSKLFFJKLSDD")
time.sleep(60)
</code></pre>
<p>The first log file created is called just "Rotate_Test" then once it rolls over to the next day it changes the file name to: "Rotate_Test.YYYY-MM-DD" Where YYYY-MM-DD is the current day.</p>
<p>How can i change how it alters the filename? I googled and looked at the API and found pretty much nothing.</p>
| 5 | 2008-12-03T19:37:51Z | 32,198,288 | <p>You can do this by changing the log suffix as suggested above but you will also need to change the extMatch variable to match the suffix for it to find rotated files:</p>
<pre><code>handler.suffix = "%Y%m%d"
handler.extMatch = re.compile(r"^\d{8}$")
</code></pre>
| 0 | 2015-08-25T07:45:46Z | [
"python",
"logging"
] |
python ImportError No module named | 338,768 | <p>I am very new at Python and I am getting this error:</p>
<pre><code>Traceback (most recent call last):
File "mountain.py", line 28, in ?
from toolkit.interface import interface
ImportError: No module named toolkit.interface
</code></pre>
<p>Python is installed in a local directory:</p>
<p>My directory tree is like this:</p>
<pre><code>(local directory)/site-packages/toolkit/interface.py
</code></pre>
<p>My code is in here </p>
<pre><code>(local directory)/site-packages/toolkit/examples/mountain.py
</code></pre>
<p>To run the example I do <code>python mountain.py</code>, and in the code I have:</p>
<pre><code>from toolkit.interface import interface
</code></pre>
<p>And i get the error that I wrote, I have already checked <code>sys.path</code> and there I have the directory <code>/site-packages</code>, also I have the file <code>__init__.py.bin</code> in the toolkit folder to indicate to Python that this is a package. I also have a <code>__init__.py.bin</code> in the examples directory.</p>
<p>I do not know why Python cannot find the file when it is in <code>sys.path</code>, any ideas? Can be a permissions problem? Do I need execution permission?</p>
| 186 | 2008-12-03T21:26:28Z | 338,790 | <p>To mark a directory as a package you need a file named <code>__init__.py</code>, does this help?</p>
| 11 | 2008-12-03T21:31:53Z | [
"python",
"importerror",
"python-import"
] |
python ImportError No module named | 338,768 | <p>I am very new at Python and I am getting this error:</p>
<pre><code>Traceback (most recent call last):
File "mountain.py", line 28, in ?
from toolkit.interface import interface
ImportError: No module named toolkit.interface
</code></pre>
<p>Python is installed in a local directory:</p>
<p>My directory tree is like this:</p>
<pre><code>(local directory)/site-packages/toolkit/interface.py
</code></pre>
<p>My code is in here </p>
<pre><code>(local directory)/site-packages/toolkit/examples/mountain.py
</code></pre>
<p>To run the example I do <code>python mountain.py</code>, and in the code I have:</p>
<pre><code>from toolkit.interface import interface
</code></pre>
<p>And i get the error that I wrote, I have already checked <code>sys.path</code> and there I have the directory <code>/site-packages</code>, also I have the file <code>__init__.py.bin</code> in the toolkit folder to indicate to Python that this is a package. I also have a <code>__init__.py.bin</code> in the examples directory.</p>
<p>I do not know why Python cannot find the file when it is in <code>sys.path</code>, any ideas? Can be a permissions problem? Do I need execution permission?</p>
| 186 | 2008-12-03T21:26:28Z | 338,858 | <p>Does</p>
<pre><code>(local directory)/site-packages/toolkit
</code></pre>
<p>have a <code>__init__.py</code>?</p>
<p>To make import <em>walk</em> through your directories every directory must have a <code>__init__.py</code> file.</p>
| 33 | 2008-12-03T21:50:15Z | [
"python",
"importerror",
"python-import"
] |
python ImportError No module named | 338,768 | <p>I am very new at Python and I am getting this error:</p>
<pre><code>Traceback (most recent call last):
File "mountain.py", line 28, in ?
from toolkit.interface import interface
ImportError: No module named toolkit.interface
</code></pre>
<p>Python is installed in a local directory:</p>
<p>My directory tree is like this:</p>
<pre><code>(local directory)/site-packages/toolkit/interface.py
</code></pre>
<p>My code is in here </p>
<pre><code>(local directory)/site-packages/toolkit/examples/mountain.py
</code></pre>
<p>To run the example I do <code>python mountain.py</code>, and in the code I have:</p>
<pre><code>from toolkit.interface import interface
</code></pre>
<p>And i get the error that I wrote, I have already checked <code>sys.path</code> and there I have the directory <code>/site-packages</code>, also I have the file <code>__init__.py.bin</code> in the toolkit folder to indicate to Python that this is a package. I also have a <code>__init__.py.bin</code> in the examples directory.</p>
<p>I do not know why Python cannot find the file when it is in <code>sys.path</code>, any ideas? Can be a permissions problem? Do I need execution permission?</p>
| 186 | 2008-12-03T21:26:28Z | 339,220 | <p>Based on your comments to orip's post, I guess this is what happened:</p>
<ol>
<li>You edited <code>__init__.py</code> on windows.</li>
<li>The windows editor added something non-printing, perhaps a carriage-return (end-of-line in Windows is CR/LF; in unix it is LF only), or perhaps a CTRL-Z (windows end-of-file).</li>
<li>You used WinSCP to copy the file to your unix box.</li>
<li>WinSCP thought: "This has something that's not basic text; I'll put a .bin extension to indicate binary data."</li>
<li>The missing <code>__init__.py</code> (now called <code>__init__.py.bin</code>) means python doesn't understand toolkit as a package.</li>
<li>You create <code>__init__.py</code> in the appropriate directory and everything works... ?</li>
</ol>
| 159 | 2008-12-04T00:17:40Z | [
"python",
"importerror",
"python-import"
] |
python ImportError No module named | 338,768 | <p>I am very new at Python and I am getting this error:</p>
<pre><code>Traceback (most recent call last):
File "mountain.py", line 28, in ?
from toolkit.interface import interface
ImportError: No module named toolkit.interface
</code></pre>
<p>Python is installed in a local directory:</p>
<p>My directory tree is like this:</p>
<pre><code>(local directory)/site-packages/toolkit/interface.py
</code></pre>
<p>My code is in here </p>
<pre><code>(local directory)/site-packages/toolkit/examples/mountain.py
</code></pre>
<p>To run the example I do <code>python mountain.py</code>, and in the code I have:</p>
<pre><code>from toolkit.interface import interface
</code></pre>
<p>And i get the error that I wrote, I have already checked <code>sys.path</code> and there I have the directory <code>/site-packages</code>, also I have the file <code>__init__.py.bin</code> in the toolkit folder to indicate to Python that this is a package. I also have a <code>__init__.py.bin</code> in the examples directory.</p>
<p>I do not know why Python cannot find the file when it is in <code>sys.path</code>, any ideas? Can be a permissions problem? Do I need execution permission?</p>
| 186 | 2008-12-03T21:26:28Z | 339,333 | <p>I solved my own problem, I will write a summary of the things that were wrong and the solution:</p>
<p>The file needs to be called exactly <code>__init__.py</code>, if the extension is different such as my case <code>.py.bin</code> then python cannot move through the directories and then it cannot find the modules. To edit the files you need to use a Linux editor, such as vi or nano, if you use a windows editor this will write some hidden characters. </p>
<p>Another problem that was affecting was that I had another python version installed by the root, so if someone is working with a local installation of python, be sure that the python that is running the programs is the local python, to check this just do <code>which python</code>, and see if the executable is the one that is in your local directory. If not change the path but be sure that the local python directory is before than the other python.</p>
| 17 | 2008-12-04T01:11:08Z | [
"python",
"importerror",
"python-import"
] |
python ImportError No module named | 338,768 | <p>I am very new at Python and I am getting this error:</p>
<pre><code>Traceback (most recent call last):
File "mountain.py", line 28, in ?
from toolkit.interface import interface
ImportError: No module named toolkit.interface
</code></pre>
<p>Python is installed in a local directory:</p>
<p>My directory tree is like this:</p>
<pre><code>(local directory)/site-packages/toolkit/interface.py
</code></pre>
<p>My code is in here </p>
<pre><code>(local directory)/site-packages/toolkit/examples/mountain.py
</code></pre>
<p>To run the example I do <code>python mountain.py</code>, and in the code I have:</p>
<pre><code>from toolkit.interface import interface
</code></pre>
<p>And i get the error that I wrote, I have already checked <code>sys.path</code> and there I have the directory <code>/site-packages</code>, also I have the file <code>__init__.py.bin</code> in the toolkit folder to indicate to Python that this is a package. I also have a <code>__init__.py.bin</code> in the examples directory.</p>
<p>I do not know why Python cannot find the file when it is in <code>sys.path</code>, any ideas? Can be a permissions problem? Do I need execution permission?</p>
| 186 | 2008-12-03T21:26:28Z | 420,458 | <p>Yup. You need the directory to contain the <code>__init__.py</code> file, which is the file that initializes the package. Here, have a look at <a href="http://docs.python.org/tutorial/modules.html" rel="nofollow">this</a>.</p>
<blockquote>
<p>The __init__.py files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later on the module search path. In the simplest case, __init__.py can just be an empty file, but it can also execute initialization code for the package or set the __all__ variable, described later.</p>
</blockquote>
| 5 | 2009-01-07T14:22:01Z | [
"python",
"importerror",
"python-import"
] |
python ImportError No module named | 338,768 | <p>I am very new at Python and I am getting this error:</p>
<pre><code>Traceback (most recent call last):
File "mountain.py", line 28, in ?
from toolkit.interface import interface
ImportError: No module named toolkit.interface
</code></pre>
<p>Python is installed in a local directory:</p>
<p>My directory tree is like this:</p>
<pre><code>(local directory)/site-packages/toolkit/interface.py
</code></pre>
<p>My code is in here </p>
<pre><code>(local directory)/site-packages/toolkit/examples/mountain.py
</code></pre>
<p>To run the example I do <code>python mountain.py</code>, and in the code I have:</p>
<pre><code>from toolkit.interface import interface
</code></pre>
<p>And i get the error that I wrote, I have already checked <code>sys.path</code> and there I have the directory <code>/site-packages</code>, also I have the file <code>__init__.py.bin</code> in the toolkit folder to indicate to Python that this is a package. I also have a <code>__init__.py.bin</code> in the examples directory.</p>
<p>I do not know why Python cannot find the file when it is in <code>sys.path</code>, any ideas? Can be a permissions problem? Do I need execution permission?</p>
| 186 | 2008-12-03T21:26:28Z | 5,199,346 | <p>On *nix, also make sure that PYTHONPATH is configured correctly, esp that it has the format </p>
<pre><code> .:/usr/local/lib/python
</code></pre>
<p>(mind the .: at the beginning, so that it can search on the current directory, too)</p>
| 22 | 2011-03-04T21:14:56Z | [
"python",
"importerror",
"python-import"
] |
python ImportError No module named | 338,768 | <p>I am very new at Python and I am getting this error:</p>
<pre><code>Traceback (most recent call last):
File "mountain.py", line 28, in ?
from toolkit.interface import interface
ImportError: No module named toolkit.interface
</code></pre>
<p>Python is installed in a local directory:</p>
<p>My directory tree is like this:</p>
<pre><code>(local directory)/site-packages/toolkit/interface.py
</code></pre>
<p>My code is in here </p>
<pre><code>(local directory)/site-packages/toolkit/examples/mountain.py
</code></pre>
<p>To run the example I do <code>python mountain.py</code>, and in the code I have:</p>
<pre><code>from toolkit.interface import interface
</code></pre>
<p>And i get the error that I wrote, I have already checked <code>sys.path</code> and there I have the directory <code>/site-packages</code>, also I have the file <code>__init__.py.bin</code> in the toolkit folder to indicate to Python that this is a package. I also have a <code>__init__.py.bin</code> in the examples directory.</p>
<p>I do not know why Python cannot find the file when it is in <code>sys.path</code>, any ideas? Can be a permissions problem? Do I need execution permission?</p>
| 186 | 2008-12-03T21:26:28Z | 18,604,658 | <p>Disclaimer: this answer is not so relevant for this question, but this page pops up when googling for the error message...</p>
<p>In my case, the problem was I was linking to <em>debug</em> <code>python</code> & <code>boost::Python</code>, which requires that the extension be <code>FooLib_d.pyd</code> not just <code>FooLib.pyd</code>; renaming the file or updating <code>CMakeLists.txt</code> properties fixed the error. </p>
| 3 | 2013-09-04T02:52:25Z | [
"python",
"importerror",
"python-import"
] |
python ImportError No module named | 338,768 | <p>I am very new at Python and I am getting this error:</p>
<pre><code>Traceback (most recent call last):
File "mountain.py", line 28, in ?
from toolkit.interface import interface
ImportError: No module named toolkit.interface
</code></pre>
<p>Python is installed in a local directory:</p>
<p>My directory tree is like this:</p>
<pre><code>(local directory)/site-packages/toolkit/interface.py
</code></pre>
<p>My code is in here </p>
<pre><code>(local directory)/site-packages/toolkit/examples/mountain.py
</code></pre>
<p>To run the example I do <code>python mountain.py</code>, and in the code I have:</p>
<pre><code>from toolkit.interface import interface
</code></pre>
<p>And i get the error that I wrote, I have already checked <code>sys.path</code> and there I have the directory <code>/site-packages</code>, also I have the file <code>__init__.py.bin</code> in the toolkit folder to indicate to Python that this is a package. I also have a <code>__init__.py.bin</code> in the examples directory.</p>
<p>I do not know why Python cannot find the file when it is in <code>sys.path</code>, any ideas? Can be a permissions problem? Do I need execution permission?</p>
| 186 | 2008-12-03T21:26:28Z | 21,029,693 | <ol>
<li>You must have the file __ init__.py in the same directory where it's the file that you are importing.</li>
<li>You can not try to import a file that has the same name and be a file from 2 folders configured on the PYTHONPATH.</li>
</ol>
<p>eg:
/etc/environment</p>
<p>PYTHONPATH=$PYTHONPATH:/opt/folder1:/opt/folder2</p>
<p>/opt/folder1/foo</p>
<p>/opt/folder2/foo</p>
<p>And, if you are trying to import foo file, python will not know which one you want.</p>
<p>from foo import ... >>> importerror: no module named foo</p>
| 3 | 2014-01-09T19:45:22Z | [
"python",
"importerror",
"python-import"
] |
python ImportError No module named | 338,768 | <p>I am very new at Python and I am getting this error:</p>
<pre><code>Traceback (most recent call last):
File "mountain.py", line 28, in ?
from toolkit.interface import interface
ImportError: No module named toolkit.interface
</code></pre>
<p>Python is installed in a local directory:</p>
<p>My directory tree is like this:</p>
<pre><code>(local directory)/site-packages/toolkit/interface.py
</code></pre>
<p>My code is in here </p>
<pre><code>(local directory)/site-packages/toolkit/examples/mountain.py
</code></pre>
<p>To run the example I do <code>python mountain.py</code>, and in the code I have:</p>
<pre><code>from toolkit.interface import interface
</code></pre>
<p>And i get the error that I wrote, I have already checked <code>sys.path</code> and there I have the directory <code>/site-packages</code>, also I have the file <code>__init__.py.bin</code> in the toolkit folder to indicate to Python that this is a package. I also have a <code>__init__.py.bin</code> in the examples directory.</p>
<p>I do not know why Python cannot find the file when it is in <code>sys.path</code>, any ideas? Can be a permissions problem? Do I need execution permission?</p>
| 186 | 2008-12-03T21:26:28Z | 23,210,066 | <p>I ran into something very similar when I did this exercise in LPTHW; I could never get Python to recognise that I had files in the directory I was calling from. But I was able to get it to work in the end. What I did, and what I recommend, is to try this:</p>
<p>(NOTE: From your initial post, I am assuming you are using an *NIX-based machine and are running things from the command line, so this advice is tailored to that. Since I run Ubuntu, this is what I did) </p>
<p>1) Change directory (cd) to the directory <em>above</em> the directory where your files are. In this case, you're trying to run the <code>mountain.py</code> file, and trying to call the <code>toolkit.interface.py</code> module, which are in separate directories. In this case, you would go to the directory that contains paths to both those files (or in other words, the closest directory that the paths of both those files share). Which in this case is the <code>toolkit</code> directory.</p>
<p>2) When you are in the <code>tookit</code> directory, enter this line of code on your command line:</p>
<p><code>export PYTHONPATH=.</code></p>
<p>This sets your PYTHONPATH to ".", which basically means that your PYTHONPATH will now look for any called files within the directory you are currently in, (and more to the point, in the <em>sub-directory branches</em> of the directory you are in. So it doesn't just look in your current directory, but in all the directories that are <strong>in</strong> your current directory).</p>
<p>3) After you've set your PYTHONPATH in the step above, run your module from your current directory (the <code>toolkit</code> directory). Python should now find and load the modules you specified.</p>
<p>Hope this helps. I was quite frustrated with this myself. </p>
| 13 | 2014-04-22T03:52:48Z | [
"python",
"importerror",
"python-import"
] |
python ImportError No module named | 338,768 | <p>I am very new at Python and I am getting this error:</p>
<pre><code>Traceback (most recent call last):
File "mountain.py", line 28, in ?
from toolkit.interface import interface
ImportError: No module named toolkit.interface
</code></pre>
<p>Python is installed in a local directory:</p>
<p>My directory tree is like this:</p>
<pre><code>(local directory)/site-packages/toolkit/interface.py
</code></pre>
<p>My code is in here </p>
<pre><code>(local directory)/site-packages/toolkit/examples/mountain.py
</code></pre>
<p>To run the example I do <code>python mountain.py</code>, and in the code I have:</p>
<pre><code>from toolkit.interface import interface
</code></pre>
<p>And i get the error that I wrote, I have already checked <code>sys.path</code> and there I have the directory <code>/site-packages</code>, also I have the file <code>__init__.py.bin</code> in the toolkit folder to indicate to Python that this is a package. I also have a <code>__init__.py.bin</code> in the examples directory.</p>
<p>I do not know why Python cannot find the file when it is in <code>sys.path</code>, any ideas? Can be a permissions problem? Do I need execution permission?</p>
| 186 | 2008-12-03T21:26:28Z | 23,964,457 | <p>Linux: Imported modules are located in /usr/local/lib/python2.7/dist-packages</p>
<p>If you're using a module compiled in C, don't forget to chmod the .so file after <code>sudo setup.py install</code>.</p>
<pre><code>sudo chmod 755 /usr/local/lib/python2.7/dist-packages/*.so
</code></pre>
| 2 | 2014-05-30T22:50:26Z | [
"python",
"importerror",
"python-import"
] |
python ImportError No module named | 338,768 | <p>I am very new at Python and I am getting this error:</p>
<pre><code>Traceback (most recent call last):
File "mountain.py", line 28, in ?
from toolkit.interface import interface
ImportError: No module named toolkit.interface
</code></pre>
<p>Python is installed in a local directory:</p>
<p>My directory tree is like this:</p>
<pre><code>(local directory)/site-packages/toolkit/interface.py
</code></pre>
<p>My code is in here </p>
<pre><code>(local directory)/site-packages/toolkit/examples/mountain.py
</code></pre>
<p>To run the example I do <code>python mountain.py</code>, and in the code I have:</p>
<pre><code>from toolkit.interface import interface
</code></pre>
<p>And i get the error that I wrote, I have already checked <code>sys.path</code> and there I have the directory <code>/site-packages</code>, also I have the file <code>__init__.py.bin</code> in the toolkit folder to indicate to Python that this is a package. I also have a <code>__init__.py.bin</code> in the examples directory.</p>
<p>I do not know why Python cannot find the file when it is in <code>sys.path</code>, any ideas? Can be a permissions problem? Do I need execution permission?</p>
| 186 | 2008-12-03T21:26:28Z | 25,199,209 | <p>After just suffering the same issue I found my resolution was to delete all <code>pyc</code> files from my project, it seems like these cached files were somehow causing this error.</p>
<p>Easiest way I found to do this was to navigate to my project folder in Windows explorer and searching for <code>*.pyc</code>, then selecting all (<kbd>Ctrl</kbd>+<kbd>A</kbd>) and deleting them (<kbd>Ctrl</kbd>+<kbd>X</kbd>).</p>
<p>Its possible I could have resolved my issues by just deleting the specific <code>pyc</code> file but I never tried this</p>
| 0 | 2014-08-08T08:36:19Z | [
"python",
"importerror",
"python-import"
] |
python ImportError No module named | 338,768 | <p>I am very new at Python and I am getting this error:</p>
<pre><code>Traceback (most recent call last):
File "mountain.py", line 28, in ?
from toolkit.interface import interface
ImportError: No module named toolkit.interface
</code></pre>
<p>Python is installed in a local directory:</p>
<p>My directory tree is like this:</p>
<pre><code>(local directory)/site-packages/toolkit/interface.py
</code></pre>
<p>My code is in here </p>
<pre><code>(local directory)/site-packages/toolkit/examples/mountain.py
</code></pre>
<p>To run the example I do <code>python mountain.py</code>, and in the code I have:</p>
<pre><code>from toolkit.interface import interface
</code></pre>
<p>And i get the error that I wrote, I have already checked <code>sys.path</code> and there I have the directory <code>/site-packages</code>, also I have the file <code>__init__.py.bin</code> in the toolkit folder to indicate to Python that this is a package. I also have a <code>__init__.py.bin</code> in the examples directory.</p>
<p>I do not know why Python cannot find the file when it is in <code>sys.path</code>, any ideas? Can be a permissions problem? Do I need execution permission?</p>
| 186 | 2008-12-03T21:26:28Z | 25,699,674 | <p>My two cents:</p>
<p><img src="http://i.stack.imgur.com/oHpHx.jpg" alt="enter image description here"></p>
<p>Spit:</p>
<pre><code>Traceback (most recent call last):
File "bash\bash.py", line 454, in main
import bosh
File "Wrye Bash Launcher.pyw", line 63, in load_module
mod = imp.load_source(fullname,filename+ext,fp)
File "bash\bosh.py", line 69, in <module>
from game.oblivion.RecordGroups import MobWorlds, MobDials, MobICells, \
ImportError: No module named RecordGroups
</code></pre>
<p>This confused the hell out of me - went through posts and posts suggesting ugly syspath hacks (as you see my <code>__init__.py</code> were all there). Well turns out that game/oblivion.py and game/oblivion was confusing python
which spit out the rather unhelpful "No module named RecordGroups". I'd be interested in a workaround and/or links documenting this (same name) behavior.</p>
<p>EDIT (2015.01.17): I did not mention we use a <a href="https://github.com/wrye-bash/wrye-bash/blob/dev/Mopy/Wrye%20Bash%20Launcher.pyw#L47-L80" rel="nofollow">custom launcher</a> dissected <a href="http://stackoverflow.com/questions/27193586/file-string-in-python-traceback/27202474#27202474">here</a>.</p>
| 1 | 2014-09-06T11:17:22Z | [
"python",
"importerror",
"python-import"
] |
python ImportError No module named | 338,768 | <p>I am very new at Python and I am getting this error:</p>
<pre><code>Traceback (most recent call last):
File "mountain.py", line 28, in ?
from toolkit.interface import interface
ImportError: No module named toolkit.interface
</code></pre>
<p>Python is installed in a local directory:</p>
<p>My directory tree is like this:</p>
<pre><code>(local directory)/site-packages/toolkit/interface.py
</code></pre>
<p>My code is in here </p>
<pre><code>(local directory)/site-packages/toolkit/examples/mountain.py
</code></pre>
<p>To run the example I do <code>python mountain.py</code>, and in the code I have:</p>
<pre><code>from toolkit.interface import interface
</code></pre>
<p>And i get the error that I wrote, I have already checked <code>sys.path</code> and there I have the directory <code>/site-packages</code>, also I have the file <code>__init__.py.bin</code> in the toolkit folder to indicate to Python that this is a package. I also have a <code>__init__.py.bin</code> in the examples directory.</p>
<p>I do not know why Python cannot find the file when it is in <code>sys.path</code>, any ideas? Can be a permissions problem? Do I need execution permission?</p>
| 186 | 2008-12-03T21:26:28Z | 34,102,396 | <p>I faced the same problem: <code>Import error</code>. In addition the library've been installed 100% correctly. The source of the problem was that on my PC 3 version of python (anaconda packet) have been installed). This is why the library was installed no to the right place. After that I just changed to the proper version of python in the my IDE PyCharm.</p>
| 0 | 2015-12-05T07:21:41Z | [
"python",
"importerror",
"python-import"
] |
python ImportError No module named | 338,768 | <p>I am very new at Python and I am getting this error:</p>
<pre><code>Traceback (most recent call last):
File "mountain.py", line 28, in ?
from toolkit.interface import interface
ImportError: No module named toolkit.interface
</code></pre>
<p>Python is installed in a local directory:</p>
<p>My directory tree is like this:</p>
<pre><code>(local directory)/site-packages/toolkit/interface.py
</code></pre>
<p>My code is in here </p>
<pre><code>(local directory)/site-packages/toolkit/examples/mountain.py
</code></pre>
<p>To run the example I do <code>python mountain.py</code>, and in the code I have:</p>
<pre><code>from toolkit.interface import interface
</code></pre>
<p>And i get the error that I wrote, I have already checked <code>sys.path</code> and there I have the directory <code>/site-packages</code>, also I have the file <code>__init__.py.bin</code> in the toolkit folder to indicate to Python that this is a package. I also have a <code>__init__.py.bin</code> in the examples directory.</p>
<p>I do not know why Python cannot find the file when it is in <code>sys.path</code>, any ideas? Can be a permissions problem? Do I need execution permission?</p>
| 186 | 2008-12-03T21:26:28Z | 38,512,198 | <p>Fixed my issue by writing <code>print (sys.path)</code> and found out that python was using out of date packages despite a clean install. Deleting these made python automatically use the correct packages.</p>
| 0 | 2016-07-21T18:51:03Z | [
"python",
"importerror",
"python-import"
] |
Nicest way to pad zeroes to string | 339,007 | <p>What is the nicest/shortest way to pad a string with zeroes to the left, so the string length has a specific length?</p>
| 647 | 2008-12-03T22:39:51Z | 339,012 | <p>For numbers:</p>
<pre><code>print "%05d" % number
</code></pre>
<p>See also: <a href="http://docs.python.org/library/string.html#string-formatting">Python: String formatting</a>.</p>
<p><strong>EDIT</strong>: It's worth noting that as of <strike>yesterday</strike> December 3rd, 2008, this method of formatting is deprecated in favour of the <code>format</code> string method:</p>
<pre><code>print("{0:05d}".format(number)) # or
print(format(number, "05d"))
</code></pre>
<p>See <a href="http://www.python.org/dev/peps/pep-3101/">PEP 3101</a> for details.</p>
| 76 | 2008-12-03T22:41:49Z | [
"python",
"string"
] |
Nicest way to pad zeroes to string | 339,007 | <p>What is the nicest/shortest way to pad a string with zeroes to the left, so the string length has a specific length?</p>
| 647 | 2008-12-03T22:39:51Z | 339,013 | <p>Strings:</p>
<pre><code>>>> n = '4'
>>> print n.zfill(3)
004
</code></pre>
<p>And for numbers:</p>
<pre><code>>>> n = 4
>>> print '%03d' % n
004
>>> print format(4, '03') # python >= 2.6
004
>>> print '{0:03d}'.format(4) # python >= 2.6
004
>>> print '{foo:03d}'.format(foo=4) # python >= 2.6
004
>>> print('{:03d}'.format(4)) # python >= 2.7 + python3
004
>>> print('{0:03d}'.format(4)) # python 3
004
</code></pre>
<p><a href="https://docs.python.org/2/library/string.html#formatexamples">String formatting documentation</a>.</p>
| 984 | 2008-12-03T22:42:04Z | [
"python",
"string"
] |
Nicest way to pad zeroes to string | 339,007 | <p>What is the nicest/shortest way to pad a string with zeroes to the left, so the string length has a specific length?</p>
| 647 | 2008-12-03T22:39:51Z | 339,019 | <pre><code>width = 10
x = 5
print "%0*d" % (width, x)
> 0000000005
</code></pre>
<p>See the print documentation for all the exciting details!</p>
<p><strong>Update for Python 3.x (7.5 years later)</strong></p>
<p>That last line should now be:</p>
<pre><code>print("%0*d" % (width, x))
</code></pre>
<p>I.e. <code>print()</code> is now a function, not a statement. Note that I still prefer the Old School <code>printf()</code> style because, IMNSHO, it reads better, and because, um, I've been using that notation since January, 1980. Something ... old dogs .. something something ... new tricks.</p>
| 9 | 2008-12-03T22:44:58Z | [
"python",
"string"
] |
Nicest way to pad zeroes to string | 339,007 | <p>What is the nicest/shortest way to pad a string with zeroes to the left, so the string length has a specific length?</p>
| 647 | 2008-12-03T22:39:51Z | 339,024 | <p>Just use the <a href="http://docs.python.org/2/library/stdtypes.html#string-methods">rjust</a> method of the string object.</p>
<p>This example will make a string of 10 characters long, padding as necessary.</p>
<pre><code>>>> t = 'test'
>>> t.rjust(10, '0')
>>> '000000test'
</code></pre>
| 200 | 2008-12-03T22:47:13Z | [
"python",
"string"
] |
Nicest way to pad zeroes to string | 339,007 | <p>What is the nicest/shortest way to pad a string with zeroes to the left, so the string length has a specific length?</p>
| 647 | 2008-12-03T22:39:51Z | 6,196,270 | <h1>GREAT for zip codes saved as integers!</h1>
<pre><code>>>> a = 6340
>>> b = 90210
>>> print '%05d' % a
06340
>>> print '%05d' % b
90210
</code></pre>
| 2 | 2011-06-01T04:27:15Z | [
"python",
"string"
] |
Nicest way to pad zeroes to string | 339,007 | <p>What is the nicest/shortest way to pad a string with zeroes to the left, so the string length has a specific length?</p>
| 647 | 2008-12-03T22:39:51Z | 6,196,350 | <p><code>str(n).zfill(width)</code> will work with <code>string</code>s, <code>int</code>s, <code>float</code>s... and is Python 2.<em>x</em> and 3.<em>x</em> compatible:</p>
<pre><code>>>> n = 3
>>> str(n).zfill(5)
'00003'
>>> n = '3'
>>> str(n).zfill(5)
'00003'
>>> n = '3.0'
>>> str(n).zfill(5)
'003.0'
</code></pre>
| 26 | 2011-06-01T04:40:02Z | [
"python",
"string"
] |
Nicest way to pad zeroes to string | 339,007 | <p>What is the nicest/shortest way to pad a string with zeroes to the left, so the string length has a specific length?</p>
| 647 | 2008-12-03T22:39:51Z | 11,753,186 | <pre><code>>>> width = 4
>>> x = 5
>>> print("%0*d" %(width,x))
>>> 00005
</code></pre>
<p>this will work in python 3.x</p>
| 2 | 2012-08-01T05:44:48Z | [
"python",
"string"
] |
Nicest way to pad zeroes to string | 339,007 | <p>What is the nicest/shortest way to pad a string with zeroes to the left, so the string length has a specific length?</p>
| 647 | 2008-12-03T22:39:51Z | 14,269,071 | <pre><code>>>> '99'.zfill(5)
'00099'
>>> '99'.rjust(5,'0')
'00099'
</code></pre>
<p>if you want the opposite:</p>
<pre><code>>>> '99'.ljust(5,'0')
'99000'
</code></pre>
| 28 | 2013-01-10T23:19:37Z | [
"python",
"string"
] |
Nicest way to pad zeroes to string | 339,007 | <p>What is the nicest/shortest way to pad a string with zeroes to the left, so the string length has a specific length?</p>
| 647 | 2008-12-03T22:39:51Z | 16,408,018 | <p>You could also repeat "0", prepend it to str(n) and get the rightmost width slice. Quick and dirty little expression.</p>
<pre><code>def pad_left(n, width, pad="0"):
return ((pad * width) + str(n))[-width:]
</code></pre>
| 0 | 2013-05-06T22:02:55Z | [
"python",
"string"
] |
Nicest way to pad zeroes to string | 339,007 | <p>What is the nicest/shortest way to pad a string with zeroes to the left, so the string length has a specific length?</p>
| 647 | 2008-12-03T22:39:51Z | 24,386,708 | <p>Works in both Python 2 and Python 3:</p>
<pre><code>>>> "{:0>2}".format("1") # Works for both numbers and strings.
'01'
>>> "{:02}".format(1) # Only works for numbers.
'01'
</code></pre>
| 24 | 2014-06-24T12:31:08Z | [
"python",
"string"
] |
Nicest way to pad zeroes to string | 339,007 | <p>What is the nicest/shortest way to pad a string with zeroes to the left, so the string length has a specific length?</p>
| 647 | 2008-12-03T22:39:51Z | 38,353,814 | <p>For the ones how came here to understand and not just can a quick answer.
I do these especially for time strings:</p>
<pre><code>hour = 4
minute = 3
"{:0>2}:{:0>2}".format(hour,minute)
# prints 04:03
"{:0>3}:{:0>5}".format(hour,minute)
# prints '004:00003'
"{:0<3}:{:0<5}".format(hour,minute)
# prints '400:30000'
"{:$<3}:{:#<5}".format(hour,minute)
# prints '4$$:3####'
</code></pre>
<blockquote>
<p>"0" symbols what to replace with the "2" padding characters, the default is an empty space</p>
<p>">" symbols allign all the 2 "0" character to the left of the string</p>
<p>":" symbols the format_spec</p>
</blockquote>
| 0 | 2016-07-13T13:59:00Z | [
"python",
"string"
] |
How do you unzip very large files in python? | 339,053 | <p>Using python 2.4 and the built-in <code>ZipFile</code> library, I cannot read very large zip files (greater than 1 or 2 GB) because it wants to store the entire contents of the uncompressed file in memory. Is there another way to do this (either with a third-party library or some other hack), or must I "shell out" and unzip it that way (which isn't as cross-platform, obviously).</p>
| 15 | 2008-12-03T23:00:54Z | 339,506 | <p>Here's an outline of decompression of large files.</p>
<pre><code>import zipfile
import zlib
import os
src = open( doc, "rb" )
zf = zipfile.ZipFile( src )
for m in zf.infolist():
# Examine the header
print m.filename, m.header_offset, m.compress_size, repr(m.extra), repr(m.comment)
src.seek( m.header_offset )
src.read( 30 ) # Good to use struct to unpack this.
nm= src.read( len(m.filename) )
if len(m.extra) > 0: ex= src.read( len(m.extra) )
if len(m.comment) > 0: cm= src.read( len(m.comment) )
# Build a decompression object
decomp= zlib.decompressobj(-15)
# This can be done with a loop reading blocks
out= open( m.filename, "wb" )
result= decomp.decompress( src.read( m.compress_size ) )
out.write( result )
result = decomp.flush()
out.write( result )
# end of the loop
out.close()
zf.close()
src.close()
</code></pre>
| 16 | 2008-12-04T03:08:28Z | [
"python",
"compression",
"zip",
"unzip"
] |
How do you unzip very large files in python? | 339,053 | <p>Using python 2.4 and the built-in <code>ZipFile</code> library, I cannot read very large zip files (greater than 1 or 2 GB) because it wants to store the entire contents of the uncompressed file in memory. Is there another way to do this (either with a third-party library or some other hack), or must I "shell out" and unzip it that way (which isn't as cross-platform, obviously).</p>
| 15 | 2008-12-03T23:00:54Z | 28,766,502 | <p>As of Python 2.6, you can use <a href="https://docs.python.org/2/library/zipfile.html#zipfile.ZipFile.open" rel="nofollow"><code>ZipFile.open()</code></a> to open a file handle on a file, and copy contents efficiently to a target file of your choosing:</p>
<pre><code>import errno
import os
import shutil
import zipfile
TARGETDIR = '/foo/bar/baz'
with open(doc, "rb") as zipsrc:
zfile = zipfile.ZipFile(zipsrc)
for member in zfile.infolist():
target_path = os.path.join(TARGETDIR, member.filename)
if target_path.endswith('/'): # folder entry, create
try:
os.makedirs(target_path)
except (OSError, IOError) as err:
# Windows may complain if the folders already exist
if err.errno != errno.EEXIST:
raise
continue
with open(target_path, 'wb') as outfile, zfile.open(member) as infile:
shutil.copyfileobj(infile, outfile)
</code></pre>
<p>This uses <a href="https://docs.python.org/2/library/shutil.html#shutil.copyfileobj" rel="nofollow"><code>shutil.copyfileobj()</code></a> to efficiently read data from the open zipfile object, copying it over to the output file.</p>
| 6 | 2015-02-27T13:41:54Z | [
"python",
"compression",
"zip",
"unzip"
] |
Writing a compiler for a DSL in python | 339,217 | <p>I am writing a game in python and have decided to create a DSL for the map data files. I know I could write my own parser with regex, but I am wondering if there are existing python tools which can do this more easily, like re2c which is used in the PHP engine.</p>
<p>Some extra info:</p>
<ul>
<li>Yes, I <em>do</em> need a DSL, and even if I didn't I still want the experience of building and using one in a project.</li>
<li><p>The DSL contains only data (declarative?), it doesn't get "executed". Most lines look like:</p>
<p><code>SOMETHING: !abc @123 #xyz/123</code></p>
<p>I just need to read the tree of data.</p></li>
</ul>
| 5 | 2008-12-04T00:17:14Z | 339,235 | <p>There are plenty of Python parsing tools: <a href="http://nedbatchelder.com/text/python-parsers.html">http://nedbatchelder.com/text/python-parsers.html</a></p>
| 7 | 2008-12-04T00:24:14Z | [
"python",
"dsl",
"dsl-tools"
] |
Writing a compiler for a DSL in python | 339,217 | <p>I am writing a game in python and have decided to create a DSL for the map data files. I know I could write my own parser with regex, but I am wondering if there are existing python tools which can do this more easily, like re2c which is used in the PHP engine.</p>
<p>Some extra info:</p>
<ul>
<li>Yes, I <em>do</em> need a DSL, and even if I didn't I still want the experience of building and using one in a project.</li>
<li><p>The DSL contains only data (declarative?), it doesn't get "executed". Most lines look like:</p>
<p><code>SOMETHING: !abc @123 #xyz/123</code></p>
<p>I just need to read the tree of data.</p></li>
</ul>
| 5 | 2008-12-04T00:17:14Z | 339,300 | <p>Yes, there are many -- too many -- parsing tools, but none in the standard library.</p>
<p>From what what I saw PLY and SPARK are popular. <a href="http://www.dabeaz.com/ply/" rel="nofollow">PLY</a> is like yacc, but you do everything in Python because you write your grammar in docstrings.</p>
<p>Personally, I like the concept of parser combinators (taken from functional programming), and I quite like <a href="http://pyparsing.wikispaces.com/" rel="nofollow">pyparsing</a>: you write your grammar and actions directly in python and it is easy to start with. I ended up producing my own tree node types with actions though, instead of using their default <code>ParserElement</code> type.</p>
<p>Otherwise, you can also use existing declarative language like <a href="http://www.dabeaz.com/ply/" rel="nofollow">YAML</a>.</p>
| 3 | 2008-12-04T00:59:31Z | [
"python",
"dsl",
"dsl-tools"
] |
Writing a compiler for a DSL in python | 339,217 | <p>I am writing a game in python and have decided to create a DSL for the map data files. I know I could write my own parser with regex, but I am wondering if there are existing python tools which can do this more easily, like re2c which is used in the PHP engine.</p>
<p>Some extra info:</p>
<ul>
<li>Yes, I <em>do</em> need a DSL, and even if I didn't I still want the experience of building and using one in a project.</li>
<li><p>The DSL contains only data (declarative?), it doesn't get "executed". Most lines look like:</p>
<p><code>SOMETHING: !abc @123 #xyz/123</code></p>
<p>I just need to read the tree of data.</p></li>
</ul>
| 5 | 2008-12-04T00:17:14Z | 339,308 | <p>I've always been impressed by <a href="http://pyparsing.wikispaces.com/">pyparsing</a>. The author, Paul McGuire, is active on the <a href="http://mail.python.org/mailman/listinfo/python-list">python list</a>/<a href="http://groups.google.com/group/comp.lang.python">comp.lang.python</a> and has always been very helpful with any queries concerning it.</p>
| 11 | 2008-12-04T01:02:53Z | [
"python",
"dsl",
"dsl-tools"
] |
Writing a compiler for a DSL in python | 339,217 | <p>I am writing a game in python and have decided to create a DSL for the map data files. I know I could write my own parser with regex, but I am wondering if there are existing python tools which can do this more easily, like re2c which is used in the PHP engine.</p>
<p>Some extra info:</p>
<ul>
<li>Yes, I <em>do</em> need a DSL, and even if I didn't I still want the experience of building and using one in a project.</li>
<li><p>The DSL contains only data (declarative?), it doesn't get "executed". Most lines look like:</p>
<p><code>SOMETHING: !abc @123 #xyz/123</code></p>
<p>I just need to read the tree of data.</p></li>
</ul>
| 5 | 2008-12-04T00:17:14Z | 339,329 | <p>Here's an approach that works really well.</p>
<pre><code>abc= ONETHING( ... )
xyz= ANOTHERTHING( ... )
pqr= SOMETHING( this=abc, that=123, more=(xyz,123) )
</code></pre>
<p>Declarative. Easy-to-parse. </p>
<p>And...</p>
<p>It's actually Python. A few class declarations and the work is done. The DSL is actually class declarations.</p>
<p>What's important is that a DSL merely creates objects. When you define a DSL, first you have to start with an object model. Later, you put some syntax around that object model. You don't start with syntax, you start with the model.</p>
| 6 | 2008-12-04T01:09:56Z | [
"python",
"dsl",
"dsl-tools"
] |
Writing a compiler for a DSL in python | 339,217 | <p>I am writing a game in python and have decided to create a DSL for the map data files. I know I could write my own parser with regex, but I am wondering if there are existing python tools which can do this more easily, like re2c which is used in the PHP engine.</p>
<p>Some extra info:</p>
<ul>
<li>Yes, I <em>do</em> need a DSL, and even if I didn't I still want the experience of building and using one in a project.</li>
<li><p>The DSL contains only data (declarative?), it doesn't get "executed". Most lines look like:</p>
<p><code>SOMETHING: !abc @123 #xyz/123</code></p>
<p>I just need to read the tree of data.</p></li>
</ul>
| 5 | 2008-12-04T00:17:14Z | 341,880 | <p>I have written something like this in work to read in SNMP notification definitions and automatically generate Java classes and SNMP MIB files from this. Using this little DSL, I could write 20 lines of my specification and it would generate roughly 80 lines of Java code and a 100 line MIB file.</p>
<p>To implement this, I actually just used straight Python string handling (split(), slicing etc) to parse the file. I find Pythons string capabilities to be adequate for most of my (simple) parsing needs.</p>
<p>Besides the libraries mentioned by others, if I were writing something more complex and needed proper parsing capabilities, I would probably use <a href="http://www.antlr.org/" rel="nofollow">ANTLR</a>, which supports Python (and other languages).</p>
| 2 | 2008-12-04T20:08:42Z | [
"python",
"dsl",
"dsl-tools"
] |
Writing a compiler for a DSL in python | 339,217 | <p>I am writing a game in python and have decided to create a DSL for the map data files. I know I could write my own parser with regex, but I am wondering if there are existing python tools which can do this more easily, like re2c which is used in the PHP engine.</p>
<p>Some extra info:</p>
<ul>
<li>Yes, I <em>do</em> need a DSL, and even if I didn't I still want the experience of building and using one in a project.</li>
<li><p>The DSL contains only data (declarative?), it doesn't get "executed". Most lines look like:</p>
<p><code>SOMETHING: !abc @123 #xyz/123</code></p>
<p>I just need to read the tree of data.</p></li>
</ul>
| 5 | 2008-12-04T00:17:14Z | 343,028 | <p>Peter,</p>
<p>DSLs are a <em>good thing</em>, so you don't need to defend yourself :-)
However, have you considered an internal DSL ? These have so many pros versus external (parsed) DSLs that they're at least worth consideration. Mixing a DSL with the power of the native language really solves lots of the problems for you, and Python is not really bad at internal DSLs, with the <code>with</code> statement handy.</p>
| 2 | 2008-12-05T06:10:45Z | [
"python",
"dsl",
"dsl-tools"
] |
Writing a compiler for a DSL in python | 339,217 | <p>I am writing a game in python and have decided to create a DSL for the map data files. I know I could write my own parser with regex, but I am wondering if there are existing python tools which can do this more easily, like re2c which is used in the PHP engine.</p>
<p>Some extra info:</p>
<ul>
<li>Yes, I <em>do</em> need a DSL, and even if I didn't I still want the experience of building and using one in a project.</li>
<li><p>The DSL contains only data (declarative?), it doesn't get "executed". Most lines look like:</p>
<p><code>SOMETHING: !abc @123 #xyz/123</code></p>
<p>I just need to read the tree of data.</p></li>
</ul>
| 5 | 2008-12-04T00:17:14Z | 1,660,889 | <p>For "small languages" as the one you are describing, I use a simple split, shlex (mind that the # defines a comment) or regular expressions. </p>
<pre><code>>>> line = 'SOMETHING: !abc @123 #xyz/123'
>>> line.split()
['SOMETHING:', '!abc', '@123', '#xyz/123']
>>> import shlex
>>> list(shlex.shlex(line))
['SOMETHING', ':', '!', 'abc', '@', '123']
</code></pre>
<p>The following is an example, as I do not know exactly what you are looking for.</p>
<pre><code>>>> import re
>>> result = re.match(r'([A-Z]*): !([a-z]*) @([0-9]*) #([a-z0-9/]*)', line)
>>> result.groups()
('SOMETHING', 'abc', '123', 'xyz/123')
</code></pre>
| 2 | 2009-11-02T12:00:47Z | [
"python",
"dsl",
"dsl-tools"
] |
Writing a compiler for a DSL in python | 339,217 | <p>I am writing a game in python and have decided to create a DSL for the map data files. I know I could write my own parser with regex, but I am wondering if there are existing python tools which can do this more easily, like re2c which is used in the PHP engine.</p>
<p>Some extra info:</p>
<ul>
<li>Yes, I <em>do</em> need a DSL, and even if I didn't I still want the experience of building and using one in a project.</li>
<li><p>The DSL contains only data (declarative?), it doesn't get "executed". Most lines look like:</p>
<p><code>SOMETHING: !abc @123 #xyz/123</code></p>
<p>I just need to read the tree of data.</p></li>
</ul>
| 5 | 2008-12-04T00:17:14Z | 8,180,818 | <p>On the lines of declarative python, I wrote a helper module called 'bpyml' which lets you declare data in python in a more XML structured way without the verbose tags, it can be converted to/from XML too, but is valid python.</p>
<p><a href="https://svn.blender.org/svnroot/bf-blender/trunk/blender/release/scripts/modules/bpyml.py" rel="nofollow">https://svn.blender.org/svnroot/bf-blender/trunk/blender/release/scripts/modules/bpyml.py</a></p>
<p>Example Use
<a href="http://wiki.blender.org/index.php/User:Ideasman42#Declarative_UI_In_Blender" rel="nofollow">http://wiki.blender.org/index.php/User:Ideasman42#Declarative_UI_In_Blender</a></p>
| 0 | 2011-11-18T10:15:42Z | [
"python",
"dsl",
"dsl-tools"
] |
Problems raising a ValidationError on a Django Form | 339,387 | <p>I'm trying to validate that a submitted URL doesn't already exist in the database.</p>
<p>The relevant parts of the Form class look like this:</p>
<pre><code>from django.contrib.sites.models import Site
class SignUpForm(forms.Form):
# ... Other fields ...
url = forms.URLField(label='URL for new site, eg: example.com')
def clean_url(self):
url = self.cleaned_data['url']
try:
a = Site.objects.get(domain=url)
except Site.DoesNotExist:
return url
else:
raise forms.ValidationError("That URL is already in the database. Please submit a unique URL.")
def clean(self):
# Other form cleaning stuff. I don't *think* this is causing the grief
</code></pre>
<p>The problem is, regardless of what value I submit, I can't raise the <code>ValidationError</code>. And if I do something like this in the <code>clean_url()</code> method:</p>
<pre><code>if Site.objects.get(domain=url):
raise forms.ValidationError("That URL is already in the database. Please submit a unique URL.")
</code></pre>
<p>then I get a <code>DoesNotExist</code> error, even for URLs that already exist in the Database. Any ideas?</p>
| 5 | 2008-12-04T01:51:26Z | 339,463 | <p>I do it this way. It's slightly simpler.</p>
<pre><code>try:
a = Site.objects.get(domain=url)
raise forms.ValidationError("That URL is already in the database. Please submit a unique URL.")
except Site.DoesNotExist:
pass
return url
</code></pre>
| 2 | 2008-12-04T02:38:01Z | [
"python",
"django",
"django-forms",
"cleaned-data"
] |
Problems raising a ValidationError on a Django Form | 339,387 | <p>I'm trying to validate that a submitted URL doesn't already exist in the database.</p>
<p>The relevant parts of the Form class look like this:</p>
<pre><code>from django.contrib.sites.models import Site
class SignUpForm(forms.Form):
# ... Other fields ...
url = forms.URLField(label='URL for new site, eg: example.com')
def clean_url(self):
url = self.cleaned_data['url']
try:
a = Site.objects.get(domain=url)
except Site.DoesNotExist:
return url
else:
raise forms.ValidationError("That URL is already in the database. Please submit a unique URL.")
def clean(self):
# Other form cleaning stuff. I don't *think* this is causing the grief
</code></pre>
<p>The problem is, regardless of what value I submit, I can't raise the <code>ValidationError</code>. And if I do something like this in the <code>clean_url()</code> method:</p>
<pre><code>if Site.objects.get(domain=url):
raise forms.ValidationError("That URL is already in the database. Please submit a unique URL.")
</code></pre>
<p>then I get a <code>DoesNotExist</code> error, even for URLs that already exist in the Database. Any ideas?</p>
| 5 | 2008-12-04T01:51:26Z | 340,160 | <p>I think, you can return '' and fill _errors.</p>
<pre><code>msg = u"That URL is already in the database. Please submit a unique URL."
self._errors["url"]=ErrorList([msg])
return ''
</code></pre>
<p>or</p>
<pre><code>from django.contrib.sites.models import Site
class SignUpForm(forms.Form):
# ... Other fields ...
url = forms.URLField(label='URL for new site, eg: example.com')
def clean_url(self):
url = self.cleaned_data['url']
try:
a = Site.objects.get(domain=url)
raise forms.ValidationError("That URL is already in the database. Please submit a unique URL.")
except Site.DoesNotExist:
return url
return ''
def clean(self):
# Other form cleaning stuff. I don't *think* this is causing the grief
</code></pre>
| 0 | 2008-12-04T10:31:07Z | [
"python",
"django",
"django-forms",
"cleaned-data"
] |
Problems raising a ValidationError on a Django Form | 339,387 | <p>I'm trying to validate that a submitted URL doesn't already exist in the database.</p>
<p>The relevant parts of the Form class look like this:</p>
<pre><code>from django.contrib.sites.models import Site
class SignUpForm(forms.Form):
# ... Other fields ...
url = forms.URLField(label='URL for new site, eg: example.com')
def clean_url(self):
url = self.cleaned_data['url']
try:
a = Site.objects.get(domain=url)
except Site.DoesNotExist:
return url
else:
raise forms.ValidationError("That URL is already in the database. Please submit a unique URL.")
def clean(self):
# Other form cleaning stuff. I don't *think* this is causing the grief
</code></pre>
<p>The problem is, regardless of what value I submit, I can't raise the <code>ValidationError</code>. And if I do something like this in the <code>clean_url()</code> method:</p>
<pre><code>if Site.objects.get(domain=url):
raise forms.ValidationError("That URL is already in the database. Please submit a unique URL.")
</code></pre>
<p>then I get a <code>DoesNotExist</code> error, even for URLs that already exist in the Database. Any ideas?</p>
| 5 | 2008-12-04T01:51:26Z | 341,621 | <p>django channel in IRC saved me here. The problem was that the URLField.clean() does two things I wasn't expecting:</p>
<ol>
<li>If no URL scheme is present (eg, http://) the method prepends 'http://' to the url</li>
<li>the method also appends a trailing slash.</li>
</ol>
<p>The results are returned and stored in the form's cleaned_data. So I was checking <code>cleaned_data['url']</code> expecting something like <code>example.com</code> and actually getting <code>http://example.com/</code>. Suffice to say, changing my <code>clean_url()</code> method to the following works:</p>
<pre><code>def clean_url(self):
url = self.cleaned_data['url']
bits = urlparse(url)
dom = bits[1]
try:
site=Site.objects.get(domain__iexact=dom)
except Site.DoesNotExist:
return dom
raise forms.ValidationError(u'That domain is already taken. Please choose another')
</code></pre>
| 4 | 2008-12-04T18:30:40Z | [
"python",
"django",
"django-forms",
"cleaned-data"
] |
Problems raising a ValidationError on a Django Form | 339,387 | <p>I'm trying to validate that a submitted URL doesn't already exist in the database.</p>
<p>The relevant parts of the Form class look like this:</p>
<pre><code>from django.contrib.sites.models import Site
class SignUpForm(forms.Form):
# ... Other fields ...
url = forms.URLField(label='URL for new site, eg: example.com')
def clean_url(self):
url = self.cleaned_data['url']
try:
a = Site.objects.get(domain=url)
except Site.DoesNotExist:
return url
else:
raise forms.ValidationError("That URL is already in the database. Please submit a unique URL.")
def clean(self):
# Other form cleaning stuff. I don't *think* this is causing the grief
</code></pre>
<p>The problem is, regardless of what value I submit, I can't raise the <code>ValidationError</code>. And if I do something like this in the <code>clean_url()</code> method:</p>
<pre><code>if Site.objects.get(domain=url):
raise forms.ValidationError("That URL is already in the database. Please submit a unique URL.")
</code></pre>
<p>then I get a <code>DoesNotExist</code> error, even for URLs that already exist in the Database. Any ideas?</p>
| 5 | 2008-12-04T01:51:26Z | 4,185,803 | <p>Well I logged in cause I found this via Google with a similar issue and wanted to add a comment to Carl Meyers post noting that using self._errors is totally valid as per the Django docs:</p>
<p><a href="http://docs.djangoproject.com/en/1.2/ref/forms/validation/#cleaning-and-validating-fields-that-depend-on-each-other" rel="nofollow">http://docs.djangoproject.com/en/1.2/ref/forms/validation/#cleaning-and-validating-fields-that-depend-on-each-other</a></p>
| 0 | 2010-11-15T15:20:10Z | [
"python",
"django",
"django-forms",
"cleaned-data"
] |
End-line characters from lines read from text file, using Python | 339,537 | <p>When reading lines from a text file using python, the end-line character often needs to be truncated before processing the text, as in the following example:</p>
<pre><code> f = open("myFile.txt", "r")
for line in f:
line = line[:-1]
# do something with line
</code></pre>
<p>Is there an elegant way or idiom for retrieving text lines without the end-line character?</p>
| 26 | 2008-12-04T03:39:07Z | 339,574 | <p>What's wrong with your code? I find it to be quite elegant and simple. The only problem is that if the file doesn't end in a newline, the last line returned won't have a <code>'\n'</code> as the last character, and therefore doing <code>line = line[:-1]</code> would incorrectly strip off the last character of the line.</p>
<p>The most elegant way to solve this problem would be to define a generator which took the lines of the file and removed the last character from each line only if that character is a newline:</p>
<pre><code>def strip_trailing_newlines(file):
for line in file:
if line[-1] == '\n':
yield line[:-1]
else:
yield line
f = open("myFile.txt", "r")
for line in strip_trailing_newlines(f):
# do something with line
</code></pre>
| 4 | 2008-12-04T04:10:42Z | [
"python"
] |
End-line characters from lines read from text file, using Python | 339,537 | <p>When reading lines from a text file using python, the end-line character often needs to be truncated before processing the text, as in the following example:</p>
<pre><code> f = open("myFile.txt", "r")
for line in f:
line = line[:-1]
# do something with line
</code></pre>
<p>Is there an elegant way or idiom for retrieving text lines without the end-line character?</p>
| 26 | 2008-12-04T03:39:07Z | 339,579 | <p>Simple. Use <strong>splitlines()</strong></p>
<pre><code>L = open("myFile.txt", "r").read().splitlines();
for line in L:
process(line) # this 'line' will not have '\n' character at the end
</code></pre>
| 17 | 2008-12-04T04:13:21Z | [
"python"
] |
End-line characters from lines read from text file, using Python | 339,537 | <p>When reading lines from a text file using python, the end-line character often needs to be truncated before processing the text, as in the following example:</p>
<pre><code> f = open("myFile.txt", "r")
for line in f:
line = line[:-1]
# do something with line
</code></pre>
<p>Is there an elegant way or idiom for retrieving text lines without the end-line character?</p>
| 26 | 2008-12-04T03:39:07Z | 339,587 | <p>You may also consider using line.rstrip() to remove the whitespaces at the end of your line.</p>
| 2 | 2008-12-04T04:18:14Z | [
"python"
] |
End-line characters from lines read from text file, using Python | 339,537 | <p>When reading lines from a text file using python, the end-line character often needs to be truncated before processing the text, as in the following example:</p>
<pre><code> f = open("myFile.txt", "r")
for line in f:
line = line[:-1]
# do something with line
</code></pre>
<p>Is there an elegant way or idiom for retrieving text lines without the end-line character?</p>
| 26 | 2008-12-04T03:39:07Z | 339,842 | <p>The <em>idiomatic</em> way to do this in Python is to use <strong>rstrip('\n')</strong>:</p>
<pre><code>for line in open('myfile.txt'): # opened in text-mode; all EOLs are converted to '\n'
line = line.rstrip('\n')
process(line)
</code></pre>
<p>Each of the other alternatives has a gotcha:</p>
<ul>
<li><strong>file('...').read().splitlines()</strong> has to load the whole file in memory at once.</li>
<li><strong>line = line[:-1]</strong> will fail if the last line has no EOL.</li>
</ul>
| 43 | 2008-12-04T08:04:19Z | [
"python"
] |
End-line characters from lines read from text file, using Python | 339,537 | <p>When reading lines from a text file using python, the end-line character often needs to be truncated before processing the text, as in the following example:</p>
<pre><code> f = open("myFile.txt", "r")
for line in f:
line = line[:-1]
# do something with line
</code></pre>
<p>Is there an elegant way or idiom for retrieving text lines without the end-line character?</p>
| 26 | 2008-12-04T03:39:07Z | 1,118,507 | <p>Long time ago, there was Dear, clean, old, BASIC code that could run on 16 kb core machines:
like that: </p>
<pre><code>if (not open(1,"file.txt")) error "Could not open 'file.txt' for reading"
while(not eof(1))
line input #1 a$
print a$
wend
close
</code></pre>
<p>Now, to read a file line by line, with far better hardware and software (Python), we must reinvent the wheel:</p>
<pre><code>def line_input (file):
for line in file:
if line[-1] == '\n':
yield line[:-1]
else:
yield line
f = open("myFile.txt", "r")
for line_input(f):
# do something with line
</code></pre>
<p>I am induced to think that something has gone the wrong way somewhere...</p>
| 3 | 2009-07-13T09:39:48Z | [
"python"
] |
End-line characters from lines read from text file, using Python | 339,537 | <p>When reading lines from a text file using python, the end-line character often needs to be truncated before processing the text, as in the following example:</p>
<pre><code> f = open("myFile.txt", "r")
for line in f:
line = line[:-1]
# do something with line
</code></pre>
<p>Is there an elegant way or idiom for retrieving text lines without the end-line character?</p>
| 26 | 2008-12-04T03:39:07Z | 6,978,968 | <p>What do you thing about this approach?</p>
<pre><code>with open(filename) as data:
datalines = (line.rstrip('\r\n') for line in data)
for line in datalines:
...do something awesome...
</code></pre>
<p>Generator expression avoids loading whole file into memory and <code>with</code> ensures closing the file</p>
| 3 | 2011-08-08T07:29:15Z | [
"python"
] |
How do I strptime from a pattern like this? | 339,856 | <p>I need to use a datetime.strptime on the text which looks like follows.</p>
<p>"Some Random text of undetermined length Jan 28, 1986"</p>
<p>how do i do this?</p>
| 3 | 2008-12-04T08:10:18Z | 339,884 | <p>Using the ending 3 words, no need for regexps (using the <code>time</code> module):</p>
<pre><code>>>> import time
>>> a="Some Random text of undetermined length Jan 28, 1986"
>>> datetuple = a.rsplit(" ",3)[-3:]
>>> datetuple
['Jan', '28,', '1986']
>>> time.strptime(' '.join(datetuple),"%b %d, %Y")
time.struct_time(tm_year=1986, tm_mon=1, tm_mday=28, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=28, tm_isdst=-1)
>>>
</code></pre>
<p>Using the <code>datetime</code> module:</p>
<pre><code>>>> from datetime import datetime
>>> datetime.strptime(" ".join(datetuple), "%b %d, %Y")
datetime.datetime(1986, 1, 28, 0, 0)
>>>
</code></pre>
| 2 | 2008-12-04T08:25:07Z | [
"python",
"regex",
"datetime"
] |
How do I strptime from a pattern like this? | 339,856 | <p>I need to use a datetime.strptime on the text which looks like follows.</p>
<p>"Some Random text of undetermined length Jan 28, 1986"</p>
<p>how do i do this?</p>
| 3 | 2008-12-04T08:10:18Z | 339,886 | <p>You may find <a href="http://stackoverflow.com/questions/285408/python-module-to-extract-probable-dates-from-strings">this</a> question useful. I'll give the answer I gave there, which is to use the <a href="http://labix.org/python-dateutil" rel="nofollow">dateutil</a> module. This accepts a fuzzy parameter which will ignore any text that doesn't look like a date. ie:</p>
<pre><code>>>> from dateutil.parser import parse
>>> parse("Some Random text of undetermined length Jan 28, 1986", fuzzy=True)
datetime.datetime(1986, 1, 28, 0, 0)
</code></pre>
| 4 | 2008-12-04T08:25:51Z | [
"python",
"regex",
"datetime"
] |
How do I strptime from a pattern like this? | 339,856 | <p>I need to use a datetime.strptime on the text which looks like follows.</p>
<p>"Some Random text of undetermined length Jan 28, 1986"</p>
<p>how do i do this?</p>
| 3 | 2008-12-04T08:10:18Z | 339,893 | <p>Don't try to use strptime to capture the non-date text. For good fuzzy matching, dateutil.parser is great, but if you know the format of the date, you could use a regular expression to find the date within the string, then use strptime to turn it into a datetime object, like this:</p>
<pre><code>import datetime
import re
pattern = "((Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) [0-9]+, [0-9]+)"
datestr = re.search(, s).group(0)
d = datetime.datetime.strptime(datestr, "%b %d, %Y")
</code></pre>
| 3 | 2008-12-04T08:28:10Z | [
"python",
"regex",
"datetime"
] |
Proxy objects in IronPython | 340,093 | <p>I'm trying to make a proxy object in IronPython, which should dynamically present underlying structure. The proxy itself shouldn't have any functions and properties, I'm trying to catch all the calls in the runtime. Catching the function calls is easy, I just need to define <strong>getattr</strong>() function for my object, and check does appropriate function exists in the underlying layer, and return some function-like object.</p>
<p>I have problems with properties - I don't know how to distinguish the calling context, is my property called as a lvalue or rvalue:</p>
<p>o = myproxy.myproperty # *I need to call underlying.myproperty_get()*</p>
<p>or</p>
<p>myproxy.myproperty = o # *I need to call underlying.myproperty_set(o)*</p>
<p>I looked at the list of special functions in Python, but I didn't found anything appropriate.</p>
<p>I also tried to make property in the object on the fly, with combination of exec() and builtin property() function, but I found that IronPython 1.1.2 lacks of entire 'new' module (which is present in IronPython 2.x beta, but I'll rather use IP 1.x, because of .NET 2.0 framework).</p>
<p>Any ideas?</p>
| 1 | 2008-12-04T10:06:01Z | 340,220 | <p>The usual implementation of what you want in python would be this:</p>
<pre><code>class CallProxy(object):
'this class wraps a callable in an object'
def __init__(self, fun):
self.fun = fun
def __call__(self, *args, **kwargs):
return self.fun(*args, **kwargs)
class ObjProxy(object):
''' a proxy object intercepting attribute access
'''
def __init__(self, obj):
self.__dict__['_ObjProxy__obj'] = obj
def __getattr__(self, name):
attr = getattr(self.__obj, name)
if callable(attr):
return CallProxy(attr)
else:
return attr
def __setattr__(self, name, value):
setattr(self.__obj, name, value)
</code></pre>
<p>I wrote a test to prove that this behaves as expected:</p>
<pre><code>#keep a list of calls to the TestObj for verification
call_log = list()
class TestObj(object):
''' test object on which to prove
that the proxy implementation is correct
'''
def __init__(self):
#example attribute
self.a = 1
self._c = 3
def b(self):
'example method'
call_log.append('b')
return 2
def get_c(self):
call_log.append('get_c')
return self._c
def set_c(self, value):
call_log.append('set_c')
self._c = value
c = property(get_c, set_c, 'example property')
def verify(obj, a_val, b_val, c_val):
'testing of the usual object semantics'
assert obj.a == a_val
obj.a = a_val + 1
assert obj.a == a_val + 1
assert obj.b() == b_val
assert call_log[-1] == 'b'
assert obj.c == c_val
assert call_log[-1] == 'get_c'
obj.c = c_val + 1
assert call_log[-1] == 'set_c'
assert obj.c == c_val + 1
def test():
test = TestObj()
proxy = ObjProxy(test)
#check validity of the test
verify(test, 1, 2, 3)
#check proxy equivalent behavior
verify(proxy, 2, 2, 4)
#check that change is in the original object
verify(test, 3, 2, 5)
if __name__ == '__main__':
test()
</code></pre>
<p>This executes on CPython without any assert throwing an exception. IronPython should be equivalent, otherwise it's broken and this test should be added to its unit test suite.</p>
| 2 | 2008-12-04T11:03:33Z | [
".net",
"python",
"ironpython"
] |
Proxy objects in IronPython | 340,093 | <p>I'm trying to make a proxy object in IronPython, which should dynamically present underlying structure. The proxy itself shouldn't have any functions and properties, I'm trying to catch all the calls in the runtime. Catching the function calls is easy, I just need to define <strong>getattr</strong>() function for my object, and check does appropriate function exists in the underlying layer, and return some function-like object.</p>
<p>I have problems with properties - I don't know how to distinguish the calling context, is my property called as a lvalue or rvalue:</p>
<p>o = myproxy.myproperty # *I need to call underlying.myproperty_get()*</p>
<p>or</p>
<p>myproxy.myproperty = o # *I need to call underlying.myproperty_set(o)*</p>
<p>I looked at the list of special functions in Python, but I didn't found anything appropriate.</p>
<p>I also tried to make property in the object on the fly, with combination of exec() and builtin property() function, but I found that IronPython 1.1.2 lacks of entire 'new' module (which is present in IronPython 2.x beta, but I'll rather use IP 1.x, because of .NET 2.0 framework).</p>
<p>Any ideas?</p>
| 1 | 2008-12-04T10:06:01Z | 340,369 | <p>Try this:</p>
<pre><code>class Test(object):
_test = 0
def test():
def fget(self):
return self._test
def fset(self, value):
self._test = value
return locals()
test = property(**test())
def greet(self, name):
print "hello", name
class Proxy(object):
def __init__(self, obj):
self._obj = obj
def __getattribute__(self, key):
obj = object.__getattribute__(self, "_obj")
return getattr(obj, key)
def __setattr__(self, name, value):
if name == "_obj":
object.__setattr__(self, name, value)
else:
obj = object.__getattribute__(self, "_obj")
setattr(obj, name, value)
t = Test()
p = Proxy(t)
p.test = 1
assert t.test == p.test
p.greet("world")
</code></pre>
| 2 | 2008-12-04T12:07:00Z | [
".net",
"python",
"ironpython"
] |
IronPython For Unit Testing over C# | 340,128 | <p>We know that Python provides a lot of productivity over any compiled languages. We have programming in C# & need to write the unit test cases in C# itself. If we see the amount of code we write for unit test is approximately ten times more than the original code. </p>
<p>Is it ideal choice to write unit test cases in IronPython instead of C#? Any body has done like that? I wrote few test cases, they seems to be good. But hairy pointy managers won't accept.</p>
| 13 | 2008-12-04T10:21:03Z | 340,152 | <p>There's an obvious <em>disadvantage</em> which is that everyone working on the code now needs to be proficient in two languages, not just one. I'm fairly hairy but not very pointy, but I do see why managers might be sceptical.</p>
| 2 | 2008-12-04T10:29:38Z | [
"c#",
"python",
"unit-testing",
"ironpython"
] |
IronPython For Unit Testing over C# | 340,128 | <p>We know that Python provides a lot of productivity over any compiled languages. We have programming in C# & need to write the unit test cases in C# itself. If we see the amount of code we write for unit test is approximately ten times more than the original code. </p>
<p>Is it ideal choice to write unit test cases in IronPython instead of C#? Any body has done like that? I wrote few test cases, they seems to be good. But hairy pointy managers won't accept.</p>
| 13 | 2008-12-04T10:21:03Z | 340,174 | <p>Will's answer is good - you're introducing a new requirement for developers.</p>
<p>In addition, what's the tool support like? I haven't tried any of this myself, but I'd want to know:</p>
<ul>
<li>How easy is it to debug into failing unit tests?</li>
<li>How easy is it to run unit tests from the IDE? (e.g. with ReSharper)</li>
<li>How easy is it to automate the unit tests from a continuous build server?</li>
</ul>
<p>It could be that all of these are fine - but you should make check them, and document the results.</p>
<p>There are other options as well as IronPython, of course - <a href="http://boo.codehaus.org/" rel="nofollow">Boo</a> being a fairly obvious choice.</p>
| 4 | 2008-12-04T10:36:19Z | [
"c#",
"python",
"unit-testing",
"ironpython"
] |
IronPython For Unit Testing over C# | 340,128 | <p>We know that Python provides a lot of productivity over any compiled languages. We have programming in C# & need to write the unit test cases in C# itself. If we see the amount of code we write for unit test is approximately ten times more than the original code. </p>
<p>Is it ideal choice to write unit test cases in IronPython instead of C#? Any body has done like that? I wrote few test cases, they seems to be good. But hairy pointy managers won't accept.</p>
| 13 | 2008-12-04T10:21:03Z | 341,683 | <p>Python being a much less verbose language than C# might actually lower the barrier to writing unit tests since there is still a lot of developers that are resistant to doing automated unit testing in general. Introducing and having them use a language like IronPython that typically tends to take less time to write the equivalent code in C# might actually encourage more unit tests to be written which is always a good thing.</p>
<p>Plus, by using IronPython for your test code, you might end up with less lines of code (LOC) for your project overall meaning that your unit tests might be more likely to be maintained in the long run versus being ignored and/or discarded.</p>
| 3 | 2008-12-04T18:57:17Z | [
"c#",
"python",
"unit-testing",
"ironpython"
] |
IronPython For Unit Testing over C# | 340,128 | <p>We know that Python provides a lot of productivity over any compiled languages. We have programming in C# & need to write the unit test cases in C# itself. If we see the amount of code we write for unit test is approximately ten times more than the original code. </p>
<p>Is it ideal choice to write unit test cases in IronPython instead of C#? Any body has done like that? I wrote few test cases, they seems to be good. But hairy pointy managers won't accept.</p>
| 13 | 2008-12-04T10:21:03Z | 342,457 | <p>Very interesting. </p>
<p>What would happen if you write all your code with IronPython (not just the unit tests)? Would you end up with approximately 10 times less code? </p>
<p>Maybe I should learn IronPython too. </p>
| 0 | 2008-12-04T23:36:58Z | [
"c#",
"python",
"unit-testing",
"ironpython"
] |
IronPython For Unit Testing over C# | 340,128 | <p>We know that Python provides a lot of productivity over any compiled languages. We have programming in C# & need to write the unit test cases in C# itself. If we see the amount of code we write for unit test is approximately ten times more than the original code. </p>
<p>Is it ideal choice to write unit test cases in IronPython instead of C#? Any body has done like that? I wrote few test cases, they seems to be good. But hairy pointy managers won't accept.</p>
| 13 | 2008-12-04T10:21:03Z | 342,490 | <p>Actually testing is a great opportunity to try integrating a new language. Languages like Python shine especially well in testing, and it's a low risk project to try - the worst case is not too bad at all.</p>
<p>As far as experience testing another language in Python, I've tested C and C++ systems like this and it was excellent. I think it's definitely worth a shot.</p>
<p>What Jon says is true, though - the level of tooling for Python in general, and IronPython in particular, is nowhere near that of C#. How much that affects you is something you'll find out in your pilot.</p>
| 3 | 2008-12-05T00:04:30Z | [
"c#",
"python",
"unit-testing",
"ironpython"
] |
IronPython For Unit Testing over C# | 340,128 | <p>We know that Python provides a lot of productivity over any compiled languages. We have programming in C# & need to write the unit test cases in C# itself. If we see the amount of code we write for unit test is approximately ten times more than the original code. </p>
<p>Is it ideal choice to write unit test cases in IronPython instead of C#? Any body has done like that? I wrote few test cases, they seems to be good. But hairy pointy managers won't accept.</p>
| 13 | 2008-12-04T10:21:03Z | 346,907 | <p>Python is excellent for UnitTesting C# code. Our app is 75% in Python and 25% C#(Python.Net), and our unit tests are 100% python. </p>
<p>I find that it's much easier to make use of stubs and mocks in Python which is probably one of the most critical components that enable one to write effective unittests.</p>
| 6 | 2008-12-06T22:28:16Z | [
"c#",
"python",
"unit-testing",
"ironpython"
] |
IronPython For Unit Testing over C# | 340,128 | <p>We know that Python provides a lot of productivity over any compiled languages. We have programming in C# & need to write the unit test cases in C# itself. If we see the amount of code we write for unit test is approximately ten times more than the original code. </p>
<p>Is it ideal choice to write unit test cases in IronPython instead of C#? Any body has done like that? I wrote few test cases, they seems to be good. But hairy pointy managers won't accept.</p>
| 13 | 2008-12-04T10:21:03Z | 443,959 | <p>I gotta go with Will and Jon..</p>
<p>I would prefer my tests be in the same language as the code I'm testing; it causes fewer cognitive context switches. But maybe I'm just not as mentally agile as I once was.</p>
<ul>
<li>Jon</li>
</ul>
| 0 | 2009-01-14T17:41:30Z | [
"c#",
"python",
"unit-testing",
"ironpython"
] |
IronPython For Unit Testing over C# | 340,128 | <p>We know that Python provides a lot of productivity over any compiled languages. We have programming in C# & need to write the unit test cases in C# itself. If we see the amount of code we write for unit test is approximately ten times more than the original code. </p>
<p>Is it ideal choice to write unit test cases in IronPython instead of C#? Any body has done like that? I wrote few test cases, they seems to be good. But hairy pointy managers won't accept.</p>
| 13 | 2008-12-04T10:21:03Z | 2,994,724 | <p>I've recently been re-evaluating my testing attitudes after discovering parameterised testing in <a href="http://www.mbunit.com/" rel="nofollow">mbUnit</a> and <a href="http://nunit.net/blogs/?p=60" rel="nofollow">NUnit</a>. Previously, I recommended Python unittest as a way to automate any testing possible, because of the concise nature and discoverability of the tests.</p>
<p>Parameterised tests allow you to customise the test fixtures with a range of data parameters and thus your C# tests can end up even more concise than Python tests.</p>
<pre><code>[TestCase(12, 3, 4)]
[TestCase(12, 2, 6)]
[TestCase(12, 4, 3)]
[TestCase(12, 0, 0, ExpectedException = typeof(System.DivideByZeroException),
TestName = âDivisionByZeroThrowsExceptionTypeâ)]
[TestCase(12, 0, 0, ExpectedExceptionName = âSystem.DivideByZeroExceptionâ,
TestName = âDivisionByZeroThrowsNamedExceptionâ)]
public void IntegerDivisionWithResultPassedToTest(int n, int d, int q)
{
Assert.AreEqual(q, n / d);
}
</code></pre>
| 1 | 2010-06-08T04:17:27Z | [
"c#",
"python",
"unit-testing",
"ironpython"
] |
Is rewriting a PHP app into Python a productive step? | 340,318 | <p>I have some old apps written in PHP that I'm thinking of converting to Python - both are websites that started as simple static html, then progressed to PHP and now include blogs with admin areas, rss etc. I'm thinking of rewriting them in Python to improve maintainability as well as to take advantage of my increase in experience to write things more robustly.</p>
<p>Is this worth the effort?</p>
| 6 | 2008-12-04T11:48:19Z | 340,329 | <p>Be sure to resist the <a href="http://en.wikipedia.org/wiki/Second-system_effect" rel="nofollow">Second-system effect</a> and you should be safe.</p>
<p>Rewriting an existing project gives you a reachable goal. You know which way you are heading. But don't try to do too much at once.</p>
| 4 | 2008-12-04T11:51:27Z | [
"php",
"python"
] |
Is rewriting a PHP app into Python a productive step? | 340,318 | <p>I have some old apps written in PHP that I'm thinking of converting to Python - both are websites that started as simple static html, then progressed to PHP and now include blogs with admin areas, rss etc. I'm thinking of rewriting them in Python to improve maintainability as well as to take advantage of my increase in experience to write things more robustly.</p>
<p>Is this worth the effort?</p>
| 6 | 2008-12-04T11:48:19Z | 340,334 | <p>Is your aim purely to improve the applications, or is it that you want to learn/work with Python?</p>
<p>If it's the first, I would say you should stick with PHP, since you already know that.</p>
| 1 | 2008-12-04T11:53:50Z | [
"php",
"python"
] |
Is rewriting a PHP app into Python a productive step? | 340,318 | <p>I have some old apps written in PHP that I'm thinking of converting to Python - both are websites that started as simple static html, then progressed to PHP and now include blogs with admin areas, rss etc. I'm thinking of rewriting them in Python to improve maintainability as well as to take advantage of my increase in experience to write things more robustly.</p>
<p>Is this worth the effort?</p>
| 6 | 2008-12-04T11:48:19Z | 340,338 | <p>You need to take some parts into mind here,</p>
<ol>
<li>What will you gain from re-writing</li>
<li>Is it an economically wise decision</li>
<li>Will the code be easier to handle for new programmers</li>
<li>Performance-wise, will this be a good option?</li>
</ol>
<p>These four points is something that is important, will the work be more efficient after you re-write the code? Probably. But will it be worth the cost of re-development?</p>
<p>One important step to follow, if you decide to re-write, make 3 documents, first Analyze the project, what needs to be done? How should everything work? Then put up a document with Requirements, what specificly do we need and how should this be done? Last but not least, the design document, where you put all your final class diagrams, the system operations and how the design and flow of the page should work.</p>
<p>This will help a new developer, and old ones, to actually think about "do we really need to re-write?".</p>
| 14 | 2008-12-04T11:54:58Z | [
"php",
"python"
] |
Is rewriting a PHP app into Python a productive step? | 340,318 | <p>I have some old apps written in PHP that I'm thinking of converting to Python - both are websites that started as simple static html, then progressed to PHP and now include blogs with admin areas, rss etc. I'm thinking of rewriting them in Python to improve maintainability as well as to take advantage of my increase in experience to write things more robustly.</p>
<p>Is this worth the effort?</p>
| 6 | 2008-12-04T11:48:19Z | 340,342 | <p>Well, it depends... ;) If you're going to use the old code together with new Python code, it might be useful, not so much for speed but for easier integration. But usually: "If it ain't broke, don't fix it". Allso rewriting can result in better code, but only do it if you need to.</p>
<p>As a hobby project of course it's worth it, cause the process is the goal.</p>
| 2 | 2008-12-04T11:57:32Z | [
"php",
"python"
] |
Is rewriting a PHP app into Python a productive step? | 340,318 | <p>I have some old apps written in PHP that I'm thinking of converting to Python - both are websites that started as simple static html, then progressed to PHP and now include blogs with admin areas, rss etc. I'm thinking of rewriting them in Python to improve maintainability as well as to take advantage of my increase in experience to write things more robustly.</p>
<p>Is this worth the effort?</p>
| 6 | 2008-12-04T11:48:19Z | 340,398 | <p>Rewrites are very expensive: you spend a lot of time doing something which doesn't directly help you. Joel Spolsky elaborates on this:</p>
<p><a href="http://www.joelonsoftware.com/articles/fog0000000069.html" rel="nofollow">Things You Should Never Do, Part I</a></p>
<p>You should do it if the benefits outweigh the costs; just be careful that you don't underestimate the costs.</p>
| 2 | 2008-12-04T12:17:20Z | [
"php",
"python"
] |
Is rewriting a PHP app into Python a productive step? | 340,318 | <p>I have some old apps written in PHP that I'm thinking of converting to Python - both are websites that started as simple static html, then progressed to PHP and now include blogs with admin areas, rss etc. I'm thinking of rewriting them in Python to improve maintainability as well as to take advantage of my increase in experience to write things more robustly.</p>
<p>Is this worth the effort?</p>
| 6 | 2008-12-04T11:48:19Z | 340,604 | <p>As others have said, look at why you are doing it.</p>
<p>For instance, at work I am rewriting our existing inventory/sales system to a Python/django backend. Why? Because the existing PHP code base is stale, and is going to scale poorly as we grow our business (plus it was built when our business model was different, then patched up to match our current needs which resulted in some spaghetti code)</p>
<p>So basically, if you think you're going to benefit from it in ways that aren't just "sweet this is in python now!" then go for it.</p>
| 2 | 2008-12-04T13:39:05Z | [
"php",
"python"
] |
Is rewriting a PHP app into Python a productive step? | 340,318 | <p>I have some old apps written in PHP that I'm thinking of converting to Python - both are websites that started as simple static html, then progressed to PHP and now include blogs with admin areas, rss etc. I'm thinking of rewriting them in Python to improve maintainability as well as to take advantage of my increase in experience to write things more robustly.</p>
<p>Is this worth the effort?</p>
| 6 | 2008-12-04T11:48:19Z | 340,685 | <p>If you are going to add more features to the code you already have working, then it might be a good idea to port it to python. After all, it will get you increased productivity. You just have to balance it, whether the rewriting task will not outweigh the potential gain... </p>
<p>And also, when you do that, try to unittest as much as you can.</p>
| 1 | 2008-12-04T14:07:12Z | [
"php",
"python"
] |
Is rewriting a PHP app into Python a productive step? | 340,318 | <p>I have some old apps written in PHP that I'm thinking of converting to Python - both are websites that started as simple static html, then progressed to PHP and now include blogs with admin areas, rss etc. I'm thinking of rewriting them in Python to improve maintainability as well as to take advantage of my increase in experience to write things more robustly.</p>
<p>Is this worth the effort?</p>
| 6 | 2008-12-04T11:48:19Z | 340,719 | <p>Other issues include how business critical are the applications and how hard will it be to find maintainers. If the pages are hobbies of yours then I don't see a reason why you shouldn't rewrite them since if you introduce bugs or the rewrite doesn't go according to schedule a business won't lose money. If the application is central to a business I wouldnât rewrite it unless you are running into limitations with the current design that can not be overcome with out a complete rewrite at which point the language choice is secondary to the fact that you need to throw out several years of work because itâs not maintainable and no longer meets your needs.</p>
| 0 | 2008-12-04T14:14:49Z | [
"php",
"python"
] |
Is rewriting a PHP app into Python a productive step? | 340,318 | <p>I have some old apps written in PHP that I'm thinking of converting to Python - both are websites that started as simple static html, then progressed to PHP and now include blogs with admin areas, rss etc. I'm thinking of rewriting them in Python to improve maintainability as well as to take advantage of my increase in experience to write things more robustly.</p>
<p>Is this worth the effort?</p>
| 6 | 2008-12-04T11:48:19Z | 340,792 | <p>As others have said, re-writing will take a lot longer than you think and fixing all the bugs and making use everything worked like in the old version will take even longer. Chances are you are better off simply improving and refactoring the php code you have. There are only a few good reasons to port a project from one language to another:</p>
<ol>
<li>Performance. Some languages are simply faster than others, and there comes a point where there is nothing left to optimize and throwing hardware at the problem ceases to be effective. </li>
<li>Maintainability. Sometimes it is hard to find good people who know some obscure language which your legacy code is written in. In those cases it might be a good idea to re-write it in a more popular language to ease maintenance down the road.</li>
<li>Porting to a different platform. If you all of a sudden need to make your old VB program run on OS X and Linux as well as Windows then youâre probably looking at a re-write in a different language</li>
</ol>
<p>In your case it doesn't seem like any of the above points hold. Of course if it's an unimportant app and you want to do it for the learning experience then by all means go for it, but from a business or economic point of view I'd take a long hard look at what such a re-write will cost and what exactly you hope to gain.</p>
| 1 | 2008-12-04T14:40:13Z | [
"php",
"python"
] |
Is rewriting a PHP app into Python a productive step? | 340,318 | <p>I have some old apps written in PHP that I'm thinking of converting to Python - both are websites that started as simple static html, then progressed to PHP and now include blogs with admin areas, rss etc. I'm thinking of rewriting them in Python to improve maintainability as well as to take advantage of my increase in experience to write things more robustly.</p>
<p>Is this worth the effort?</p>
| 6 | 2008-12-04T11:48:19Z | 340,877 | <p>One item that has not come up is the size of the current code base. Depending on how much code there is should influence your decision. </p>
<p><a href="http://www.joelonsoftware.com/articles/fog0000000069.html" rel="nofollow">Joel Spolsky's</a> argument to never rewrite is valid in the context of a code base the size of Netscape. Whereas a smaller code base code significantly benefit from the rewrite.</p>
| 0 | 2008-12-04T15:03:10Z | [
"php",
"python"
] |
Is rewriting a PHP app into Python a productive step? | 340,318 | <p>I have some old apps written in PHP that I'm thinking of converting to Python - both are websites that started as simple static html, then progressed to PHP and now include blogs with admin areas, rss etc. I'm thinking of rewriting them in Python to improve maintainability as well as to take advantage of my increase in experience to write things more robustly.</p>
<p>Is this worth the effort?</p>
| 6 | 2008-12-04T11:48:19Z | 341,834 | <p>I did a conversion between a PHP site and a Turbogears(Python) site for my company. The initial reason for doing so was two fold, first so a redesign would be easier and second that features could be easily added. It did take a while to get the full conversion done, but what we end up with was a very flexible back end and an even more flexible and readable front end. We've added several features that would have been very hard in PHP and we are currently doing a complete overhaul of the front end, which is turning out to be very easy.</p>
<p>In short it's something I would recommend, and my boss would probably say the same thing. Some people here are making good points though. Python isn't as fast as what PHP can give you, but what it lacks in performance it more then makes up for in versatility.</p>
| 1 | 2008-12-04T19:55:51Z | [
"php",
"python"
] |
Suppressing Output of Paramiko SSHClient Class | 340,341 | <p>When I call the connect function of the Paramiko <code>SSHClient</code> class, it outputs some log data about establishing the connection, which I would like to suppress.</p>
<p>Is there a way to do this either through Paramiko itself, or Python in general?</p>
| 4 | 2008-12-04T11:56:59Z | 340,815 | <p>I don't know what Paramiko is, and there must be a log level setting for sure, but if you are desperate and looking for a temporary solution and if your app is single threaded</p>
<pre><code>import sys
dev_null = sys.stdout = sys.stderr = open('/dev/null', 'w')
try:
.
. connect()
.
finally:
dev_null.close()
</code></pre>
<p>you can use StringIO for output also, if you are on an OS not have a '/dev/null'</p>
| 0 | 2008-12-04T14:48:33Z | [
"python",
"paramiko"
] |
Suppressing Output of Paramiko SSHClient Class | 340,341 | <p>When I call the connect function of the Paramiko <code>SSHClient</code> class, it outputs some log data about establishing the connection, which I would like to suppress.</p>
<p>Is there a way to do this either through Paramiko itself, or Python in general?</p>
| 4 | 2008-12-04T11:56:59Z | 340,896 | <p>Paramiko doesn't output anything by default. You probably have a call to the logging module, setting a loglevel that's inherited when paramiko sets up it's own logging.</p>
<p>If you want to get at the paramiko logger to override the settings:</p>
<pre><code>logger = paramiko.util.logging.getLogger()
</code></pre>
<p>There's also a convenience function to log everything to a file:</p>
<pre><code>paramiko.util.log_to_file('filename.log')
</code></pre>
| 7 | 2008-12-04T15:08:27Z | [
"python",
"paramiko"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.