title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags list |
|---|---|---|---|---|---|---|---|---|---|
Run a Python project in Eclipse as root | 981,411 | <p>I use Eclipse as my IDE, and when I run my application I wish the application itself to run as root. My program currently checks if it is root, and if not it restarts itself with <code>gksudo</code>. The output, however, isn't written to the console. I can't use <code>sudo</code>, since it doesn't give me a graphical prompt. (While my program is CLI, Eclipse doesn't permit console interaction afaict)</p>
<p>What's the "right" way to be elevating my application?</p>
| 8 | 2009-06-11T14:24:30Z | 33,567,564 | <p>You might need to create a runner with external tools pointing to '/sur/bin/sudo' and pointing to variable ${resource_loc}
Run -> External tools -> External Tools Configuration
The below link will guide you on creating a external runner,</p>
<p><a href="http://help.eclipse.org/mars/index.jsp?topic=%2Forg.eclipse.platform.doc.user%2FgettingStarted%2Fqs-97_standalone_ets.htm" rel="nofollow">http://help.eclipse.org/mars/index.jsp?topic=%2Forg.eclipse.platform.doc.user%2FgettingStarted%2Fqs-97_standalone_ets.htm</a></p>
<p>To run,
Click on the main python file
Run -> External tools -> {choose your runner}</p>
<p>This will serve your purpose.</p>
| 0 | 2015-11-06T13:08:57Z | [
"python",
"eclipse",
"root",
"sudo",
"gksudo"
] |
windows command line and Python | 981,691 | <p>I have a python script that i want to run from the command line but unsure how to run it. Thanks :)</p>
| 1 | 2009-06-11T15:07:05Z | 981,705 | <p><code>python myscript.py</code></p>
| 3 | 2009-06-11T15:08:56Z | [
"python",
"windows",
"command-line"
] |
windows command line and Python | 981,691 | <p>I have a python script that i want to run from the command line but unsure how to run it. Thanks :)</p>
| 1 | 2009-06-11T15:07:05Z | 981,707 | <p>See <a href="http://www.voidspace.org.uk/python/articles/command%5Fline.shtml#path" rel="nofollow">Basic Hints for Windows Command Line Programming</a>.</p>
<p>If your python installation directory is included in <code>%PATH%</code> -</p>
<pre><code>C:\> python myscript.py
</code></pre>
<p>If you know the installation path:</p>
<pre><code>C:\> C:\python26\python myscript.py
</code></pre>
<p>And, you can insert a <code>hashbang</code> in the 1st line of the script:</p>
<pre><code>#! C:\python26\python
</code></pre>
<p>and it will run by typing just the script name. This is the content of <code>p.py</code>:</p>
<pre><code>#!C:\python26\python
import sys
print sys.path
</code></pre>
<p>And calling it directly from a <code>cmd.exe</code> window:</p>
<pre><code>C:\>p.py
['C:\\WINDOWS\\system32\\python26.zip', 'C:\\Python26\\DLLs',
'C:\\Python26\\lib', 'C:\\Python26\\lib\\plat-win',
'C:\\Python26', 'C:\\Python26\\lib\\site-packages',
'C:\\Python26\\lib\\site-packages\\win32', 'C:\\Python26\\lib]
</code></pre>
| 3 | 2009-06-11T15:09:33Z | [
"python",
"windows",
"command-line"
] |
windows command line and Python | 981,691 | <p>I have a python script that i want to run from the command line but unsure how to run it. Thanks :)</p>
| 1 | 2009-06-11T15:07:05Z | 981,711 | <p>If your script is foo.py, you can simply do</p>
<pre><code>C:\Python25\python.exe foo.py
</code></pre>
<p>Assuming you have python 2.5 installed in the default location. Alternatively, you can add C:\Python25 to your %PATH%, so that:</p>
<pre><code>python foo.py
</code></pre>
<p>will work. But be aware that changing %PATH% may affect applications (that's why it is not done by the python installer by default).</p>
| 2 | 2009-06-11T15:10:17Z | [
"python",
"windows",
"command-line"
] |
windows command line and Python | 981,691 | <p>I have a python script that i want to run from the command line but unsure how to run it. Thanks :)</p>
| 1 | 2009-06-11T15:07:05Z | 981,712 | <p>I do it this way:</p>
<pre><code>C:\path\to\folder> yourscript.py
</code></pre>
| 4 | 2009-06-11T15:10:18Z | [
"python",
"windows",
"command-line"
] |
windows command line and Python | 981,691 | <p>I have a python script that i want to run from the command line but unsure how to run it. Thanks :)</p>
| 1 | 2009-06-11T15:07:05Z | 981,725 | <ol>
<li>do you have python installed? if not
install it from python.org</li>
<li><p>on command line use </p>
<p>python "path to
script.py"</p></li>
<li><p>if python is not in PATH
list you can add it to PATH in
environment variables or directly
use path to python.exe e.g. </p>
<pre><code> c:\python25\python.exe myscript.py
</code></pre></li>
</ol>
| 0 | 2009-06-11T15:13:32Z | [
"python",
"windows",
"command-line"
] |
windows command line and Python | 981,691 | <p>I have a python script that i want to run from the command line but unsure how to run it. Thanks :)</p>
| 1 | 2009-06-11T15:07:05Z | 981,747 | <p>You might find it useful to include a .bat file which calls the .py script. Then all you need to do is to type the name of your script to run it.</p>
<p>Try something like:
python %~dp0\%~n0.py %*</p>
<p>(From <a href="http://wiki.tcl.tk/2455" rel="nofollow">http://wiki.tcl.tk/2455</a>)</p>
| 0 | 2009-06-11T15:17:15Z | [
"python",
"windows",
"command-line"
] |
python automatic (or dynamic) import classes in packages | 981,753 | <p>I'm writing some kind of automated test suite and I want to make sure the classes contained in the package 'tests' get imported automatically upon runtime in the main namespace, without adding them to the <code>__init__</code> file of the package.</p>
<p>So here is the script I have so far:</p>
<pre><code>import os
for dirpath, dirnames, filenames in os.walk('tests'):
for filename in filenames:
if filename.lower().endswith(('.pyc', '__init__.py')): continue
module = ".".join([dirpath, filename.split('.')[0]])
print module
</code></pre>
<p>If I use <code>modulename = __import__(module)</code> the classes get added to the module 'modulename' and not the main namespace.</p>
<p>My question is, how do I import them to the current namespace?</p>
<p>So I can do things like:</p>
<pre><code>testcase = TestCase()
testcase.run()
results = testcase.results()
</code></pre>
<p>or whatever in the main script without explicitly importing the classes.</p>
<p>Thanks in advance!</p>
<p>Thank you all for replying and trying to help me out.</p>
| 2 | 2009-06-11T15:17:55Z | 981,816 | <p>I do not fully understand the need because you can collect all the modules and iterate thru test case classes</p>
<p>but if you do want to get all names in current scope
use something like</p>
<pre><code>execfile("mod.py")
</code></pre>
<p>it will get all classed defined in mod.py into scope</p>
| 0 | 2009-06-11T15:29:04Z | [
"python"
] |
python automatic (or dynamic) import classes in packages | 981,753 | <p>I'm writing some kind of automated test suite and I want to make sure the classes contained in the package 'tests' get imported automatically upon runtime in the main namespace, without adding them to the <code>__init__</code> file of the package.</p>
<p>So here is the script I have so far:</p>
<pre><code>import os
for dirpath, dirnames, filenames in os.walk('tests'):
for filename in filenames:
if filename.lower().endswith(('.pyc', '__init__.py')): continue
module = ".".join([dirpath, filename.split('.')[0]])
print module
</code></pre>
<p>If I use <code>modulename = __import__(module)</code> the classes get added to the module 'modulename' and not the main namespace.</p>
<p>My question is, how do I import them to the current namespace?</p>
<p>So I can do things like:</p>
<pre><code>testcase = TestCase()
testcase.run()
results = testcase.results()
</code></pre>
<p>or whatever in the main script without explicitly importing the classes.</p>
<p>Thanks in advance!</p>
<p>Thank you all for replying and trying to help me out.</p>
| 2 | 2009-06-11T15:17:55Z | 981,980 | <p>I'm not sure I exactly understand your question, but you might try <a href="http://somethingaboutorange.com/mrl/projects/nose/" rel="nofollow">nose</a> to <a href="http://www.somethingaboutorange.com/mrl/projects/nose/0.11.1/finding%5Ftests.html" rel="nofollow">discover</a> your test suites.</p>
| 1 | 2009-06-11T15:56:16Z | [
"python"
] |
python automatic (or dynamic) import classes in packages | 981,753 | <p>I'm writing some kind of automated test suite and I want to make sure the classes contained in the package 'tests' get imported automatically upon runtime in the main namespace, without adding them to the <code>__init__</code> file of the package.</p>
<p>So here is the script I have so far:</p>
<pre><code>import os
for dirpath, dirnames, filenames in os.walk('tests'):
for filename in filenames:
if filename.lower().endswith(('.pyc', '__init__.py')): continue
module = ".".join([dirpath, filename.split('.')[0]])
print module
</code></pre>
<p>If I use <code>modulename = __import__(module)</code> the classes get added to the module 'modulename' and not the main namespace.</p>
<p>My question is, how do I import them to the current namespace?</p>
<p>So I can do things like:</p>
<pre><code>testcase = TestCase()
testcase.run()
results = testcase.results()
</code></pre>
<p>or whatever in the main script without explicitly importing the classes.</p>
<p>Thanks in advance!</p>
<p>Thank you all for replying and trying to help me out.</p>
| 2 | 2009-06-11T15:17:55Z | 981,997 | <p>To get classes from some module, there can be better way but here is generic way to get you started</p>
<pre><code>mod = __import__("mod")
for klass in vars(mod):
o = getattr(mod, klass)
if type(o) == type:
print o
</code></pre>
| 3 | 2009-06-11T15:59:05Z | [
"python"
] |
python automatic (or dynamic) import classes in packages | 981,753 | <p>I'm writing some kind of automated test suite and I want to make sure the classes contained in the package 'tests' get imported automatically upon runtime in the main namespace, without adding them to the <code>__init__</code> file of the package.</p>
<p>So here is the script I have so far:</p>
<pre><code>import os
for dirpath, dirnames, filenames in os.walk('tests'):
for filename in filenames:
if filename.lower().endswith(('.pyc', '__init__.py')): continue
module = ".".join([dirpath, filename.split('.')[0]])
print module
</code></pre>
<p>If I use <code>modulename = __import__(module)</code> the classes get added to the module 'modulename' and not the main namespace.</p>
<p>My question is, how do I import them to the current namespace?</p>
<p>So I can do things like:</p>
<pre><code>testcase = TestCase()
testcase.run()
results = testcase.results()
</code></pre>
<p>or whatever in the main script without explicitly importing the classes.</p>
<p>Thanks in advance!</p>
<p>Thank you all for replying and trying to help me out.</p>
| 2 | 2009-06-11T15:17:55Z | 983,427 | <p>you could use the exec on a formatted string for each module name in your scanned directory:</p>
<pre><code>exec "from %s import *" % moduleName
</code></pre>
| 0 | 2009-06-11T20:20:15Z | [
"python"
] |
python automatic (or dynamic) import classes in packages | 981,753 | <p>I'm writing some kind of automated test suite and I want to make sure the classes contained in the package 'tests' get imported automatically upon runtime in the main namespace, without adding them to the <code>__init__</code> file of the package.</p>
<p>So here is the script I have so far:</p>
<pre><code>import os
for dirpath, dirnames, filenames in os.walk('tests'):
for filename in filenames:
if filename.lower().endswith(('.pyc', '__init__.py')): continue
module = ".".join([dirpath, filename.split('.')[0]])
print module
</code></pre>
<p>If I use <code>modulename = __import__(module)</code> the classes get added to the module 'modulename' and not the main namespace.</p>
<p>My question is, how do I import them to the current namespace?</p>
<p>So I can do things like:</p>
<pre><code>testcase = TestCase()
testcase.run()
results = testcase.results()
</code></pre>
<p>or whatever in the main script without explicitly importing the classes.</p>
<p>Thanks in advance!</p>
<p>Thank you all for replying and trying to help me out.</p>
| 2 | 2009-06-11T15:17:55Z | 15,397,425 | <p>Place this code in __init__.py of the tests package and it will import all tests in the current package and subpackages.</p>
<pre><code>import pkgutil
import unittest
for loader, module_name, is_pkg in pkgutil.walk_packages(__path__):
module = loader.find_module(module_name).load_module(module_name)
for name in dir(module):
obj = getattr(module, name)
if isinstance(obj, type) and issubclass(obj, unittest.case.TestCase):
exec ('%s = obj' % obj.__name__)
</code></pre>
<p>As others have said, if you're trying to have all of your tests discovered, there are better ways.</p>
| 0 | 2013-03-13T22:07:09Z | [
"python"
] |
python automatic (or dynamic) import classes in packages | 981,753 | <p>I'm writing some kind of automated test suite and I want to make sure the classes contained in the package 'tests' get imported automatically upon runtime in the main namespace, without adding them to the <code>__init__</code> file of the package.</p>
<p>So here is the script I have so far:</p>
<pre><code>import os
for dirpath, dirnames, filenames in os.walk('tests'):
for filename in filenames:
if filename.lower().endswith(('.pyc', '__init__.py')): continue
module = ".".join([dirpath, filename.split('.')[0]])
print module
</code></pre>
<p>If I use <code>modulename = __import__(module)</code> the classes get added to the module 'modulename' and not the main namespace.</p>
<p>My question is, how do I import them to the current namespace?</p>
<p>So I can do things like:</p>
<pre><code>testcase = TestCase()
testcase.run()
results = testcase.results()
</code></pre>
<p>or whatever in the main script without explicitly importing the classes.</p>
<p>Thanks in advance!</p>
<p>Thank you all for replying and trying to help me out.</p>
| 2 | 2009-06-11T15:17:55Z | 32,368,953 | <p>Instead of using <code>__import__</code> and assign it to a variable like this</p>
<pre><code>modulename = __import__(module)
</code></pre>
<p>Use <code>importlib.import_module</code> instead, and don't assign it:</p>
<pre><code>import importlib
importlib.import_module(module)
</code></pre>
<p>At least on Python 3.4, this works fine.</p>
| 0 | 2015-09-03T07:00:04Z | [
"python"
] |
How to tractably solve the assignment optimisation task | 982,127 | <p>I'm working on a script that takes the elements from <code>companies</code> and pairs them up with the elements of <code>people</code>. The goal is to optimize the pairings such that the sum of all pair values is maximized (the value of each individual pairing is precomputed and stored in the dictionary <code>ctrPairs</code>). </p>
<p>They're all paired in a 1:1, each company has only one person and each person belongs to only one company, and the number of companies is equal to the number of people. I used a top-down approach with a memoization table (<code>memDict</code>) to avoid recomputing areas that have already been solved. </p>
<p>I believe that I could vastly improve the speed of what's going on here but I'm not really sure how. Areas I'm worried about are marked with <code>#slow?</code>, any advice would be appreciated (the script works for inputs of lists n<15 but it gets incredibly slow for n > ~15)</p>
<pre><code>def getMaxCTR(companies, people):
if(memDict.has_key((companies,people))):
return memDict[(companies,people)] #here's where we return the memoized version if it exists
if(not len(companies) or not len(people)):
return 0
maxCTR = None
remainingCompanies = companies[1:len(companies)] #slow?
for p in people:
remainingPeople = list(people) #slow?
remainingPeople.remove(p) #slow?
ctr = ctrPairs[(companies[0],p)] + getMaxCTR(remainingCompanies,tuple(remainingPeople)) #recurse
if(ctr > maxCTR):
maxCTR = ctr
memDict[(companies,people)] = maxCTR
return maxCTR
</code></pre>
| 3 | 2009-06-11T16:22:48Z | 982,219 | <p>This line:</p>
<p>remainingCompanies = companies[1:len(companies)]</p>
<p>Can be replaced with this line:</p>
<pre><code>remainingCompanies = companies[1:]
</code></pre>
<p>For a very slight speed increase. That's the only improvement I see.</p>
| 0 | 2009-06-11T16:39:58Z | [
"python",
"algorithm",
"optimization",
"dynamic-programming"
] |
How to tractably solve the assignment optimisation task | 982,127 | <p>I'm working on a script that takes the elements from <code>companies</code> and pairs them up with the elements of <code>people</code>. The goal is to optimize the pairings such that the sum of all pair values is maximized (the value of each individual pairing is precomputed and stored in the dictionary <code>ctrPairs</code>). </p>
<p>They're all paired in a 1:1, each company has only one person and each person belongs to only one company, and the number of companies is equal to the number of people. I used a top-down approach with a memoization table (<code>memDict</code>) to avoid recomputing areas that have already been solved. </p>
<p>I believe that I could vastly improve the speed of what's going on here but I'm not really sure how. Areas I'm worried about are marked with <code>#slow?</code>, any advice would be appreciated (the script works for inputs of lists n<15 but it gets incredibly slow for n > ~15)</p>
<pre><code>def getMaxCTR(companies, people):
if(memDict.has_key((companies,people))):
return memDict[(companies,people)] #here's where we return the memoized version if it exists
if(not len(companies) or not len(people)):
return 0
maxCTR = None
remainingCompanies = companies[1:len(companies)] #slow?
for p in people:
remainingPeople = list(people) #slow?
remainingPeople.remove(p) #slow?
ctr = ctrPairs[(companies[0],p)] + getMaxCTR(remainingCompanies,tuple(remainingPeople)) #recurse
if(ctr > maxCTR):
maxCTR = ctr
memDict[(companies,people)] = maxCTR
return maxCTR
</code></pre>
| 3 | 2009-06-11T16:22:48Z | 982,300 | <p>If you want to get a copy of a tuple as a list you can do
mylist = list(mytuple)</p>
| 0 | 2009-06-11T16:54:22Z | [
"python",
"algorithm",
"optimization",
"dynamic-programming"
] |
How to tractably solve the assignment optimisation task | 982,127 | <p>I'm working on a script that takes the elements from <code>companies</code> and pairs them up with the elements of <code>people</code>. The goal is to optimize the pairings such that the sum of all pair values is maximized (the value of each individual pairing is precomputed and stored in the dictionary <code>ctrPairs</code>). </p>
<p>They're all paired in a 1:1, each company has only one person and each person belongs to only one company, and the number of companies is equal to the number of people. I used a top-down approach with a memoization table (<code>memDict</code>) to avoid recomputing areas that have already been solved. </p>
<p>I believe that I could vastly improve the speed of what's going on here but I'm not really sure how. Areas I'm worried about are marked with <code>#slow?</code>, any advice would be appreciated (the script works for inputs of lists n<15 but it gets incredibly slow for n > ~15)</p>
<pre><code>def getMaxCTR(companies, people):
if(memDict.has_key((companies,people))):
return memDict[(companies,people)] #here's where we return the memoized version if it exists
if(not len(companies) or not len(people)):
return 0
maxCTR = None
remainingCompanies = companies[1:len(companies)] #slow?
for p in people:
remainingPeople = list(people) #slow?
remainingPeople.remove(p) #slow?
ctr = ctrPairs[(companies[0],p)] + getMaxCTR(remainingCompanies,tuple(remainingPeople)) #recurse
if(ctr > maxCTR):
maxCTR = ctr
memDict[(companies,people)] = maxCTR
return maxCTR
</code></pre>
| 3 | 2009-06-11T16:22:48Z | 982,306 | <p>To all those who wonder about the use of learning theory, this question is a good illustration. The right question is not about a "fast way to bounce between lists and tuples in python" â the reason for the slowness is something deeper.</p>
<p>What you're trying to solve here is known as the <a href="http://en.wikipedia.org/wiki/Assignment_problem">assignment problem</a>: given two lists of n elements each and n×n values (the value of each pair), how to assign them so that the total "value" is maximized (or equivalently, minimized). There are several algorithms for this, such as the <a href="http://en.wikipedia.org/wiki/Hungarian_algorithm">Hungarian algorithm</a> (<a href="http://www.clapper.org/software/python/munkres/">Python implementation</a>), or you could solve it using more general min-cost flow algorithms, or even cast it as a linear program and use an LP solver. Most of these would have a running time of O(n<sup>3</sup>).</p>
<p>What your algorithm above does is to try each possible way of pairing them. (The memoisation only helps to avoid recomputing answers for pairs of subsets, but you're still looking at all pairs of subsets.) This approach is at least Ω(n<sup>2</sup>2<sup>2n</sup>). For n=16, n<sup>3</sup> is 4096 and n<sup>2</sup>2<sup>2n</sup> is 1099511627776. There are constant factors in each algorithm of course, but see the difference? :-) (The approach in the question is still better than the naive O(n!), which would be much worse.) Use one of the O(n^3) algorithms, and I predict it should run in time for up to n=10000 or so, instead of just up to n=15. </p>
<p>"Premature optimization is the root of all evil", as Knuth said, but so is delayed/overdue optimization: you should first carefully consider an appropriate algorithm before implementing it, not pick a bad one and then wonder what parts of it are slow. :-) Even badly implementing a good algorithm in Python would be orders of magnitude faster than fixing all the "slow?" parts of the code above (e.g., by rewriting in C).</p>
| 19 | 2009-06-11T16:55:18Z | [
"python",
"algorithm",
"optimization",
"dynamic-programming"
] |
How to tractably solve the assignment optimisation task | 982,127 | <p>I'm working on a script that takes the elements from <code>companies</code> and pairs them up with the elements of <code>people</code>. The goal is to optimize the pairings such that the sum of all pair values is maximized (the value of each individual pairing is precomputed and stored in the dictionary <code>ctrPairs</code>). </p>
<p>They're all paired in a 1:1, each company has only one person and each person belongs to only one company, and the number of companies is equal to the number of people. I used a top-down approach with a memoization table (<code>memDict</code>) to avoid recomputing areas that have already been solved. </p>
<p>I believe that I could vastly improve the speed of what's going on here but I'm not really sure how. Areas I'm worried about are marked with <code>#slow?</code>, any advice would be appreciated (the script works for inputs of lists n<15 but it gets incredibly slow for n > ~15)</p>
<pre><code>def getMaxCTR(companies, people):
if(memDict.has_key((companies,people))):
return memDict[(companies,people)] #here's where we return the memoized version if it exists
if(not len(companies) or not len(people)):
return 0
maxCTR = None
remainingCompanies = companies[1:len(companies)] #slow?
for p in people:
remainingPeople = list(people) #slow?
remainingPeople.remove(p) #slow?
ctr = ctrPairs[(companies[0],p)] + getMaxCTR(remainingCompanies,tuple(remainingPeople)) #recurse
if(ctr > maxCTR):
maxCTR = ctr
memDict[(companies,people)] = maxCTR
return maxCTR
</code></pre>
| 3 | 2009-06-11T16:22:48Z | 982,331 | <p>i see two issues here:</p>
<ol>
<li><p>efficiency: you're recreating the same <code>remainingPeople</code> sublists for each company. it would be better to create all the <code>remainingPeople</code> and all the <code>remainingCompanies</code> once and then do all the combinations.</p></li>
<li><p>memoization: you're using tuples instead of lists to use them as <code>dict</code> keys for memoization; but tuple identity is order-sensitive. IOW: <code>(1,2) != (2,1)</code> you better use <code>set</code>s and <code>frozenset</code>s for this: <code>frozenset((1,2)) == frozenset((2,1))</code></p></li>
</ol>
| 1 | 2009-06-11T16:59:58Z | [
"python",
"algorithm",
"optimization",
"dynamic-programming"
] |
Trac Using Database Authentication | 982,226 | <p>Is it possible to use a database for authentication with Trac?
.htpasswd auth is not desired in this install.</p>
<p>Using Trac .11 and MySQL as the database. Trac is currently using the database, but provides no authentication.</p>
| 5 | 2009-06-11T16:40:52Z | 982,345 | <p>Out of the box, <a href="http://trac.edgewall.org/wiki/TracAuthenticationIntroduction" rel="nofollow">Trac doesn't actually do its own authentication</a>, it leaves it up to the web server. So, you've got a wealth of Apache-related options available to you. You could maybe look at something like <a href="http://sourceforge.net/projects/modauthmysql" rel="nofollow">auth_mysql</a> to let you keep user credentials in a database.</p>
<p>Alternatively, take a look at the <a href="http://trac-hacks.org/wiki/AccountManagerPlugin" rel="nofollow">AccountManagerPlugin</a> on trac-hacks.org</p>
| 5 | 2009-06-11T17:03:07Z | [
"python",
"mysql",
"apache",
"trac"
] |
Trac Using Database Authentication | 982,226 | <p>Is it possible to use a database for authentication with Trac?
.htpasswd auth is not desired in this install.</p>
<p>Using Trac .11 and MySQL as the database. Trac is currently using the database, but provides no authentication.</p>
| 5 | 2009-06-11T16:40:52Z | 982,372 | <p>You can use <a href="http://trac-hacks.org/wiki/AccountManagerPlugin#SessionStore" rel="nofollow">Account Manager Plugin with SessionStore</a></p>
<p>The AccountManagerPlugin offers several features for managing user accounts: </p>
<ul>
<li>allow users to register new accounts </li>
<li>login via an HTML form instead of using HTTP authentication </li>
<li>allow existing users to change their passwords or delete their accounts </li>
<li>send a new password to users whoâve forgotten their password </li>
<li>administration of user accounts</li>
</ul>
| 1 | 2009-06-11T17:08:50Z | [
"python",
"mysql",
"apache",
"trac"
] |
Trac Using Database Authentication | 982,226 | <p>Is it possible to use a database for authentication with Trac?
.htpasswd auth is not desired in this install.</p>
<p>Using Trac .11 and MySQL as the database. Trac is currently using the database, but provides no authentication.</p>
| 5 | 2009-06-11T16:40:52Z | 3,609,831 | <p>Please refer to <a href="http://trac-hacks.org/wiki/AccountManagerPlugin" rel="nofollow">http://trac-hacks.org/wiki/AccountManagerPlugin</a></p>
<p>Do the following on your trac.ini
[components]
; be sure to enable the component
acct_mgr.svnserve.* = enabled
acct_mgr.svnserve.svnservepasswordstore = enabled
; choose one of the hash methods
acct_mgr.pwhash.htdigesthashmethod = enabled
acct_mgr.pwhash.htpasswdhashmethod = enabled</p>
<p>[account-manager]
password_store = SvnServePasswordStore
password_file = /path/to/svn/repos/conf/passwd
; choose one of the hash methods
hash_method = HtDigestHashMethod
hash_method = HtPasswdHashMethod</p>
<p>Now trac will use user in the database</p>
| 0 | 2010-08-31T14:10:04Z | [
"python",
"mysql",
"apache",
"trac"
] |
Obfuscate strings in Python | 982,260 | <p>I have a password string that must be passed to a method. Everything works fine but I don't feel comfortable storing the password in clear text. Is there a way to obfuscate the string or to truly encrypt it? I'm aware that obfuscation can be reverse engineered, but I think I should at least try to cover up the password a bit. At the very least it wont be visible to a indexing program, or a stray eye giving a quick look at my code.</p>
<p>I am aware of pyobfuscate but I don't want the whole program obfuscated, just one string and possibly the whole line itself where the variable is defined.</p>
<p>Target platform is GNU Linux Generic (If that makes a difference)</p>
| 7 | 2009-06-11T16:47:30Z | 982,287 | <p>Many password-accepting protocols and facilities have a way to specify a keyfile rather than a password. That strategy will probably work here; rather than hard-coding a password, hard-code a filename (or better yet, make it a parameter!). You could even go as far as SSH and refuse to load keyfiles that aren't (1) owned by the current user (2) only readable by that user.</p>
| 0 | 2009-06-11T16:52:00Z | [
"python",
"linux",
"encryption",
"passwords",
"obfuscation"
] |
Obfuscate strings in Python | 982,260 | <p>I have a password string that must be passed to a method. Everything works fine but I don't feel comfortable storing the password in clear text. Is there a way to obfuscate the string or to truly encrypt it? I'm aware that obfuscation can be reverse engineered, but I think I should at least try to cover up the password a bit. At the very least it wont be visible to a indexing program, or a stray eye giving a quick look at my code.</p>
<p>I am aware of pyobfuscate but I don't want the whole program obfuscated, just one string and possibly the whole line itself where the variable is defined.</p>
<p>Target platform is GNU Linux Generic (If that makes a difference)</p>
| 7 | 2009-06-11T16:47:30Z | 982,288 | <p>You should avoid storing the password in clear in the first place. That's the only "true" solution.</p>
<p>Now, you can encrypt the password easily with the hash module (md5 and similar modules in python 2.5 and below).</p>
<pre><code>import hashlib
mypass = "yo"
a = hashlib.sha256(mypass).digest()
</code></pre>
| 1 | 2009-06-11T16:52:01Z | [
"python",
"linux",
"encryption",
"passwords",
"obfuscation"
] |
Obfuscate strings in Python | 982,260 | <p>I have a password string that must be passed to a method. Everything works fine but I don't feel comfortable storing the password in clear text. Is there a way to obfuscate the string or to truly encrypt it? I'm aware that obfuscation can be reverse engineered, but I think I should at least try to cover up the password a bit. At the very least it wont be visible to a indexing program, or a stray eye giving a quick look at my code.</p>
<p>I am aware of pyobfuscate but I don't want the whole program obfuscated, just one string and possibly the whole line itself where the variable is defined.</p>
<p>Target platform is GNU Linux Generic (If that makes a difference)</p>
| 7 | 2009-06-11T16:47:30Z | 982,310 | <p>If you just want to prevent casually glancing at a password, you may want to consider encoding/decoding the password to/from <a href="http://docs.python.org/library/base64.html">base64</a>. It's not secure in the least, but the password won't be casually human/robot readable.</p>
<pre><code>import base64
# Encode password
encoded_pw = base64.b64encode(raw_pw)
# Decode password
decoded_pw = base64.b64decode(encoded_pw)
</code></pre>
| 20 | 2009-06-11T16:57:06Z | [
"python",
"linux",
"encryption",
"passwords",
"obfuscation"
] |
Obfuscate strings in Python | 982,260 | <p>I have a password string that must be passed to a method. Everything works fine but I don't feel comfortable storing the password in clear text. Is there a way to obfuscate the string or to truly encrypt it? I'm aware that obfuscation can be reverse engineered, but I think I should at least try to cover up the password a bit. At the very least it wont be visible to a indexing program, or a stray eye giving a quick look at my code.</p>
<p>I am aware of pyobfuscate but I don't want the whole program obfuscated, just one string and possibly the whole line itself where the variable is defined.</p>
<p>Target platform is GNU Linux Generic (If that makes a difference)</p>
| 7 | 2009-06-11T16:47:30Z | 982,431 | <p>It depends alot on why you're keeping the password around, and where you feel there is a security issue.</p>
<p>If you're storing or matching this password to a database in the future:</p>
<p>This shouldn't really be a problem, but if you're concerned, use your database's password encryption early and store that ( SELECT PASSWORD('mySamplePassword'); ), then compare the encrypted version directly in your later query.</p>
<p>If you're saving it for later transmision:</p>
<p>There really isn't much you can do. The transmission itself is very likely to be easier to sniff than your handling of the password.</p>
<p>Without knowing a few more details of what you're doing, this is sortof hard to answer.</p>
| 0 | 2009-06-11T17:18:51Z | [
"python",
"linux",
"encryption",
"passwords",
"obfuscation"
] |
Obfuscate strings in Python | 982,260 | <p>I have a password string that must be passed to a method. Everything works fine but I don't feel comfortable storing the password in clear text. Is there a way to obfuscate the string or to truly encrypt it? I'm aware that obfuscation can be reverse engineered, but I think I should at least try to cover up the password a bit. At the very least it wont be visible to a indexing program, or a stray eye giving a quick look at my code.</p>
<p>I am aware of pyobfuscate but I don't want the whole program obfuscated, just one string and possibly the whole line itself where the variable is defined.</p>
<p>Target platform is GNU Linux Generic (If that makes a difference)</p>
| 7 | 2009-06-11T16:47:30Z | 982,750 | <p>Obviously your best option is to delegate this to a third party. If you can authenticate with whatever you're connecting to using some other credential (eg. the user account your process is running as), you can leave the permission levels up to the OS layer. Alternatively, if sufficiently important / possible you could prompt the user (storing the key in the (arguably) slightly less hackable wetware instead)</p>
<p>If you <em>do</em> need to store some password or key, I'd recommend you store it <em>seperate</em> from your code, in a file you read in, and de-obfusticate if neccessary. This has the advantages that:</p>
<ul>
<li><p>You can set the file permissions on the file as tight as possible (ie. only readable by the account your program runs as), unlike the rest of your program which may be read by more people.</p></li>
<li><p>You won't accidently check it into your version control system!</p></li>
<li><p>No need to be restricted to printable characters (or use awkward escaping) for a python string, so you can use an arbitrary keyfile if possible, rather than a human readable password. If it's non human-entered, there's no reason to have all the weaknesses of passwords.</p></li>
</ul>
<p>To obfusticate, you can use base64 as suggested, or some home-brew scheme like XORing or decrypting with another key stored elsewhere, requiring both locations to be looked at. Be aware that this doesn't protect against anything beyond opportunistic shoulder surfing (if that) - make sure that there is some level of <em>real</em> security as well (including obvious ones like physical access to the machine!)</p>
| 2 | 2009-06-11T18:13:23Z | [
"python",
"linux",
"encryption",
"passwords",
"obfuscation"
] |
Obfuscate strings in Python | 982,260 | <p>I have a password string that must be passed to a method. Everything works fine but I don't feel comfortable storing the password in clear text. Is there a way to obfuscate the string or to truly encrypt it? I'm aware that obfuscation can be reverse engineered, but I think I should at least try to cover up the password a bit. At the very least it wont be visible to a indexing program, or a stray eye giving a quick look at my code.</p>
<p>I am aware of pyobfuscate but I don't want the whole program obfuscated, just one string and possibly the whole line itself where the variable is defined.</p>
<p>Target platform is GNU Linux Generic (If that makes a difference)</p>
| 7 | 2009-06-11T16:47:30Z | 35,443,610 | <p>The base64 answer is good for obfuscating the password and will work with no user intervention at the cost of being insecure. If the user can be logged in with access to a system keyring service, take a look at the <a href="https://pypi.python.org/pypi/keyring" rel="nofollow">keyring</a> package. I used it to store passwords on both OS X and Linux systems.</p>
| 0 | 2016-02-16T21:44:35Z | [
"python",
"linux",
"encryption",
"passwords",
"obfuscation"
] |
Finding PI digits using Monte Carlo | 982,381 | <p>I have tried many algorithms for finding Ï using Monte Carlo.
One of the solutions (in Python) is this:</p>
<pre><code>def calc_PI():
n_points = 1000000
hits = 0
for i in range(1, n_points):
x, y = uniform(0.0, 1.0), uniform(0.0, 1.0)
if (x**2 + y**2) <= 1.0:
hits += 1
print "Calc2: PI result", 4.0 * float(hits) / n_points
</code></pre>
<p>The sad part is that even with 1000000000 the precision is VERY bad (<strong>3.141...</strong>).</p>
<p>Is this the maximum precision this method can offer?
The reason I choose Monte Carlo was that it's very easy to break it in parallel parts.
Is there another algorithm for Ï that is easy to break into pieces and calculate?</p>
| 4 | 2009-06-11T17:10:29Z | 982,423 | <p>Your fractional error goes by <code>sqrt(N)/N = 1/sqrt(N)</code>, So this is a very inefficient way to get a precise estimate. This limit is set by the statistical nature of the measurement and can't be beaten.</p>
<p>You should be able to get about <code>floor(log_10(N))/2-1</code> digits of good precision for <code>N</code> throws. Maybe <code>-2</code> just to be safe...</p>
<p>Even at that it assumes that you are using a real RNG or a good enough PRNG.</p>
| 8 | 2009-06-11T17:18:03Z | [
"python",
"statistics",
"montecarlo",
"pi"
] |
Finding PI digits using Monte Carlo | 982,381 | <p>I have tried many algorithms for finding Ï using Monte Carlo.
One of the solutions (in Python) is this:</p>
<pre><code>def calc_PI():
n_points = 1000000
hits = 0
for i in range(1, n_points):
x, y = uniform(0.0, 1.0), uniform(0.0, 1.0)
if (x**2 + y**2) <= 1.0:
hits += 1
print "Calc2: PI result", 4.0 * float(hits) / n_points
</code></pre>
<p>The sad part is that even with 1000000000 the precision is VERY bad (<strong>3.141...</strong>).</p>
<p>Is this the maximum precision this method can offer?
The reason I choose Monte Carlo was that it's very easy to break it in parallel parts.
Is there another algorithm for Ï that is easy to break into pieces and calculate?</p>
| 4 | 2009-06-11T17:10:29Z | 982,475 | <p>This is a classic example of Monte Carlo. But if you're trying to break the calculation of pi into parallel parts, why not just use an infinite series and let each core take a range, then sum the results as you go?</p>
<p><a href="http://mathworld.wolfram.com/PiFormulas.html">http://mathworld.wolfram.com/PiFormulas.html</a></p>
| 14 | 2009-06-11T17:26:25Z | [
"python",
"statistics",
"montecarlo",
"pi"
] |
Finding PI digits using Monte Carlo | 982,381 | <p>I have tried many algorithms for finding Ï using Monte Carlo.
One of the solutions (in Python) is this:</p>
<pre><code>def calc_PI():
n_points = 1000000
hits = 0
for i in range(1, n_points):
x, y = uniform(0.0, 1.0), uniform(0.0, 1.0)
if (x**2 + y**2) <= 1.0:
hits += 1
print "Calc2: PI result", 4.0 * float(hits) / n_points
</code></pre>
<p>The sad part is that even with 1000000000 the precision is VERY bad (<strong>3.141...</strong>).</p>
<p>Is this the maximum precision this method can offer?
The reason I choose Monte Carlo was that it's very easy to break it in parallel parts.
Is there another algorithm for Ï that is easy to break into pieces and calculate?</p>
| 4 | 2009-06-11T17:10:29Z | 986,367 | <p>Use a quasi random number generator (<a href="http://www.nag.co.uk/IndustryArticles/introduction_to_quasi_random_numbers.pdf" rel="nofollow">http://www.nag.co.uk/IndustryArticles/introduction_to_quasi_random_numbers.pdf</a>) instead of a standard pseudo RNG. Quasi random numbers cover the integration area (what you're doing is a MC integration) more evenly than pseudo random numbers, giving better convergence.</p>
| 4 | 2009-06-12T12:25:04Z | [
"python",
"statistics",
"montecarlo",
"pi"
] |
How can I search and replace in XML with Python? | 982,414 | <p>I am in the middle of making a script for doing translation of xml documents. It's actually pretty cool, the idea is (and it is working) to take an xml file (or a folder of xml files) and open it, parse the xml, get whatever is in between some tags and using the google translate api's translate it and replace the content of the xml files.</p>
<p>As I said, I have this working, but only in fairly strict xml formatted documents, now I have to make it compatible with documents formatted differently. So my idea was:</p>
<p>Parse the xml, find a node, e.g:</p>
<pre><code><template>lorem lipsum dolor mit amet<think><set name="she">Ada</set></think></template>
</code></pre>
<p>Save this as a string, do some regex search and replace on this string. But i sadly have no clue on how to proceed. I want to search to the string (xml node) find text that is inbetween tags, in this case "lorem lipsum dolor mit amet" and "Ada", call a function with those text's as a parameter and then insert the result of the function in the same place as it originated from.</p>
<p>The reason i cant just get the text and rebuild the xml formatting is that there will be differently formatted xml nodes so i need it to be identical...</p>
| 3 | 2009-06-11T17:16:23Z | 982,493 | <p>Don't try to parse XML using regular expressions! <a href="http://welbog.homeip.net/glue/53/XML-is-not-regular" rel="nofollow">XML is not regular</a> and therefore regular expressions are not suited to doing this kind of task.</p>
<p>Use an actual XML parser. Many of these are readily available for Python. A quick search has lead me to <a href="http://stackoverflow.com/questions/8692/how-to-use-xpath-in-python">this SO question</a> which covers how to use XPath in Python.</p>
| 7 | 2009-06-11T17:29:18Z | [
"python",
"xml",
"regex"
] |
How can I search and replace in XML with Python? | 982,414 | <p>I am in the middle of making a script for doing translation of xml documents. It's actually pretty cool, the idea is (and it is working) to take an xml file (or a folder of xml files) and open it, parse the xml, get whatever is in between some tags and using the google translate api's translate it and replace the content of the xml files.</p>
<p>As I said, I have this working, but only in fairly strict xml formatted documents, now I have to make it compatible with documents formatted differently. So my idea was:</p>
<p>Parse the xml, find a node, e.g:</p>
<pre><code><template>lorem lipsum dolor mit amet<think><set name="she">Ada</set></think></template>
</code></pre>
<p>Save this as a string, do some regex search and replace on this string. But i sadly have no clue on how to proceed. I want to search to the string (xml node) find text that is inbetween tags, in this case "lorem lipsum dolor mit amet" and "Ada", call a function with those text's as a parameter and then insert the result of the function in the same place as it originated from.</p>
<p>The reason i cant just get the text and rebuild the xml formatting is that there will be differently formatted xml nodes so i need it to be identical...</p>
| 3 | 2009-06-11T17:16:23Z | 982,674 | <p><a href="http://effbot.org/zone/element.htm">ElementTree</a> would be a good choice for this kind of parsing. It is easy to use and lightweight and supports outputting XML after you do operations on it (as simple as calling write()). It comes packaged with Python standard libraries in the latest versions (I believe 2.6+).</p>
| 5 | 2009-06-11T18:04:38Z | [
"python",
"xml",
"regex"
] |
Mark data as sensitive in python | 982,682 | <p>I need to store a user's password for a short period of time in memory. How can I do so yet not have such information accidentally disclosed in coredumps or tracebacks? Is there a way to mark a value as "sensitive", so it's not saved anywhere by a debugger?</p>
| 17 | 2009-06-11T18:05:47Z | 982,735 | <p>No way to "mark as sensitive", but you could encrypt the data in memory and decrypt it again when you need to use it -- not a perfect solution but the best I can think of.</p>
| 2 | 2009-06-11T18:12:02Z | [
"python",
"security",
"passwords",
"coredump"
] |
Mark data as sensitive in python | 982,682 | <p>I need to store a user's password for a short period of time in memory. How can I do so yet not have such information accidentally disclosed in coredumps or tracebacks? Is there a way to mark a value as "sensitive", so it's not saved anywhere by a debugger?</p>
| 17 | 2009-06-11T18:05:47Z | 982,748 | <ul>
<li>XOR with a one-time pad stored separately</li>
<li>always store salted hash rather than password itself</li>
</ul>
<p>or, if you're very paranoid about dumps, store unique random key in some other place, e.g. i a different thread, in a registry, on your server, etc.</p>
| 2 | 2009-06-11T18:13:14Z | [
"python",
"security",
"passwords",
"coredump"
] |
Mark data as sensitive in python | 982,682 | <p>I need to store a user's password for a short period of time in memory. How can I do so yet not have such information accidentally disclosed in coredumps or tracebacks? Is there a way to mark a value as "sensitive", so it's not saved anywhere by a debugger?</p>
| 17 | 2009-06-11T18:05:47Z | 983,525 | <p><strong>Edit</strong></p>
<p>I have made a solution that uses ctypes (which in turn uses C) to zero memory.</p>
<pre><code>import sys
import ctypes
def zerome(string):
location = id(string) + 20
size = sys.getsizeof(string) - 20
memset = ctypes.cdll.msvcrt.memset
# For Linux, use the following. Change the 6 to whatever it is on your computer.
# memset = ctypes.CDLL("libc.so.6").memset
print "Clearing 0x%08x size %i bytes" % (location, size)
memset(location, 0, size)
</code></pre>
<p>I make no guarantees of the safety of this code. It is tested to work on x86 and CPython 2.6.2. A longer writeup is <a href="http://web.archive.org/web/20100929111257/http://www.codexon.com/posts/clearing-passwords-in-memory-with-python">here</a>.</p>
<p>Decrypting and encrypting in Python will not work. Strings and Integers are interned and persistent, which means you are leaving a mess of password information all over the place.</p>
<p>Hashing is the standard answer, though of course the plaintext eventually needs to be processed somewhere.</p>
<p>The correct solution is to do the sensitive processes as a C module.</p>
<p>But if your memory is constantly being compromised, I would rethink your security setup. </p>
| 27 | 2009-06-11T20:39:42Z | [
"python",
"security",
"passwords",
"coredump"
] |
Mark data as sensitive in python | 982,682 | <p>I need to store a user's password for a short period of time in memory. How can I do so yet not have such information accidentally disclosed in coredumps or tracebacks? Is there a way to mark a value as "sensitive", so it's not saved anywhere by a debugger?</p>
| 17 | 2009-06-11T18:05:47Z | 14,667,881 | <blockquote>
<p>... <strong>The only solution to this is to use mutable data structures.</strong> That
is, you must only use data structures that allow you to dynamically
replace elements. For example, in Python you can use lists to store an
array of characters. However, <em>every time you add or remove an element
from a list, the language might copy the entire list behind your back</em>,
depending on the implementation details. To be safe, if you have to
dynamically resize a data structure, <strong>you should create a new one, copy
data, and then write over the old one</strong>. For example:</p>
</blockquote>
<pre><code>def paranoid_add_character_to_list(ch, l):
"""Copy l, adding a new character, ch. Erase l. Return the result."""
new_list = []
for i in range(len(l)):
new_list.append(0)
new_list.append(ch)
for i in range(len(l)):
new_list[i] = l[i]
l[i] = 0
return new_list
</code></pre>
<p><strong>Source: <a href="http://www.ibm.com/developerworks/library/s-data.html" rel="nofollow">http://www.ibm.com/developerworks/library/s-data.html</a></strong></p>
<ul>
<li>Author: John Viega (viega@list.org) is co-author of Building Secure
Software (Addison-Wesley, 2001) and Java Enterprise Architecture
(O'Reilly and Associates, 2001). John has authored more than 50
technical publications, primarily in the area of software security.
He also wrote Mailman, the GNU Mailing List Manager and ITS4, a tool
for finding security vulnerabilities in C and C++ code.</li>
</ul>
| 3 | 2013-02-02T23:53:57Z | [
"python",
"security",
"passwords",
"coredump"
] |
Weird program behaviour in Python | 982,970 | <p>When running the following code, which is an easy problem, the Python interpreter works weirdly:</p>
<pre><code>n = input()
for i in range(n):
testcase = raw_input()
#print i
print testcase[2:(int(testcase[0])+1)]+testcase[(int(testcase[0])+2):]
</code></pre>
<p>The problem consists in taking n strings and deleting a single character from them.
For example, given the string "4 PYTHON", the program should output "PYTON".
The code runs ok, but if I take out the comment mark, the statement print i makes the interpreter give an unexpected EOF while parsing. Any idea on why this happens?</p>
<p>EDIT: I'm working under Python 2.5, 32 bits in Windows.</p>
| 0 | 2009-06-11T18:59:44Z | 983,082 | <p>Are you sure that the problem is the print i statement? The code works as
expected when I uncomment that statement and run it. However, if I forget to
enter a value for the first input() call, and just enter "4 PYTHON" right off
the bat, then I get:</p>
<pre><code>"SyntaxError: unexpected EOF while parsing"
</code></pre>
<p>This happens because input() is not simply storing the text you enter, but also
running eval() on it. And "4 PYTHON" isn't valid python code.</p>
| 4 | 2009-06-11T19:18:25Z | [
"python"
] |
Weird program behaviour in Python | 982,970 | <p>When running the following code, which is an easy problem, the Python interpreter works weirdly:</p>
<pre><code>n = input()
for i in range(n):
testcase = raw_input()
#print i
print testcase[2:(int(testcase[0])+1)]+testcase[(int(testcase[0])+2):]
</code></pre>
<p>The problem consists in taking n strings and deleting a single character from them.
For example, given the string "4 PYTHON", the program should output "PYTON".
The code runs ok, but if I take out the comment mark, the statement print i makes the interpreter give an unexpected EOF while parsing. Any idea on why this happens?</p>
<p>EDIT: I'm working under Python 2.5, 32 bits in Windows.</p>
| 0 | 2009-06-11T18:59:44Z | 983,102 | <p>This worked for me too, give it a try...</p>
<pre><code>n = raw_input()
n = int(n)
for i in range(n):
testcase = raw_input()
print i
print testcase[2:(int(testcase[0])+1)]+testcase[(int(testcase[0])+2):]
</code></pre>
<p>Note the <code>n = int(n)</code></p>
<p>PS: You can continue to use <code>n = input()</code> on the first line; i prefer raw_input.</p>
| 1 | 2009-06-11T19:22:14Z | [
"python"
] |
Weird program behaviour in Python | 982,970 | <p>When running the following code, which is an easy problem, the Python interpreter works weirdly:</p>
<pre><code>n = input()
for i in range(n):
testcase = raw_input()
#print i
print testcase[2:(int(testcase[0])+1)]+testcase[(int(testcase[0])+2):]
</code></pre>
<p>The problem consists in taking n strings and deleting a single character from them.
For example, given the string "4 PYTHON", the program should output "PYTON".
The code runs ok, but if I take out the comment mark, the statement print i makes the interpreter give an unexpected EOF while parsing. Any idea on why this happens?</p>
<p>EDIT: I'm working under Python 2.5, 32 bits in Windows.</p>
| 0 | 2009-06-11T18:59:44Z | 989,853 | <p>I am yet another who has no trouble with or without the commented print statement. The input function on the first line is no problem as long as I give it something Python can evaluate. So the most likely explanation is that when you are getting that error, you have typed something that isn't a valid Python expression.</p>
<p>Do you <em>always</em> get that error? Can you post a transcript of your interactive session, complete with stack trace?</p>
| 1 | 2009-06-13T03:28:35Z | [
"python"
] |
How to do a non-blocking URL fetch in Python | 983,144 | <p>I am writing a GUI app in <a href="http://www.pyglet.org/" rel="nofollow">Pyglet</a> that has to display tens to hundreds of thumbnails from the Internet. Right now, I am using <a href="http://docs.python.org/library/urllib.html#urllib.urlretrieve" rel="nofollow">urllib.urlretrieve</a> to grab them, but this blocks each time until they are finished, and only grabs one at a time.</p>
<p>I would prefer to download them in parallel and have each one display as soon as it's finished, without blocking the GUI at any point. What is the best way to do this?</p>
<p>I don't know much about threads, but it looks like the <a href="http://docs.python.org/library/threading.html" rel="nofollow">threading</a> module might help? Or perhaps there is some easy way I've overlooked.</p>
| 1 | 2009-06-11T19:31:02Z | 983,210 | <p>As you suspected, this is a perfect situation for threading. <a href="http://www.wellho.net/solutions/python-python-threads-a-first-example.html" rel="nofollow">Here</a> is a short guide I found immensely helpful when doing my own first bit of threading in python.</p>
| 2 | 2009-06-11T19:44:41Z | [
"python",
"multithreading",
"blocking",
"pyglet"
] |
How to do a non-blocking URL fetch in Python | 983,144 | <p>I am writing a GUI app in <a href="http://www.pyglet.org/" rel="nofollow">Pyglet</a> that has to display tens to hundreds of thumbnails from the Internet. Right now, I am using <a href="http://docs.python.org/library/urllib.html#urllib.urlretrieve" rel="nofollow">urllib.urlretrieve</a> to grab them, but this blocks each time until they are finished, and only grabs one at a time.</p>
<p>I would prefer to download them in parallel and have each one display as soon as it's finished, without blocking the GUI at any point. What is the best way to do this?</p>
<p>I don't know much about threads, but it looks like the <a href="http://docs.python.org/library/threading.html" rel="nofollow">threading</a> module might help? Or perhaps there is some easy way I've overlooked.</p>
| 1 | 2009-06-11T19:31:02Z | 983,214 | <p>As you rightly indicated, you could create a number of threads, each of which is responsible for performing urlretrieve operations. This allows the main thread to continue uninterrupted. </p>
<p>Here is a tutorial on threading in python:
<a href="http://heather.cs.ucdavis.edu/~matloff/Python/PyThreads.pdf" rel="nofollow">http://heather.cs.ucdavis.edu/~matloff/Python/PyThreads.pdf</a></p>
| 2 | 2009-06-11T19:45:06Z | [
"python",
"multithreading",
"blocking",
"pyglet"
] |
How to do a non-blocking URL fetch in Python | 983,144 | <p>I am writing a GUI app in <a href="http://www.pyglet.org/" rel="nofollow">Pyglet</a> that has to display tens to hundreds of thumbnails from the Internet. Right now, I am using <a href="http://docs.python.org/library/urllib.html#urllib.urlretrieve" rel="nofollow">urllib.urlretrieve</a> to grab them, but this blocks each time until they are finished, and only grabs one at a time.</p>
<p>I would prefer to download them in parallel and have each one display as soon as it's finished, without blocking the GUI at any point. What is the best way to do this?</p>
<p>I don't know much about threads, but it looks like the <a href="http://docs.python.org/library/threading.html" rel="nofollow">threading</a> module might help? Or perhaps there is some easy way I've overlooked.</p>
| 1 | 2009-06-11T19:31:02Z | 983,300 | <p>Here's an example of how to use threading.Thread. Just replace the class name with your own and the run function with your own. Note that threading is great for IO restricted applications like your's and can really speed it up. Using pythong threading strictly for computation in standard python doesn't help because only one thread can compute at a time.</p>
<pre><code>import threading, time
class Ping(threading.Thread):
def __init__(self, multiple):
threading.Thread.__init__(self)
self.multiple = multiple
def run(self):
#sleeps 3 seconds then prints 'pong' x times
time.sleep(3)
printString = 'pong' * self.multiple
pingInstance = Ping(3)
pingInstance.start() #your run function will be called with the start function
print "pingInstance is alive? : %d" % pingInstance.isAlive() #will return True, or 1
print "Number of threads alive: %d" % threading.activeCount()
#main thread + class instance
time.sleep(3.5)
print "Number of threads alive: %d" % threading.activeCount()
print "pingInstance is alive?: %d" % pingInstance.isAlive()
#isAlive returns false when your thread reaches the end of it's run function.
#only main thread now
</code></pre>
| 2 | 2009-06-11T20:01:03Z | [
"python",
"multithreading",
"blocking",
"pyglet"
] |
How to do a non-blocking URL fetch in Python | 983,144 | <p>I am writing a GUI app in <a href="http://www.pyglet.org/" rel="nofollow">Pyglet</a> that has to display tens to hundreds of thumbnails from the Internet. Right now, I am using <a href="http://docs.python.org/library/urllib.html#urllib.urlretrieve" rel="nofollow">urllib.urlretrieve</a> to grab them, but this blocks each time until they are finished, and only grabs one at a time.</p>
<p>I would prefer to download them in parallel and have each one display as soon as it's finished, without blocking the GUI at any point. What is the best way to do this?</p>
<p>I don't know much about threads, but it looks like the <a href="http://docs.python.org/library/threading.html" rel="nofollow">threading</a> module might help? Or perhaps there is some easy way I've overlooked.</p>
| 1 | 2009-06-11T19:31:02Z | 983,971 | <p>You'll probably benefit from <code>threading</code> or <a href="http://docs.python.org/library/multiprocessing.html#using-a-pool-of-workers" rel="nofollow"><code>multiprocessing</code></a> modules. You don't actually need to create all those <code>Thread</code>-based classes by yourself, there is a simpler method using <code>Pool.map</code>:</p>
<pre><code>from multiprocessing import Pool
def fetch_url(url):
# Fetch the URL contents and save it anywhere you need and
# return something meaningful (like filename or error code),
# if you wish.
...
pool = Pool(processes=4)
result = pool.map(f, image_url_list)
</code></pre>
| 2 | 2009-06-11T21:58:55Z | [
"python",
"multithreading",
"blocking",
"pyglet"
] |
How to do a non-blocking URL fetch in Python | 983,144 | <p>I am writing a GUI app in <a href="http://www.pyglet.org/" rel="nofollow">Pyglet</a> that has to display tens to hundreds of thumbnails from the Internet. Right now, I am using <a href="http://docs.python.org/library/urllib.html#urllib.urlretrieve" rel="nofollow">urllib.urlretrieve</a> to grab them, but this blocks each time until they are finished, and only grabs one at a time.</p>
<p>I would prefer to download them in parallel and have each one display as soon as it's finished, without blocking the GUI at any point. What is the best way to do this?</p>
<p>I don't know much about threads, but it looks like the <a href="http://docs.python.org/library/threading.html" rel="nofollow">threading</a> module might help? Or perhaps there is some easy way I've overlooked.</p>
| 1 | 2009-06-11T19:31:02Z | 984,119 | <p>You either need to use threads, or an asynchronous networking library such as <a href="http://twistedmatrix.com" rel="nofollow">Twisted</a>. I suspect that using threads might be simpler in your particular use case.</p>
| 0 | 2009-06-11T22:34:35Z | [
"python",
"multithreading",
"blocking",
"pyglet"
] |
How to do a non-blocking URL fetch in Python | 983,144 | <p>I am writing a GUI app in <a href="http://www.pyglet.org/" rel="nofollow">Pyglet</a> that has to display tens to hundreds of thumbnails from the Internet. Right now, I am using <a href="http://docs.python.org/library/urllib.html#urllib.urlretrieve" rel="nofollow">urllib.urlretrieve</a> to grab them, but this blocks each time until they are finished, and only grabs one at a time.</p>
<p>I would prefer to download them in parallel and have each one display as soon as it's finished, without blocking the GUI at any point. What is the best way to do this?</p>
<p>I don't know much about threads, but it looks like the <a href="http://docs.python.org/library/threading.html" rel="nofollow">threading</a> module might help? Or perhaps there is some easy way I've overlooked.</p>
| 1 | 2009-06-11T19:31:02Z | 984,197 | <p>You have these choices:</p>
<ul>
<li>Threads: easiest but doesn't scale well</li>
<li>Twisted: medium difficulty, scales well but shares CPU due to GIL and being single threaded.</li>
<li>Multiprocessing: hardest. Scales well if you know how to write your own event loop.</li>
</ul>
<p>I recommend just using threads unless you need an industrial scale fetcher.</p>
| 1 | 2009-06-11T22:55:42Z | [
"python",
"multithreading",
"blocking",
"pyglet"
] |
python and sys.argv | 983,201 | <pre><code>if len(sys.argv) < 2:
sys.stderr.write('Usage: sys.argv[0] ')
sys.exit(1)
if not os.path.exists(sys.argv[1]):
sys.stderr.write('ERROR: Database sys.argv[1] was not found!')
sys.exit(1)
</code></pre>
<p>This is a portion of code I'm working on. The first part I'm trying to say if the user doesn't type <code>python programname something</code> then it will exit.</p>
<p>The second part I'm trying to see if the database exists. On both places I'm unsure if I have the correct way to write out the sys.argv's by stderr or not.</p>
| 51 | 2009-06-11T19:42:30Z | 983,229 | <p>In Python, you can't just embed arbitrary Python expressions into literal strings and have it substitute the value of the string. You need to either:</p>
<pre><code>sys.stderr.write("Usage: " + sys.argv[0])
</code></pre>
<p>or</p>
<pre><code>sys.stderr.write("Usage: %s" % sys.argv[0])
</code></pre>
<p>Also, you may want to consider using the following syntax of <code>print</code> (for Python earlier than 3.x):</p>
<pre><code>print >>sys.stderr, "Usage:", sys.argv[0]
</code></pre>
<p>Using <code>print</code> arguably makes the code easier to read. Python automatically adds a space between arguments to the <code>print</code> statement, so there will be one space after the colon in the above example.</p>
<p>In Python 3.x, you would use the <code>print</code> function:</p>
<pre><code>print("Usage:", sys.argv[0], file=sys.stderr)
</code></pre>
<p>Finally, in Python 2.6 and later you can use <code>.format</code>:</p>
<pre><code>print >>sys.stderr, "Usage: {0}".format(sys.argv[0])
</code></pre>
| 32 | 2009-06-11T19:47:14Z | [
"python"
] |
python and sys.argv | 983,201 | <pre><code>if len(sys.argv) < 2:
sys.stderr.write('Usage: sys.argv[0] ')
sys.exit(1)
if not os.path.exists(sys.argv[1]):
sys.stderr.write('ERROR: Database sys.argv[1] was not found!')
sys.exit(1)
</code></pre>
<p>This is a portion of code I'm working on. The first part I'm trying to say if the user doesn't type <code>python programname something</code> then it will exit.</p>
<p>The second part I'm trying to see if the database exists. On both places I'm unsure if I have the correct way to write out the sys.argv's by stderr or not.</p>
| 51 | 2009-06-11T19:42:30Z | 983,355 | <p>I would do it this way:</p>
<pre><code>import sys
def main(argv):
if len(argv) < 2:
sys.stderr.write("Usage: %s <database>" % (argv[0],))
return 1
if not os.path.exists(argv[1]):
sys.stderr.write("ERROR: Database %r was not found!" % (argv[1],))
return 1
if __name__ == "__main__":
sys.exit(main(sys.argv))
</code></pre>
<p>This allows <code>main()</code> to be imported into other modules if desired, and simplifies debugging because you can choose what <code>argv</code> should be.</p>
| 29 | 2009-06-11T20:09:26Z | [
"python"
] |
python and sys.argv | 983,201 | <pre><code>if len(sys.argv) < 2:
sys.stderr.write('Usage: sys.argv[0] ')
sys.exit(1)
if not os.path.exists(sys.argv[1]):
sys.stderr.write('ERROR: Database sys.argv[1] was not found!')
sys.exit(1)
</code></pre>
<p>This is a portion of code I'm working on. The first part I'm trying to say if the user doesn't type <code>python programname something</code> then it will exit.</p>
<p>The second part I'm trying to see if the database exists. On both places I'm unsure if I have the correct way to write out the sys.argv's by stderr or not.</p>
| 51 | 2009-06-11T19:42:30Z | 984,145 | <p>BTW you can pass the error message directly to sys.exit:</p>
<pre><code>if len(sys.argv) < 2:
sys.exit('Usage: %s database-name' % sys.argv[0])
if not os.path.exists(sys.argv[1]):
sys.exit('ERROR: Database %s was not found!' % sys.argv[1])
</code></pre>
| 84 | 2009-06-11T22:41:16Z | [
"python"
] |
How do I make python to wait for a pressed key | 983,354 | <p>I want my script to wait until the user presses any key.</p>
<p>How do I do that?</p>
| 229 | 2009-06-11T20:09:19Z | 983,382 | <p>One way to do this in Python 2, is to use <code>raw_input()</code>:</p>
<pre><code>raw_input("Press Enter to continue...")
</code></pre>
<p>In python3 it's just <code>input()</code></p>
| 205 | 2009-06-11T20:11:59Z | [
"python",
"wait",
"keyboard-input"
] |
How do I make python to wait for a pressed key | 983,354 | <p>I want my script to wait until the user presses any key.</p>
<p>How do I do that?</p>
| 229 | 2009-06-11T20:09:19Z | 1,135,035 | <p>In Python 3, no <code>raw_input()</code> exists. So, just use:</p>
<pre><code>input("Press Enter to continue...")
</code></pre>
<p>This only waits for a user to press enter though, so you might want to use <strong>msvcrt</strong> ((Windows/DOS only) The msvcrt module gives you access to a number of functions in the Microsoft Visual C/C++ Runtime Library (MSVCRT)):</p>
<pre><code>import msvcrt as m
def wait():
m.getch()
</code></pre>
<p>This should wait for a key press.</p>
| 176 | 2009-07-16T01:48:20Z | [
"python",
"wait",
"keyboard-input"
] |
How do I make python to wait for a pressed key | 983,354 | <p>I want my script to wait until the user presses any key.</p>
<p>How do I do that?</p>
| 229 | 2009-06-11T20:09:19Z | 5,004,022 | <p>The python <a href="http://docs.python.org/faq/library#how-do-i-get-a-single-keypress-at-a-time">manual</a> provides the following:</p>
<pre><code>import termios, fcntl, sys, os
fd = sys.stdin.fileno()
oldterm = termios.tcgetattr(fd)
newattr = termios.tcgetattr(fd)
newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO
termios.tcsetattr(fd, termios.TCSANOW, newattr)
oldflags = fcntl.fcntl(fd, fcntl.F_GETFL)
fcntl.fcntl(fd, fcntl.F_SETFL, oldflags | os.O_NONBLOCK)
try:
while 1:
try:
c = sys.stdin.read(1)
print "Got character", repr(c)
except IOError: pass
finally:
termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm)
fcntl.fcntl(fd, fcntl.F_SETFL, oldflags)
</code></pre>
<p>which can be rolled into your use case.</p>
| 13 | 2011-02-15T13:09:08Z | [
"python",
"wait",
"keyboard-input"
] |
How do I make python to wait for a pressed key | 983,354 | <p>I want my script to wait until the user presses any key.</p>
<p>How do I do that?</p>
| 229 | 2009-06-11T20:09:19Z | 6,037,500 | <p>I don't know of a platform independent way of doing it, but under Windows, if you use the msvcrt module, you can use its getch function:</p>
<pre><code>import msvcrt
c = msvcrt.getch()
print 'you entered', c
</code></pre>
<p>mscvcrt also includes the non-blocking kbhit() function to see if a key was pressed without waiting (not sure if there's a corresponding curses function). Under UNIX, there is the curses package, but not sure if you can use it without using it for all of the screen output. This code works under UNIX:</p>
<pre><code>import curses
stdscr = curses.initscr()
c = stdscr.getch()
print 'you entered', chr(c)
curses.endwin()
</code></pre>
<p>Note that curses.getch() returns the ordinal of the key pressed so to make it have the same output I had to cast it.</p>
| 10 | 2011-05-17T21:42:22Z | [
"python",
"wait",
"keyboard-input"
] |
How do I make python to wait for a pressed key | 983,354 | <p>I want my script to wait until the user presses any key.</p>
<p>How do I do that?</p>
| 229 | 2009-06-11T20:09:19Z | 6,599,441 | <p>On my linux box, I use the following code. This is similar to the <a href="http://docs.python.org/faq/library#how-do-i-get-a-single-keypress-at-a-time">manual</a> entry mentioned elsewhere but that code spins in a tight loop where this code doesn't and there are lots of odd corner cases that code doesn't account for that this code does.</p>
<pre><code>def read_single_keypress():
"""Waits for a single keypress on stdin.
This is a silly function to call if you need to do it a lot because it has
to store stdin's current setup, setup stdin for reading single keystrokes
then read the single keystroke then revert stdin back after reading the
keystroke.
Returns the character of the key that was pressed (zero on
KeyboardInterrupt which can happen when a signal gets handled)
"""
import termios, fcntl, sys, os
fd = sys.stdin.fileno()
# save old state
flags_save = fcntl.fcntl(fd, fcntl.F_GETFL)
attrs_save = termios.tcgetattr(fd)
# make raw - the way to do this comes from the termios(3) man page.
attrs = list(attrs_save) # copy the stored version to update
# iflag
attrs[0] &= ~(termios.IGNBRK | termios.BRKINT | termios.PARMRK
| termios.ISTRIP | termios.INLCR | termios. IGNCR
| termios.ICRNL | termios.IXON )
# oflag
attrs[1] &= ~termios.OPOST
# cflag
attrs[2] &= ~(termios.CSIZE | termios. PARENB)
attrs[2] |= termios.CS8
# lflag
attrs[3] &= ~(termios.ECHONL | termios.ECHO | termios.ICANON
| termios.ISIG | termios.IEXTEN)
termios.tcsetattr(fd, termios.TCSANOW, attrs)
# turn off non-blocking
fcntl.fcntl(fd, fcntl.F_SETFL, flags_save & ~os.O_NONBLOCK)
# read a single keystroke
try:
ret = sys.stdin.read(1) # returns a single character
except KeyboardInterrupt:
ret = 0
finally:
# restore old state
termios.tcsetattr(fd, termios.TCSAFLUSH, attrs_save)
fcntl.fcntl(fd, fcntl.F_SETFL, flags_save)
return ret
</code></pre>
| 27 | 2011-07-06T15:58:39Z | [
"python",
"wait",
"keyboard-input"
] |
How do I make python to wait for a pressed key | 983,354 | <p>I want my script to wait until the user presses any key.</p>
<p>How do I do that?</p>
| 229 | 2009-06-11T20:09:19Z | 11,094,086 | <p>If you want to see if they pressed a exact key (like say 'b') Do this:</p>
<pre><code>while True:
choice = raw_input("> ")
if choice == 'b' :
print "You win"
input("yay")
break
</code></pre>
| 2 | 2012-06-19T03:42:22Z | [
"python",
"wait",
"keyboard-input"
] |
How do I make python to wait for a pressed key | 983,354 | <p>I want my script to wait until the user presses any key.</p>
<p>How do I do that?</p>
| 229 | 2009-06-11T20:09:19Z | 16,933,120 | <p>If you are ok with depending on system commands you can use the following:</p>
<p>Linux:</p>
<pre><code>os.system('read -s -n 1 -p "Press any key to continue..."')
print
</code></pre>
<p>Windows:</p>
<pre><code>os.system("pause")
</code></pre>
| 15 | 2013-06-05T06:36:48Z | [
"python",
"wait",
"keyboard-input"
] |
How do I make python to wait for a pressed key | 983,354 | <p>I want my script to wait until the user presses any key.</p>
<p>How do I do that?</p>
| 229 | 2009-06-11T20:09:19Z | 20,651,266 | <p>os.system seems to always invoke sh, which does not recognize the s and n options for read. However the read command can be passed to bash: </p>
<pre><code> os.system("""bash -c 'read -s -n 1 -p "Press any key to continue..."'""")
</code></pre>
| 0 | 2013-12-18T06:39:33Z | [
"python",
"wait",
"keyboard-input"
] |
How do I make python to wait for a pressed key | 983,354 | <p>I want my script to wait until the user presses any key.</p>
<p>How do I do that?</p>
| 229 | 2009-06-11T20:09:19Z | 22,151,521 | <p>Simply using</p>
<pre><code>input("Press Enter to continue...")
</code></pre>
<p>will cause a SyntaxError: expected EOF while parsing.</p>
<p>Simple fix use:</p>
<pre><code>try:
input("Press enter to continue")
except SyntaxError:
pass
</code></pre>
| 11 | 2014-03-03T16:06:30Z | [
"python",
"wait",
"keyboard-input"
] |
How do I make python to wait for a pressed key | 983,354 | <p>I want my script to wait until the user presses any key.</p>
<p>How do I do that?</p>
| 229 | 2009-06-11T20:09:19Z | 26,338,755 | <p>or you could do</p>
<pre><code>print("This is a good joke")
print("what happened when the chicken crossed the road")
gap = input("")
if gap == (""):
print("")
else:
print("")
print("it died")
</code></pre>
| -1 | 2014-10-13T11:18:53Z | [
"python",
"wait",
"keyboard-input"
] |
How do I make python to wait for a pressed key | 983,354 | <p>I want my script to wait until the user presses any key.</p>
<p>How do I do that?</p>
| 229 | 2009-06-11T20:09:19Z | 34,956,791 | <p><strong>Cross Platform, Python 2/3 code:</strong></p>
<pre><code># import sys, os
def wait_key():
''' Wait for a key press on the console and return it. '''
result = None
if os.name == 'nt':
import msvcrt
result = msvcrt.getch()
else:
import termios
fd = sys.stdin.fileno()
oldterm = termios.tcgetattr(fd)
newattr = termios.tcgetattr(fd)
newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO
termios.tcsetattr(fd, termios.TCSANOW, newattr)
try:
result = sys.stdin.read(1)
except IOError:
pass
finally:
termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm)
return result
</code></pre>
<p>I removed the fctl/non-blocking stuff because it was giving <code>IOError</code>s and I didn't need it. I'm using this code specifically because I want it to block. ;)</p>
| 2 | 2016-01-22T22:10:39Z | [
"python",
"wait",
"keyboard-input"
] |
How do I make python to wait for a pressed key | 983,354 | <p>I want my script to wait until the user presses any key.</p>
<p>How do I do that?</p>
| 229 | 2009-06-11T20:09:19Z | 38,647,292 | <p>I am new to python and I was already thinking I am too stupid to reproduce the simplest suggestions made here.
It turns out, there's a pitfall one should know:</p>
<p>When a python-script is executed from IDLE, some IO-commands seem to behave completely different (as there is actually no terminal window).</p>
<p>Eg. msvcrt.getch is non-blocking and always returns $ff.
This has already been reported long ago (see e.g. <a href="https://bugs.python.org/issue9290" rel="nofollow">https://bugs.python.org/issue9290</a> ) - and it's marked as fixed, somehow the problem seems to persist in current versions of python/IDLE.</p>
<p>So if any of the code posted above doesn't work for you, try running the script manually, and <strong>NOT from IDLE</strong>.</p>
| 0 | 2016-07-28T21:47:58Z | [
"python",
"wait",
"keyboard-input"
] |
Create a GUI from a XML schema automatically | 983,399 | <p>I have to write a desktop application to edit data stored in a XML file. The format is defined by a XML schema file (.xsd). The format is quite complex. </p>
<p>Are there tools which can generate a basic GUI automatically? It's not yet decided which language to use. I have experience in Python and C++ using wxWidgets and C# (.NET 1) using Windows Forms.</p>
| 14 | 2009-06-11T20:14:44Z | 984,379 | <p>Go For <strong>PyQt</strong>:</p>
<p><a href="http://www.riverbankcomputing.co.uk/software/pyqt/download" rel="nofollow">http://www.riverbankcomputing.co.uk/software/pyqt/download</a></p>
<p>Download The <strong>Qt Developers tool</strong> to generate the gui automatically</p>
<p>www.qtsoftware.com/products/developer-tools</p>
<p>For schema validation try <strong>lxml</strong></p>
<p><a href="http://lxml.de/validation.html" rel="nofollow">http://lxml.de/validation.html</a></p>
| 3 | 2009-06-11T23:50:19Z | [
"c#",
"c++",
"python",
"xml",
"schema"
] |
Create a GUI from a XML schema automatically | 983,399 | <p>I have to write a desktop application to edit data stored in a XML file. The format is defined by a XML schema file (.xsd). The format is quite complex. </p>
<p>Are there tools which can generate a basic GUI automatically? It's not yet decided which language to use. I have experience in Python and C++ using wxWidgets and C# (.NET 1) using Windows Forms.</p>
| 14 | 2009-06-11T20:14:44Z | 984,789 | <p>I'm not exactly sure if I can be completely of help to you @Adrian, but I've been researching something very close to what you are discussing...</p>
<p>Using something like Linq to XML may assist you in the validation of the data being entered, as there are already methods that will validate the data for you.</p>
<p>As I recall, there are a few tools that allow you dynamically create the app... <a href="http://code.msdn.microsoft.com/dynamicWPF" rel="nofollow">link</a></p>
<p>Hope this helps.</p>
| 0 | 2009-06-12T02:57:29Z | [
"c#",
"c++",
"python",
"xml",
"schema"
] |
Create a GUI from a XML schema automatically | 983,399 | <p>I have to write a desktop application to edit data stored in a XML file. The format is defined by a XML schema file (.xsd). The format is quite complex. </p>
<p>Are there tools which can generate a basic GUI automatically? It's not yet decided which language to use. I have experience in Python and C++ using wxWidgets and C# (.NET 1) using Windows Forms.</p>
| 14 | 2009-06-11T20:14:44Z | 985,246 | <p>One solution could be to write an XSL transformation that converts the XML file into a XAML file.</p>
| 1 | 2009-06-12T06:21:05Z | [
"c#",
"c++",
"python",
"xml",
"schema"
] |
Create a GUI from a XML schema automatically | 983,399 | <p>I have to write a desktop application to edit data stored in a XML file. The format is defined by a XML schema file (.xsd). The format is quite complex. </p>
<p>Are there tools which can generate a basic GUI automatically? It's not yet decided which language to use. I have experience in Python and C++ using wxWidgets and C# (.NET 1) using Windows Forms.</p>
| 14 | 2009-06-11T20:14:44Z | 1,015,238 | <p>If the GUI will be simple and you don't bother about the geometry of the components(widgets) in the dialogs, Qt will be a good option. Actually I'm working on a similar task for my project, and my goal was to validate the form data by using an XML file.</p>
<p>Using Qt, it is possible to access any widget on the dialog at run-time by using its object name. So that validation can be applied to the dialog contents.</p>
<p>Creating any dialogs will be even easier, since you will have the widget type and certain information and using layouts, fascinating results can be obtained.</p>
| 1 | 2009-06-18T21:20:01Z | [
"c#",
"c++",
"python",
"xml",
"schema"
] |
Create a GUI from a XML schema automatically | 983,399 | <p>I have to write a desktop application to edit data stored in a XML file. The format is defined by a XML schema file (.xsd). The format is quite complex. </p>
<p>Are there tools which can generate a basic GUI automatically? It's not yet decided which language to use. I have experience in Python and C++ using wxWidgets and C# (.NET 1) using Windows Forms.</p>
| 14 | 2009-06-11T20:14:44Z | 2,118,609 | <p>It's worth taking a look at <a href="http://www.jaxfront.org/" rel="nofollow">Jaxfront</a> which is able to consume an XSD and generate a form (including HTML). You can also supply an instance XML document for it to load into the GUI, and save out instance XML documents too.</p>
<p>I tried it with one of our fairly complicated XSD's and it worked pretty well.</p>
<p>Sadly it's written in Java - I'm still looking for something which can generate .NET web forms or XAML/WPF! In fact even XFORMS would be good.</p>
| 1 | 2010-01-22T16:13:06Z | [
"c#",
"c++",
"python",
"xml",
"schema"
] |
Create a GUI from a XML schema automatically | 983,399 | <p>I have to write a desktop application to edit data stored in a XML file. The format is defined by a XML schema file (.xsd). The format is quite complex. </p>
<p>Are there tools which can generate a basic GUI automatically? It's not yet decided which language to use. I have experience in Python and C++ using wxWidgets and C# (.NET 1) using Windows Forms.</p>
| 14 | 2009-06-11T20:14:44Z | 4,294,774 | <p>There is an experimental tool, which does that, automatically create a desktop UI for handling data stored in XML. It's called <a href="http://www.lst.de/~cs/kode/kxforms.html" rel="nofollow">KXForms</a>. It comes as part of a suite of tools for handling XML data in various ways, like creating C++ code from an XML schema to represent the data natively in C++ and encapsulate parsing and writing.</p>
<p>This might not be the production-ready solution you are looking for, but it's a start and a source for inspiration. It's open source, so contributions are certainly welcome.</p>
| 0 | 2010-11-28T00:58:13Z | [
"c#",
"c++",
"python",
"xml",
"schema"
] |
Create a GUI from a XML schema automatically | 983,399 | <p>I have to write a desktop application to edit data stored in a XML file. The format is defined by a XML schema file (.xsd). The format is quite complex. </p>
<p>Are there tools which can generate a basic GUI automatically? It's not yet decided which language to use. I have experience in Python and C++ using wxWidgets and C# (.NET 1) using Windows Forms.</p>
| 14 | 2009-06-11T20:14:44Z | 5,012,070 | <p>"<a href="http://www.felixgolubov.com/XMLEditor/" rel="nofollow">XAmple XML Editor</a> project introduces a java Swing based XML editor that analyzes a given schema and then generates a document-specific graphical user interface. Unlike other XML editors, the XAmple XML editor GUI exposes not just a tree representation of the XML document but rather a logical combination of the XML document and respective XML Schema. The user interface of the XML editor is highly logical and intuitively comprehensible. To be able to prepare valid XML documents of significant complexity, a user is not required to be familiar with XML and XML Schema languages and to have any a-priori knowledge about the documents structural requirements."</p>
<p>I've tried it and even my non-technical boss likes it. You can use it as-is or use it as a library upon which to base your own Java-based UI.</p>
| 0 | 2011-02-16T02:59:58Z | [
"c#",
"c++",
"python",
"xml",
"schema"
] |
Call flatpage from with a view | 983,722 | <p>Can I call a Flatpage from with a view. Say I have some code like:</p>
<pre><code>def myview(request):
if request.subdomain != "www":
return HttpResponseRedirect("http://"+request.subdomain+".mydomain/login/")
else:
call the flatpage here...
</code></pre>
| 2 | 2009-06-11T21:13:30Z | 984,276 | <p>You sure can. Just make sure you have the <code>flatpage</code> function included in your view code:</p>
<pre><code>from django.contrib.flatpages.views import flatpage
</code></pre>
<p>And stick the following in your <code>else:</code></p>
<pre><code>return flatpage(request, '/path/to/your/flatpage/')
</code></pre>
<p>Or if you'd like to configure the flatpage to use the same URL being called, you can always do it like this:</p>
<pre><code>return flatpage(request, request.path)
</code></pre>
<p>I just tested this and it worked just fine. Let me know if it doesn't for you.</p>
| 4 | 2009-06-11T23:16:14Z | [
"python",
"django"
] |
Python JSON encoding | 983,855 | <p>I'm trying to encode data to JSON in Python and I been having a quite a bit of trouble. I believe the problem is simply a misunderstanding. </p>
<p>I'm relatively new to Python and never really got familiar with the various Python data types, so that's most likely what's messing me up. </p>
<p>Currently I am declaring a list, looping through and another list, and appending one list within another:</p>
<pre><code>import simplejson, json
data = [['apple', 'cat'], ['banana', 'dog'], ['pear', 'fish']]
x = simplejson.loads(data)
# >>> typeError: expected string or buffer..
x = simplejson.dumps(stream)
# >>> [["apple", "cat"], ["banana", "dog"], ["pear", "fish"]]
# - shouldn't JSON encoded strings be like: {{"apple":{"cat"},{"banana":"dog"}}
</code></pre>
<p>So I either: </p>
<ul>
<li>I don't understand JSON Syntax</li>
<li>I don't understand the Pythons JSON module(s)</li>
<li>I'm using an inappropriate data type.</li>
</ul>
| 39 | 2009-06-11T21:37:09Z | 983,877 | <p>The data you are encoding is a keyless array, so JSON encodes it with [] brackets. See www.json.org for more information about that. The curly braces are used for lists with key/value pairs.</p>
<p>From www.json.org:</p>
<blockquote>
<p>JSON is built on two structures:</p>
<p>A collection of name/value pairs. In
various languages, this is realized as
an object, record, struct, dictionary,
hash table, keyed list, or associative
array. An ordered list of values. In
most languages, this is realized as an
array, vector, list, or sequence. </p>
<p>An object is an unordered set of
name/value pairs. An object begins
with { (left brace) and ends with }
(right brace). Each name is followed
by : (colon) and the name/value pairs
are separated by , (comma).</p>
<p>An array is an ordered collection of
values. An array begins with [ (left
bracket) and ends with ] (right
bracket). Values are separated by ,
(comma).</p>
</blockquote>
| 4 | 2009-06-11T21:41:11Z | [
"python",
"json",
"encoding",
"types",
"simplejson"
] |
Python JSON encoding | 983,855 | <p>I'm trying to encode data to JSON in Python and I been having a quite a bit of trouble. I believe the problem is simply a misunderstanding. </p>
<p>I'm relatively new to Python and never really got familiar with the various Python data types, so that's most likely what's messing me up. </p>
<p>Currently I am declaring a list, looping through and another list, and appending one list within another:</p>
<pre><code>import simplejson, json
data = [['apple', 'cat'], ['banana', 'dog'], ['pear', 'fish']]
x = simplejson.loads(data)
# >>> typeError: expected string or buffer..
x = simplejson.dumps(stream)
# >>> [["apple", "cat"], ["banana", "dog"], ["pear", "fish"]]
# - shouldn't JSON encoded strings be like: {{"apple":{"cat"},{"banana":"dog"}}
</code></pre>
<p>So I either: </p>
<ul>
<li>I don't understand JSON Syntax</li>
<li>I don't understand the Pythons JSON module(s)</li>
<li>I'm using an inappropriate data type.</li>
</ul>
| 39 | 2009-06-11T21:37:09Z | 983,879 | <p>Python <code>lists</code> translate to JSON <code>arrays</code>. What it is giving you is a perfectly valid JSON string that could be used in a Javascript application. To get what you expected, you would need to use a <code>dict</code>:</p>
<pre><code>>>> json.dumps({'apple': 'cat', 'banana':'dog', 'pear':'fish'})
'{"pear": "fish", "apple": "cat", "banana": "dog"}'
</code></pre>
| 51 | 2009-06-11T21:41:16Z | [
"python",
"json",
"encoding",
"types",
"simplejson"
] |
Python JSON encoding | 983,855 | <p>I'm trying to encode data to JSON in Python and I been having a quite a bit of trouble. I believe the problem is simply a misunderstanding. </p>
<p>I'm relatively new to Python and never really got familiar with the various Python data types, so that's most likely what's messing me up. </p>
<p>Currently I am declaring a list, looping through and another list, and appending one list within another:</p>
<pre><code>import simplejson, json
data = [['apple', 'cat'], ['banana', 'dog'], ['pear', 'fish']]
x = simplejson.loads(data)
# >>> typeError: expected string or buffer..
x = simplejson.dumps(stream)
# >>> [["apple", "cat"], ["banana", "dog"], ["pear", "fish"]]
# - shouldn't JSON encoded strings be like: {{"apple":{"cat"},{"banana":"dog"}}
</code></pre>
<p>So I either: </p>
<ul>
<li>I don't understand JSON Syntax</li>
<li>I don't understand the Pythons JSON module(s)</li>
<li>I'm using an inappropriate data type.</li>
</ul>
| 39 | 2009-06-11T21:37:09Z | 983,884 | <p>In <code>simplejson</code> (or the library <code>json</code> in Python 2.6 and later), <code>loads</code> takes a JSON string and returns a Python data structure, <code>dumps</code> takes a Python data structure and returns a JSON string. JSON string can encode Javascript arrays, not just objects, and a Python list corresponds to a JSON string encoding an array. To get a JSON string such as</p>
<pre><code>{"apple":"cat", "banana":"dog"}
</code></pre>
<p>the Python object you pass to <code>json.dumps</code> could be:</p>
<pre><code>dict(apple="cat", banana="dog")
</code></pre>
<p>though the JSON string is also valid Python syntax for the same <code>dict</code>. I believe the specific string you say you expect is simply invalid JSON syntax, however.</p>
| 16 | 2009-06-11T21:41:48Z | [
"python",
"json",
"encoding",
"types",
"simplejson"
] |
Python JSON encoding | 983,855 | <p>I'm trying to encode data to JSON in Python and I been having a quite a bit of trouble. I believe the problem is simply a misunderstanding. </p>
<p>I'm relatively new to Python and never really got familiar with the various Python data types, so that's most likely what's messing me up. </p>
<p>Currently I am declaring a list, looping through and another list, and appending one list within another:</p>
<pre><code>import simplejson, json
data = [['apple', 'cat'], ['banana', 'dog'], ['pear', 'fish']]
x = simplejson.loads(data)
# >>> typeError: expected string or buffer..
x = simplejson.dumps(stream)
# >>> [["apple", "cat"], ["banana", "dog"], ["pear", "fish"]]
# - shouldn't JSON encoded strings be like: {{"apple":{"cat"},{"banana":"dog"}}
</code></pre>
<p>So I either: </p>
<ul>
<li>I don't understand JSON Syntax</li>
<li>I don't understand the Pythons JSON module(s)</li>
<li>I'm using an inappropriate data type.</li>
</ul>
| 39 | 2009-06-11T21:37:09Z | 983,907 | <p>JSON uses square brackets for lists ( <code>[ "one", "two", "three" ]</code> ) and curly brackets for key/value dictionaries (also called objects in JavaScript, <code>{"one":1, "two":"b"}</code>).</p>
<p>The dump is quite correct, you get a list of three elements, each one is a list of two strings.</p>
<p>if you wanted a dictionary, maybe something like this:</p>
<pre><code>x = simplejson.dumps(dict(data))
>>> {"pear": "fish", "apple": "cat", "banana": "dog"}
</code></pre>
<p>your expected string ('<code>{{"apple":{"cat"},{"banana":"dog"}}</code>') isn't valid JSON. A</p>
| 3 | 2009-06-11T21:45:40Z | [
"python",
"json",
"encoding",
"types",
"simplejson"
] |
Python JSON encoding | 983,855 | <p>I'm trying to encode data to JSON in Python and I been having a quite a bit of trouble. I believe the problem is simply a misunderstanding. </p>
<p>I'm relatively new to Python and never really got familiar with the various Python data types, so that's most likely what's messing me up. </p>
<p>Currently I am declaring a list, looping through and another list, and appending one list within another:</p>
<pre><code>import simplejson, json
data = [['apple', 'cat'], ['banana', 'dog'], ['pear', 'fish']]
x = simplejson.loads(data)
# >>> typeError: expected string or buffer..
x = simplejson.dumps(stream)
# >>> [["apple", "cat"], ["banana", "dog"], ["pear", "fish"]]
# - shouldn't JSON encoded strings be like: {{"apple":{"cat"},{"banana":"dog"}}
</code></pre>
<p>So I either: </p>
<ul>
<li>I don't understand JSON Syntax</li>
<li>I don't understand the Pythons JSON module(s)</li>
<li>I'm using an inappropriate data type.</li>
</ul>
| 39 | 2009-06-11T21:37:09Z | 983,913 | <p>So, simplejson.loads takes a json string and returns a data structure, which is why you are getting that type error there.</p>
<p>simplejson.dumps(data) comes back with </p>
<pre><code>'[["apple", "cat"], ["banana", "dog"], ["pear", "fish"]]'
</code></pre>
<p>Which is a json array, which is what you want, since you gave this a python array.</p>
<p>If you want to get an "object" type syntax you would instead do</p>
<pre><code>>>> data2 = {'apple':'cat', 'banana':'dog', 'pear':'fish'}
>>> simplejson.dumps(data2)
'{"pear": "fish", "apple": "cat", "banana": "dog"}'
</code></pre>
<p>which is javascript will come out as an object.</p>
| 3 | 2009-06-11T21:46:21Z | [
"python",
"json",
"encoding",
"types",
"simplejson"
] |
Python JSON encoding | 983,855 | <p>I'm trying to encode data to JSON in Python and I been having a quite a bit of trouble. I believe the problem is simply a misunderstanding. </p>
<p>I'm relatively new to Python and never really got familiar with the various Python data types, so that's most likely what's messing me up. </p>
<p>Currently I am declaring a list, looping through and another list, and appending one list within another:</p>
<pre><code>import simplejson, json
data = [['apple', 'cat'], ['banana', 'dog'], ['pear', 'fish']]
x = simplejson.loads(data)
# >>> typeError: expected string or buffer..
x = simplejson.dumps(stream)
# >>> [["apple", "cat"], ["banana", "dog"], ["pear", "fish"]]
# - shouldn't JSON encoded strings be like: {{"apple":{"cat"},{"banana":"dog"}}
</code></pre>
<p>So I either: </p>
<ul>
<li>I don't understand JSON Syntax</li>
<li>I don't understand the Pythons JSON module(s)</li>
<li>I'm using an inappropriate data type.</li>
</ul>
| 39 | 2009-06-11T21:37:09Z | 983,915 | <p>Try:</p>
<pre><code>import simplejson
data = {'apple': 'cat', 'banana':'dog', 'pear':'fish'}
data_json = "{'apple': 'cat', 'banana':'dog', 'pear':'fish'}"
simplejson.loads(data_json) # outputs data
simplejson.dumps(data) # outputs data_joon
</code></pre>
<p>NB: Based on Paolo's answer.</p>
| 3 | 2009-06-11T21:46:39Z | [
"python",
"json",
"encoding",
"types",
"simplejson"
] |
Python JSON encoding | 983,855 | <p>I'm trying to encode data to JSON in Python and I been having a quite a bit of trouble. I believe the problem is simply a misunderstanding. </p>
<p>I'm relatively new to Python and never really got familiar with the various Python data types, so that's most likely what's messing me up. </p>
<p>Currently I am declaring a list, looping through and another list, and appending one list within another:</p>
<pre><code>import simplejson, json
data = [['apple', 'cat'], ['banana', 'dog'], ['pear', 'fish']]
x = simplejson.loads(data)
# >>> typeError: expected string or buffer..
x = simplejson.dumps(stream)
# >>> [["apple", "cat"], ["banana", "dog"], ["pear", "fish"]]
# - shouldn't JSON encoded strings be like: {{"apple":{"cat"},{"banana":"dog"}}
</code></pre>
<p>So I either: </p>
<ul>
<li>I don't understand JSON Syntax</li>
<li>I don't understand the Pythons JSON module(s)</li>
<li>I'm using an inappropriate data type.</li>
</ul>
| 39 | 2009-06-11T21:37:09Z | 984,243 | <p>I think you are simply exchanging <em>dumps</em> and <em>loads</em>. </p>
<pre><code>>>> import json
>>> data = [['apple', 'cat'], ['banana', 'dog'], ['pear', 'fish']]
</code></pre>
<p>The first returns as a (JSON encoded) string its data argument:</p>
<pre><code>>>> encoded_str = json.dumps( data )
>>> encoded_str
'[["apple", "cat"], ["banana", "dog"], ["pear", "fish"]]'
</code></pre>
<p>The second does the opposite, returning the data corresponding to its (JSON encoded) string argument:</p>
<pre><code>>>> decoded_data = json.loads( encoded_str )
>>> decoded_data
[[u'apple', u'cat'], [u'banana', u'dog'], [u'pear', u'fish']]
>>> decoded_data == data
True
</code></pre>
| 16 | 2009-06-11T23:07:36Z | [
"python",
"json",
"encoding",
"types",
"simplejson"
] |
Facebook, Django, and Google App Engine | 984,071 | <p>I'm experimenting with <a href="http://code.google.com/p/app-engine-patch/">app-engine-patch</a> (Django for GAE) on Google App Engine. And I would like to write a Facebook application. Is it possible to use PyFacebook and its middleware? Or is there some other solution?</p>
| 14 | 2009-06-11T22:20:36Z | 984,099 | <p>According to <a href="http://forum.developers.facebook.com/viewtopic.php?id=13396" rel="nofollow">this post</a>, you need a slightly modified PyFacebook that you can download from a URL given in said post (I haven't tried it myself, though).</p>
<p>Edit: that link is wrong -- better link and more discussion on <a href="http://groups.google.com/group/facebook-and-google-app-engine/browse%5Fthread/thread/bc43804fa3032657?pli=1" rel="nofollow">this thread</a>.</p>
| 0 | 2009-06-11T22:27:59Z | [
"python",
"django",
"google-app-engine",
"facebook"
] |
Facebook, Django, and Google App Engine | 984,071 | <p>I'm experimenting with <a href="http://code.google.com/p/app-engine-patch/">app-engine-patch</a> (Django for GAE) on Google App Engine. And I would like to write a Facebook application. Is it possible to use PyFacebook and its middleware? Or is there some other solution?</p>
| 14 | 2009-06-11T22:20:36Z | 984,140 | <p>I run a system on for social networks and facebook on GAE with back-end in Python, front end in Javascript and Flash. I use mostly client side js libraries to pass data back to the server side datastore. This library for facebook to be exact: <a href="http://code.google.com/p/facebookjsapi/">http://code.google.com/p/facebookjsapi/</a> </p>
<p>There is a reason for this. Most of what we are doing will be running on its own site, in iframes in different social networks and in widgets etc. But for the most part this has worked very well. It is good because we can swap out our backend at any time or even run it on multiple platforms as it is also using a python rest GAE library but any backend would do with this setup.</p>
| 7 | 2009-06-11T22:40:35Z | [
"python",
"django",
"google-app-engine",
"facebook"
] |
Facebook, Django, and Google App Engine | 984,071 | <p>I'm experimenting with <a href="http://code.google.com/p/app-engine-patch/">app-engine-patch</a> (Django for GAE) on Google App Engine. And I would like to write a Facebook application. Is it possible to use PyFacebook and its middleware? Or is there some other solution?</p>
| 14 | 2009-06-11T22:20:36Z | 984,903 | <p>Adding the Facebook directory from the PyFacebook install directory to the app-engine-patch application allows you to add 'facebook.djangofb.FacebookMiddleware', to the MIDDLEWARE_CLASSES in settings.py. Then your view can use 'import facebook.djangofb as facebook' and '@facebook.require_login().'</p>
<p>I haven't gone end to end, but when I tried to display the view preceded by '@facebook.require_login()', I was redirected to the Facebook login.</p>
| 5 | 2009-06-12T04:00:57Z | [
"python",
"django",
"google-app-engine",
"facebook"
] |
file won't write in python | 984,216 | <p>I'm trying to replace a string in all the files within the current directory. for some reason, my temp file ends up blank. It seems my .write isn't working because the secondfile was declared outside its scope maybe? I'm new to python, so still climbing the learning curve...thanks!</p>
<p>edit: I'm aware my tempfile isn't being copied currently. I'm also aware there are much more efficient ways of doing this. I'm doing it this way for practice. If someone could answer specifically why the .write method fails to work here, that would be great. Thanks!</p>
<pre><code>import os
import shutil
for filename in os.listdir("."):
file1 = open(filename,'r')
secondfile = open("temp.out",'w')
print filename
for line in file1:
line2 = line.replace('mrddb2.','shpdb2.')
line3 = line2.replace('MRDDB2.','SHPDB2.')
secondfile.write(line3)
print 'file copy in progress'
file1.close()
secondfile.close()
</code></pre>
| 2 | 2009-06-11T23:02:09Z | 984,220 | <p>Firstly, </p>
<p>you have forgotten to copy the temp file back onto the original.</p>
<p>Secondly:</p>
<p>use sed -i or perl -i instead of python.</p>
<p>For instance:</p>
<pre><code>perl -i -pe 's/mrddb2/shpdb2/;s/MRDDB2/SHPDB2/' *
</code></pre>
| 0 | 2009-06-11T23:03:28Z | [
"python",
"file-io",
"for-loop"
] |
file won't write in python | 984,216 | <p>I'm trying to replace a string in all the files within the current directory. for some reason, my temp file ends up blank. It seems my .write isn't working because the secondfile was declared outside its scope maybe? I'm new to python, so still climbing the learning curve...thanks!</p>
<p>edit: I'm aware my tempfile isn't being copied currently. I'm also aware there are much more efficient ways of doing this. I'm doing it this way for practice. If someone could answer specifically why the .write method fails to work here, that would be great. Thanks!</p>
<pre><code>import os
import shutil
for filename in os.listdir("."):
file1 = open(filename,'r')
secondfile = open("temp.out",'w')
print filename
for line in file1:
line2 = line.replace('mrddb2.','shpdb2.')
line3 = line2.replace('MRDDB2.','SHPDB2.')
secondfile.write(line3)
print 'file copy in progress'
file1.close()
secondfile.close()
</code></pre>
| 2 | 2009-06-11T23:02:09Z | 984,296 | <p>I don't have the exact answer for you, but what might help is to stick some <code>print</code> lines in there in strategic places, like print each line before it was modified, then again after it was modified. Then place another one after the line was modified just before it is written to the file. Then just before you close the new file do a:</p>
<p><code>print secondfile.read()</code></p>
<p>You could also try to limit the results you get if there are too many for debugging purposes. You can limit string output by attaching a subscript modifier to the end, for example:</p>
<p><code>print secondfile.read()[:n]</code></p>
<p>If <code>n = 100</code> it will limit the output to 100 characters.</p>
| 0 | 2009-06-11T23:20:50Z | [
"python",
"file-io",
"for-loop"
] |
file won't write in python | 984,216 | <p>I'm trying to replace a string in all the files within the current directory. for some reason, my temp file ends up blank. It seems my .write isn't working because the secondfile was declared outside its scope maybe? I'm new to python, so still climbing the learning curve...thanks!</p>
<p>edit: I'm aware my tempfile isn't being copied currently. I'm also aware there are much more efficient ways of doing this. I'm doing it this way for practice. If someone could answer specifically why the .write method fails to work here, that would be great. Thanks!</p>
<pre><code>import os
import shutil
for filename in os.listdir("."):
file1 = open(filename,'r')
secondfile = open("temp.out",'w')
print filename
for line in file1:
line2 = line.replace('mrddb2.','shpdb2.')
line3 = line2.replace('MRDDB2.','SHPDB2.')
secondfile.write(line3)
print 'file copy in progress'
file1.close()
secondfile.close()
</code></pre>
| 2 | 2009-06-11T23:02:09Z | 984,297 | <p>Your code (correctly indented, though I don't think there's a way to indent it so it runs but doesn't work right) actually seems right. Keep in mind, temp.out will be the replaced contents of only the last source file. Could it be that file is just blank?</p>
| 2 | 2009-06-11T23:21:39Z | [
"python",
"file-io",
"for-loop"
] |
file won't write in python | 984,216 | <p>I'm trying to replace a string in all the files within the current directory. for some reason, my temp file ends up blank. It seems my .write isn't working because the secondfile was declared outside its scope maybe? I'm new to python, so still climbing the learning curve...thanks!</p>
<p>edit: I'm aware my tempfile isn't being copied currently. I'm also aware there are much more efficient ways of doing this. I'm doing it this way for practice. If someone could answer specifically why the .write method fails to work here, that would be great. Thanks!</p>
<pre><code>import os
import shutil
for filename in os.listdir("."):
file1 = open(filename,'r')
secondfile = open("temp.out",'w')
print filename
for line in file1:
line2 = line.replace('mrddb2.','shpdb2.')
line3 = line2.replace('MRDDB2.','SHPDB2.')
secondfile.write(line3)
print 'file copy in progress'
file1.close()
secondfile.close()
</code></pre>
| 2 | 2009-06-11T23:02:09Z | 984,311 | <p>Just glancing at the thing, it appears that your problem is with the 'w'.</p>
<p>It looks like you keep <strong>overwriting</strong>, not <strong>appending</strong>.</p>
<p>So you're basically looping through the file(s), <br />
and by the end you've only copied the last file to your temp file.</p>
<p>You'll may want to open the file with 'a' instead of 'w'.</p>
| 5 | 2009-06-11T23:26:46Z | [
"python",
"file-io",
"for-loop"
] |
file won't write in python | 984,216 | <p>I'm trying to replace a string in all the files within the current directory. for some reason, my temp file ends up blank. It seems my .write isn't working because the secondfile was declared outside its scope maybe? I'm new to python, so still climbing the learning curve...thanks!</p>
<p>edit: I'm aware my tempfile isn't being copied currently. I'm also aware there are much more efficient ways of doing this. I'm doing it this way for practice. If someone could answer specifically why the .write method fails to work here, that would be great. Thanks!</p>
<pre><code>import os
import shutil
for filename in os.listdir("."):
file1 = open(filename,'r')
secondfile = open("temp.out",'w')
print filename
for line in file1:
line2 = line.replace('mrddb2.','shpdb2.')
line3 = line2.replace('MRDDB2.','SHPDB2.')
secondfile.write(line3)
print 'file copy in progress'
file1.close()
secondfile.close()
</code></pre>
| 2 | 2009-06-11T23:02:09Z | 984,377 | <p>if your code is actually indented as showed in the post, the write is working fine. But if it is failing, the write call may be outside the inner for loop. </p>
| 0 | 2009-06-11T23:49:54Z | [
"python",
"file-io",
"for-loop"
] |
file won't write in python | 984,216 | <p>I'm trying to replace a string in all the files within the current directory. for some reason, my temp file ends up blank. It seems my .write isn't working because the secondfile was declared outside its scope maybe? I'm new to python, so still climbing the learning curve...thanks!</p>
<p>edit: I'm aware my tempfile isn't being copied currently. I'm also aware there are much more efficient ways of doing this. I'm doing it this way for practice. If someone could answer specifically why the .write method fails to work here, that would be great. Thanks!</p>
<pre><code>import os
import shutil
for filename in os.listdir("."):
file1 = open(filename,'r')
secondfile = open("temp.out",'w')
print filename
for line in file1:
line2 = line.replace('mrddb2.','shpdb2.')
line3 = line2.replace('MRDDB2.','SHPDB2.')
secondfile.write(line3)
print 'file copy in progress'
file1.close()
secondfile.close()
</code></pre>
| 2 | 2009-06-11T23:02:09Z | 984,389 | <p>Just to make sure I wasn't really missing something, I tested the code and it worked fine for me. Maybe you could try continue for everything but one specific filename and then check the contents of temp.out after that.</p>
<pre><code>import os
for filename in os.listdir("."):
if filename != 'findme.txt': continue
print 'Processing', filename
file1 = open(filename,'r')
secondfile = open("temp.out",'w')
print filename
for line in file1:
line2 = line.replace('mrddb2.','shpdb2.')
line3 = line2.replace('MRDDB2.','SHPDB2.')
print 'About to write:', line3
secondfile.write(line3)
print 'Done with', filename
file1.close()
secondfile.close()
</code></pre>
<p>Also, as others have mentioned, you're just clobbering your temp.out file each time you process a new file. You've also imported shutil without actually doing anything with it. Are you forgetting to copy temp.out back to your original file?</p>
| 0 | 2009-06-11T23:53:30Z | [
"python",
"file-io",
"for-loop"
] |
file won't write in python | 984,216 | <p>I'm trying to replace a string in all the files within the current directory. for some reason, my temp file ends up blank. It seems my .write isn't working because the secondfile was declared outside its scope maybe? I'm new to python, so still climbing the learning curve...thanks!</p>
<p>edit: I'm aware my tempfile isn't being copied currently. I'm also aware there are much more efficient ways of doing this. I'm doing it this way for practice. If someone could answer specifically why the .write method fails to work here, that would be great. Thanks!</p>
<pre><code>import os
import shutil
for filename in os.listdir("."):
file1 = open(filename,'r')
secondfile = open("temp.out",'w')
print filename
for line in file1:
line2 = line.replace('mrddb2.','shpdb2.')
line3 = line2.replace('MRDDB2.','SHPDB2.')
secondfile.write(line3)
print 'file copy in progress'
file1.close()
secondfile.close()
</code></pre>
| 2 | 2009-06-11T23:02:09Z | 1,112,526 | <p>I noticed sometimes it will not print to file if you don't have a file.close after file.write.</p>
<p>For example, this program never actually saves to file, it just makes a blank file (unless you add outfile.close() right after the outfile.write.)</p>
<pre><code>outfile=open("ok.txt","w")
fc="filecontents"
outfile.write(fc.encode("utf-8"))
while 1:
print "working..."
</code></pre>
| 0 | 2009-07-11T00:08:18Z | [
"python",
"file-io",
"for-loop"
] |
file won't write in python | 984,216 | <p>I'm trying to replace a string in all the files within the current directory. for some reason, my temp file ends up blank. It seems my .write isn't working because the secondfile was declared outside its scope maybe? I'm new to python, so still climbing the learning curve...thanks!</p>
<p>edit: I'm aware my tempfile isn't being copied currently. I'm also aware there are much more efficient ways of doing this. I'm doing it this way for practice. If someone could answer specifically why the .write method fails to work here, that would be great. Thanks!</p>
<pre><code>import os
import shutil
for filename in os.listdir("."):
file1 = open(filename,'r')
secondfile = open("temp.out",'w')
print filename
for line in file1:
line2 = line.replace('mrddb2.','shpdb2.')
line3 = line2.replace('MRDDB2.','SHPDB2.')
secondfile.write(line3)
print 'file copy in progress'
file1.close()
secondfile.close()
</code></pre>
| 2 | 2009-06-11T23:02:09Z | 1,112,547 | <p>@OP, you might also want to try fileinput module ( this way, you don't have to use your own temp file)</p>
<pre><code>import fileinput
for filename in os.listdir("."):
for line in fileinput.FileInput(filename,inplace=1):
line = line.strip().replace('mrddb2.','shpdb2.')
line = line.strip().replace('MRDDB2.','SHPDB2.')
print line
</code></pre>
<p>set "inplace" to 1 for editing the file in place. Set to 0 for normal print to stdout</p>
| 0 | 2009-07-11T00:17:16Z | [
"python",
"file-io",
"for-loop"
] |
How to recreate this PHP code in Python? | 984,244 | <p>I've found a PHP script that lets me do what I asked in <a href="http://stackoverflow.com/questions/922148/how-to-make-mechanize-not-fail-with-forms-on-this-page">this</a> SO question. I can use this just fine, but out of curiosity I'd like to recreate the following code in Python. </p>
<p>I can of course use urllib2 to get the page, but I'm at a loss on how to handle the cookies since mechanize (tested with Python 2.5 and 2.6 on Windows and Python 2.5 on Ubuntu...all with latest mechanize version) seems to break on the page. How do I do this in python?</p>
<pre><code>require_once "HTTP/Request.php";
$req = &new HTTP_Request('https://steamcommunity.com');
$req->setMethod(HTTP_REQUEST_METHOD_POST);
$req->addPostData("action", "doLogin");
$req->addPostData("goto", "");
$req->addPostData("steamAccountName", ACC_NAME);
$req->addPostData("steamPassword", ACC_PASS);
echo "Login: ";
$res = $req->sendRequest();
if (PEAR::isError($res))
die($res->getMessage());
$cookies = $req->getResponseCookies();
if ( !$cookies )
die("fail\n");
echo "pass\n";
foreach($cookies as $cookie)
$req->addCookie($cookie['name'],$cookie['value']);
</code></pre>
| 0 | 2009-06-11T23:08:00Z | 984,378 | <p>I'm not familiar with PHP, but this may get you started.
I'm installing the opener here which will apply it to the urlopen method. If you don't want to 'install' the opener(s) you can use the opener object directly. (opener.open(url, data)).</p>
<p>Refer to:
<a href="http://docs.python.org/library/urllib2.html?highlight=urllib2#urllib2.install_opener" rel="nofollow">http://docs.python.org/library/urllib2.html?highlight=urllib2#urllib2.install_opener</a></p>
<pre><code>import urlib2
import urllib
# 1 create handlers
cookieHandler = urllib2.HTTPCookieProcessor() # Needed for cookie handling
redirectionHandler = urllib2.HTTPRedirectHandler() # needed for redirection
# 2 apply the handler to an opener
opener = urllib2.build_opener(cookieHandler, redirectionHandler)
# 3. Install the openers
urllib2.install_opener(opener)
# prep post data
datalist_tuples = [ ('action', 'doLogin'),
('goto', ''),
('steamAccountName', ACC_NAME),
('steamPassword', ACC_PASS)
]
url = 'https://steamcommunity.com'
post_data = urllib.urlencode(datalist_tuples)
resp_f = urllib2.urlopen(url, post_data)
</code></pre>
| 5 | 2009-06-11T23:50:06Z | [
"php",
"python",
"http",
"forms",
"automation"
] |
How to recreate this PHP code in Python? | 984,244 | <p>I've found a PHP script that lets me do what I asked in <a href="http://stackoverflow.com/questions/922148/how-to-make-mechanize-not-fail-with-forms-on-this-page">this</a> SO question. I can use this just fine, but out of curiosity I'd like to recreate the following code in Python. </p>
<p>I can of course use urllib2 to get the page, but I'm at a loss on how to handle the cookies since mechanize (tested with Python 2.5 and 2.6 on Windows and Python 2.5 on Ubuntu...all with latest mechanize version) seems to break on the page. How do I do this in python?</p>
<pre><code>require_once "HTTP/Request.php";
$req = &new HTTP_Request('https://steamcommunity.com');
$req->setMethod(HTTP_REQUEST_METHOD_POST);
$req->addPostData("action", "doLogin");
$req->addPostData("goto", "");
$req->addPostData("steamAccountName", ACC_NAME);
$req->addPostData("steamPassword", ACC_PASS);
echo "Login: ";
$res = $req->sendRequest();
if (PEAR::isError($res))
die($res->getMessage());
$cookies = $req->getResponseCookies();
if ( !$cookies )
die("fail\n");
echo "pass\n";
foreach($cookies as $cookie)
$req->addCookie($cookie['name'],$cookie['value']);
</code></pre>
| 0 | 2009-06-11T23:08:00Z | 984,409 | <p>Similar to monkut's answer, but a little more concise.</p>
<pre><code>import urllib, urllib2
def steam_login(username,password):
data = urllib.urlencode({
'action': 'doLogin',
'goto': '',
'steamAccountName': username,
'steamPassword': password,
})
request = urllib2.Request('https://steamcommunity.com/',data)
cookie_handler = urllib2.HTTPCookieProcessor()
opener = urllib2.build_opener(cookie_handler)
response = opener.open(request)
if not 200 <= response.code < 300:
raise Exception("HTTP error: %d %s" % (response.code,response.msg))
else:
return cookie_handler.cookiejar
</code></pre>
<p>It returns the cookie jar, which you can use in other requests. Just pass it to the <code>HTTPCookieProcessor</code> constructor.</p>
<p>monkut's answer installs a global <code>HTTPCookieProcessor</code>, which stores the cookies between requests. My solution does not modify the global state.</p>
| 6 | 2009-06-12T00:02:28Z | [
"php",
"python",
"http",
"forms",
"automation"
] |
Does Pythoncard have an on change event? | 984,263 | <p>I want to do some validation whenever the value of a textfield changes. I don't see an on change event mentioned in the documentation though.</p>
| 0 | 2009-06-11T23:12:31Z | 984,511 | <p>Pythoncard is built on wxPython, and wxPython has a text change event. I know nothing about Pythoncard, but in wxPython one would use:</p>
<pre><code> t1 = wx.TextCtrl(self, -1, "some text", size=(125, -1)) # to make the text control
self.Bind(wx.EVT_TEXT, self.OnText, t1) # your OnText method handles the event
</code></pre>
<p>For events, there's <code>wx.EVT_TEXT</code>, <code>wx.EVT_CHAR</code>, <code>wx.EVT_TEXT_ENTER</code>, and more details about these can be found in the <a href="http://docs.wxwidgets.org/stable/wx%5Fwxtextctrl.html#wxtextctrl" rel="nofollow">wxPython docs</a>, and also usage examples in the wxPython demo if you happen to have that. Also, wxPython has several types of the text entry controls, and I'm assuming that you're using the wxTextCtrl, though the docs should have info on the others as well.</p>
| 1 | 2009-06-12T00:40:10Z | [
"python",
"events",
"event-handling",
"pythoncard",
"pycard"
] |
Does Pythoncard have an on change event? | 984,263 | <p>I want to do some validation whenever the value of a textfield changes. I don't see an on change event mentioned in the documentation though.</p>
| 0 | 2009-06-11T23:12:31Z | 2,066,008 | <p>I think the textUpdate event is what your looking for.</p>
<p><a href="http://pythoncard.sourceforge.net/framework/components/TextField.html" rel="nofollow">http://pythoncard.sourceforge.net/framework/components/TextField.html</a></p>
| 1 | 2010-01-14T17:11:52Z | [
"python",
"events",
"event-handling",
"pythoncard",
"pycard"
] |
Dynamic Language Features and Meta-Programming Used in Django | 984,272 | <p>Any good summary articles of the dynamic language and meta-programming features of Python that get utilized by Django? Or can we build that out here? Setting this up as a wiki-style entry.</p>
| 2 | 2009-06-11T23:14:48Z | 985,561 | <p>Marty Alchin (Gulopine) has a few articles on various bits of Django internals - including metaclasses and descriptors - on his blog:
<a href="http://martyalchin.com/categories/django/" rel="nofollow">http://martyalchin.com/categories/django/</a></p>
| 2 | 2009-06-12T08:12:20Z | [
"python",
"django",
"metaprogramming",
"dynamic-languages"
] |
Formatting date times provided as strings in Django | 984,412 | <p>In my Django application I get times from a webservice, provided as a string, that I use in my templates:</p>
<p>{{date.string}}</p>
<p>This provides me with a date such as:</p>
<p>2009-06-11 17:02:09+0000</p>
<p>These are obviously a bit ugly, and I'd like to present them in a nice format to my users. Django has a great built in date formatter, which would do exactly what I wanted:</p>
<p>{{ value|date:"D d M Y" }}</p>
<p>However this expects the value to be provided as a date object, and not a string. So I can't format it using this. After searching here on StackOverflow pythons strptime seems to do what I want, but being fairly new to Python I was wondering if anyone could come up with an easier way of getting date formatting using strings, without having to resort to writing a whole new custom strptime template tag? </p>
| 7 | 2009-06-12T00:03:53Z | 984,446 | <p>This doesn't deal with the Django tag, but the strptime code is:</p>
<pre><code>d = strptime("2009-06-11 17:02:09+0000", "%Y-%m-%d %H:%M:%S+0000")
</code></pre>
<p>Note that you're dropping the time zone info.</p>
| 0 | 2009-06-12T00:14:08Z | [
"python",
"django",
"date",
"time",
"strptime"
] |
Formatting date times provided as strings in Django | 984,412 | <p>In my Django application I get times from a webservice, provided as a string, that I use in my templates:</p>
<p>{{date.string}}</p>
<p>This provides me with a date such as:</p>
<p>2009-06-11 17:02:09+0000</p>
<p>These are obviously a bit ugly, and I'd like to present them in a nice format to my users. Django has a great built in date formatter, which would do exactly what I wanted:</p>
<p>{{ value|date:"D d M Y" }}</p>
<p>However this expects the value to be provided as a date object, and not a string. So I can't format it using this. After searching here on StackOverflow pythons strptime seems to do what I want, but being fairly new to Python I was wondering if anyone could come up with an easier way of getting date formatting using strings, without having to resort to writing a whole new custom strptime template tag? </p>
| 7 | 2009-06-12T00:03:53Z | 984,447 | <p>You're probably better off parsing the string received from the webservice in your view code, and then passing the datetime.date (or string) to the template for display. The spirit of Django templates is that very little coding work should be done there; they are for presentation only, and that's why they go out of their way to prevent you from writing Python code embedded in HTML.</p>
<p>Something like:</p>
<pre><code>from datetime import datetime
from django.shortcuts import render_to_response
def my_view(request):
ws_date_as_string = ... get the webservice date
the_date = datetime.strptime(ws_date, "%Y-%m-%d %H:%M:%S+0000")
return render_to_response('my_template.html', {'date':the_date})
</code></pre>
<p>As Matthew points out, this drops the timezone. If you wish to preserve the offset from GMT, try using the excellent third-party <a href="http://labix.org/python-dateutil">dateutils</a> library, which seamlessly handles parsing dates in multiple formats, with timezones, without having to provide a time format template like strptime.</p>
| 10 | 2009-06-12T00:14:16Z | [
"python",
"django",
"date",
"time",
"strptime"
] |
Django : Timestamp string custom field | 984,460 | <p>I'm trying to create a custom timestamp field.</p>
<pre><code>class TimestampKey(models.CharField):
__metaclass__ = models.SubfieldBase
def __init__(self, *args, **kwargs):
import time
kwargs['unique'] = True
kwargs['max_length'] = 20
kwargs['auto_created'] = True
kwargs['editable']=False
super(TimestampKey, self).__init__(*args, **kwargs)
def to_python(self, value) :
return value
def get_db_prep_value(self, value) :
try:
import time
t = time.localtime()
value = reduce(lambda a,b:str(a)+str(b),t)
except ValueError:
value = {}
return value
class Table1(models.Model):
f = TimestampKey(primary_key=True)
n = ....
</code></pre>
<p>It stores the value with appropriate timestamp in the db. But it doesnt populate the field 'f' in the object.</p>
<p>Eg:</p>
<pre><code>t1 = Table1(n="some value")
t1.f -> blank
t1.save()
t1.f -> blank.
</code></pre>
<p>This is the problem. Am I missing something so that it doesnt populate the filed?
Please shed some light on this.</p>
<p>Thanks.</p>
| 0 | 2009-06-12T00:17:49Z | 984,661 | <p>The <code>get_db_prep_value</code> method only prepares a value for the database, but doesn't send the prepared value back to the Python object in any way. For that you would need the <code>pre_save</code> method, I think.</p>
<p>Fortunately, there's already an "auto_now" option on DateField and DateTimeField that does what you want, using <code>pre_save</code>. Try:</p>
<pre><code>class Table1(models.Model):
f = models.DateTimeField(auto_now=True)
</code></pre>
<p>(If you must write your own <code>pre_save</code>, look at how <code>auto_now</code> modifies the actual model instance in <code>/django/db/models/fields/__init__.py</code> on lines 486-492:</p>
<pre><code>def pre_save(self, model_instance, add):
if self.auto_now or (self.auto_now_add and add):
value = datetime.datetime.now()
setattr(model_instance, self.attname, value)
return value
else:
return super(DateField, self).pre_save(model_instance, add)
</code></pre>
<p>)</p>
| 1 | 2009-06-12T01:42:26Z | [
"python",
"django",
"django-models"
] |
Django : Timestamp string custom field | 984,460 | <p>I'm trying to create a custom timestamp field.</p>
<pre><code>class TimestampKey(models.CharField):
__metaclass__ = models.SubfieldBase
def __init__(self, *args, **kwargs):
import time
kwargs['unique'] = True
kwargs['max_length'] = 20
kwargs['auto_created'] = True
kwargs['editable']=False
super(TimestampKey, self).__init__(*args, **kwargs)
def to_python(self, value) :
return value
def get_db_prep_value(self, value) :
try:
import time
t = time.localtime()
value = reduce(lambda a,b:str(a)+str(b),t)
except ValueError:
value = {}
return value
class Table1(models.Model):
f = TimestampKey(primary_key=True)
n = ....
</code></pre>
<p>It stores the value with appropriate timestamp in the db. But it doesnt populate the field 'f' in the object.</p>
<p>Eg:</p>
<pre><code>t1 = Table1(n="some value")
t1.f -> blank
t1.save()
t1.f -> blank.
</code></pre>
<p>This is the problem. Am I missing something so that it doesnt populate the filed?
Please shed some light on this.</p>
<p>Thanks.</p>
| 0 | 2009-06-12T00:17:49Z | 987,336 | <p>Is it wise to use a timestamp as your primary key? If your database uses ISO 8601 or really any time format in which second is the smallest time interval... Well, anyway, my point is that you have no guarantee, especially if this is going to be a web-facing application that two entries are going to resolve within the minimum time interval. That is, if the smallest time interval is a second, as in ISO 8601, if you get two requests to save in the same second, you're going to get an error condition. Why not stick to automatically incrementing integer keys and just make the timestamp its own field?</p>
| 3 | 2009-06-12T15:33:41Z | [
"python",
"django",
"django-models"
] |
PythonCard - Can I launch a CustomDialog Stand Alone? | 984,506 | <p>I have a CustomDialog I made to let the user configure settings. Normally I want this to be launched from a menu item within the main application which works fine.</p>
<p>But during the install, I want to launch just the dialog to let the user configure the settings. Is there a way I can have both?</p>
| 0 | 2009-06-12T00:38:13Z | 984,686 | <p>With a little supporting code you can -- see e.g. <a href="http://www.freenet.org.nz/python/PythonCard/wizard.py" rel="nofollow">wizard.py</a> which launches an almost-stand-alone custom dialog subclass "wizard".</p>
| 1 | 2009-06-12T01:54:42Z | [
"python",
"user-interface",
"wxpython",
"pythoncard",
"pycard"
] |
Correct way of handling exceptions in Python? | 984,526 | <p>I have searched for other posts, as I felt this is a rather common problem, but all other Python exception questions I have found didn't reflect my problem.</p>
<p>I will try to be as specific here as I can, so I will give a direct example. And pleeeeease do not post any workarounds for this specific problem. I am not specifically interested how you can send an email much nicer with xyz.
I want to know how you generally deal with dependent, error prone statements.</p>
<p>My question is, how to handle exceptions nicely, ones that depend on one another, meaning:
Only if the first step was successful, try the next, and so on. One more criterion is: All exceptions have to be caught, this code has to be robust.</p>
<p>For your consideration, an example:</p>
<pre><code>try:
server = smtplib.SMTP(host) #can throw an exception
except smtplib.socket.gaierror:
#actually it can throw a lot more, this is just an example
pass
else: #only if no exception was thrown we may continue
try:
server.login(username, password)
except SMTPAuthenticationError:
pass # do some stuff here
finally:
#we can only run this when the first try...except was successful
#else this throws an exception itself!
server.quit()
else:
try:
# this is already the 3rd nested try...except
# for such a simple procedure! horrible
server.sendmail(addr, [to], msg.as_string())
return True
except Exception:
return False
finally:
server.quit()
return False
</code></pre>
<p>This looks extremely unpythonic to me, and the error handling code is triple the real business code, but on the other hand how can I handle several statements that are dependent on one another, meaning statement1 is prerequisite for statement2 and so on?</p>
<p>I am also interested in proper resource cleanup, even Python can manage that for itself. </p>
<p>Thanks, Tom</p>
| 25 | 2009-06-12T00:45:51Z | 984,552 | <p>Why not one big try: block? This way, if any exception is caught, you'll go all the way to the except. And as long as all the exceptions for the different steps are different, you can always tell which part it was that fired the exception.</p>
| 0 | 2009-06-12T00:57:05Z | [
"python",
"exception"
] |
Correct way of handling exceptions in Python? | 984,526 | <p>I have searched for other posts, as I felt this is a rather common problem, but all other Python exception questions I have found didn't reflect my problem.</p>
<p>I will try to be as specific here as I can, so I will give a direct example. And pleeeeease do not post any workarounds for this specific problem. I am not specifically interested how you can send an email much nicer with xyz.
I want to know how you generally deal with dependent, error prone statements.</p>
<p>My question is, how to handle exceptions nicely, ones that depend on one another, meaning:
Only if the first step was successful, try the next, and so on. One more criterion is: All exceptions have to be caught, this code has to be robust.</p>
<p>For your consideration, an example:</p>
<pre><code>try:
server = smtplib.SMTP(host) #can throw an exception
except smtplib.socket.gaierror:
#actually it can throw a lot more, this is just an example
pass
else: #only if no exception was thrown we may continue
try:
server.login(username, password)
except SMTPAuthenticationError:
pass # do some stuff here
finally:
#we can only run this when the first try...except was successful
#else this throws an exception itself!
server.quit()
else:
try:
# this is already the 3rd nested try...except
# for such a simple procedure! horrible
server.sendmail(addr, [to], msg.as_string())
return True
except Exception:
return False
finally:
server.quit()
return False
</code></pre>
<p>This looks extremely unpythonic to me, and the error handling code is triple the real business code, but on the other hand how can I handle several statements that are dependent on one another, meaning statement1 is prerequisite for statement2 and so on?</p>
<p>I am also interested in proper resource cleanup, even Python can manage that for itself. </p>
<p>Thanks, Tom</p>
| 25 | 2009-06-12T00:45:51Z | 984,575 | <p>In general, you want to use as few try blocks as possible, distinguishing failure conditions by the kinds of exceptions they throw. For instance, here's my refactoring of the code you posted:</p>
<pre><code>try:
server = smtplib.SMTP(host)
server.login(username, password) # Only runs if the previous line didn't throw
server.sendmail(addr, [to], msg.as_string())
return True
except smtplib.socket.gaierror:
pass # Couldn't contact the host
except SMTPAuthenticationError:
pass # Login failed
except SomeSendMailError:
pass # Couldn't send mail
finally:
if server:
server.quit()
return False
</code></pre>
<p>Here, we use the fact that smtplib.SMTP(), server.login(), and server.sendmail() all throw different exceptions to flatten the tree of try-catch blocks. In the finally block we test server explicitly to avoid invoking quit() on the nil object.</p>
<p>We could also use three <em>sequential</em> try-catch blocks, returning False in the exception conditions, if there are overlapping exception cases that need to be handled separately:</p>
<pre><code>try:
server = smtplib.SMTP(host)
except smtplib.socket.gaierror:
return False # Couldn't contact the host
try:
server.login(username, password)
except SMTPAuthenticationError:
server.quit()
return False # Login failed
try:
server.sendmail(addr, [to], msg.as_string())
except SomeSendMailError:
server.quit()
return False # Couldn't send mail
return True
</code></pre>
<p>This isn't quite as nice, as you have to kill the server in more than one place, but now we can handle specific exception types different ways in different places without maintaining any extra state.</p>
| 12 | 2009-06-12T01:09:53Z | [
"python",
"exception"
] |
Correct way of handling exceptions in Python? | 984,526 | <p>I have searched for other posts, as I felt this is a rather common problem, but all other Python exception questions I have found didn't reflect my problem.</p>
<p>I will try to be as specific here as I can, so I will give a direct example. And pleeeeease do not post any workarounds for this specific problem. I am not specifically interested how you can send an email much nicer with xyz.
I want to know how you generally deal with dependent, error prone statements.</p>
<p>My question is, how to handle exceptions nicely, ones that depend on one another, meaning:
Only if the first step was successful, try the next, and so on. One more criterion is: All exceptions have to be caught, this code has to be robust.</p>
<p>For your consideration, an example:</p>
<pre><code>try:
server = smtplib.SMTP(host) #can throw an exception
except smtplib.socket.gaierror:
#actually it can throw a lot more, this is just an example
pass
else: #only if no exception was thrown we may continue
try:
server.login(username, password)
except SMTPAuthenticationError:
pass # do some stuff here
finally:
#we can only run this when the first try...except was successful
#else this throws an exception itself!
server.quit()
else:
try:
# this is already the 3rd nested try...except
# for such a simple procedure! horrible
server.sendmail(addr, [to], msg.as_string())
return True
except Exception:
return False
finally:
server.quit()
return False
</code></pre>
<p>This looks extremely unpythonic to me, and the error handling code is triple the real business code, but on the other hand how can I handle several statements that are dependent on one another, meaning statement1 is prerequisite for statement2 and so on?</p>
<p>I am also interested in proper resource cleanup, even Python can manage that for itself. </p>
<p>Thanks, Tom</p>
| 25 | 2009-06-12T00:45:51Z | 984,589 | <p>I like David's answer but if you are stuck on the server exceptions you can also check for server if is None or states. I flattened out the method a bit bit it is still a but unpythonic looking but more readable in the logic at the bottom.</p>
<pre><code>server = None
def server_obtained(host):
try:
server = smtplib.SMTP(host) #can throw an exception
return True
except smtplib.socket.gaierror:
#actually it can throw a lot more, this is just an example
return False
def server_login(username, password):
loggedin = False
try:
server.login(username, password)
loggedin = True
except SMTPAuthenticationError:
pass # do some stuff here
finally:
#we can only run this when the first try...except was successful
#else this throws an exception itself!
if(server is not None):
server.quit()
return loggedin
def send_mail(addr, to, msg):
sent = False
try:
server.sendmail(addr, to, msg)
sent = True
except Exception:
return False
finally:
server.quit()
return sent
def do_msg_send():
if(server_obtained(host)):
if(server_login(username, password)):
if(send_mail(addr, [to], msg.as_string())):
return True
return False
</code></pre>
| 0 | 2009-06-12T01:16:43Z | [
"python",
"exception"
] |
Correct way of handling exceptions in Python? | 984,526 | <p>I have searched for other posts, as I felt this is a rather common problem, but all other Python exception questions I have found didn't reflect my problem.</p>
<p>I will try to be as specific here as I can, so I will give a direct example. And pleeeeease do not post any workarounds for this specific problem. I am not specifically interested how you can send an email much nicer with xyz.
I want to know how you generally deal with dependent, error prone statements.</p>
<p>My question is, how to handle exceptions nicely, ones that depend on one another, meaning:
Only if the first step was successful, try the next, and so on. One more criterion is: All exceptions have to be caught, this code has to be robust.</p>
<p>For your consideration, an example:</p>
<pre><code>try:
server = smtplib.SMTP(host) #can throw an exception
except smtplib.socket.gaierror:
#actually it can throw a lot more, this is just an example
pass
else: #only if no exception was thrown we may continue
try:
server.login(username, password)
except SMTPAuthenticationError:
pass # do some stuff here
finally:
#we can only run this when the first try...except was successful
#else this throws an exception itself!
server.quit()
else:
try:
# this is already the 3rd nested try...except
# for such a simple procedure! horrible
server.sendmail(addr, [to], msg.as_string())
return True
except Exception:
return False
finally:
server.quit()
return False
</code></pre>
<p>This looks extremely unpythonic to me, and the error handling code is triple the real business code, but on the other hand how can I handle several statements that are dependent on one another, meaning statement1 is prerequisite for statement2 and so on?</p>
<p>I am also interested in proper resource cleanup, even Python can manage that for itself. </p>
<p>Thanks, Tom</p>
| 25 | 2009-06-12T00:45:51Z | 984,652 | <p>Just using one try-block is the way to go. This is exactly what they
are designed for: only execute the next statement if the previous
statement did not throw an exception. As for the resource clean-ups,
maybe you can check the resource if it needs to be cleaned up
(e.g. myfile.is_open(), ...) This does add some extra conditions, but
they will only be executed in the exceptional case. To handle the case
that the same Exception can be raised for different reasons, you
should be able to retrieve the reason from the Exception.</p>
<p>I suggest code like this:</p>
<pre><code>server = None
try:
server = smtplib.SMTP(host) #can throw an exception
server.login(username, password)
server.sendmail(addr, [to], msg.as_string())
server.quit()
return True
except smtplib.socket.gaierror:
pass # do some stuff here
except SMTPAuthenticationError:
pass # do some stuff here
except Exception, msg:
# Exception can have several reasons
if msg=='xxx':
pass # do some stuff here
elif:
pass # do some other stuff here
if server:
server.quit()
return False
</code></pre>
<p>It is no uncommon, that error handling code exceeds business code. Correct error handling can be complex.
But to increase maintainability it helps to separate the business code from the error handling code.</p>
| 1 | 2009-06-12T01:39:05Z | [
"python",
"exception"
] |
Correct way of handling exceptions in Python? | 984,526 | <p>I have searched for other posts, as I felt this is a rather common problem, but all other Python exception questions I have found didn't reflect my problem.</p>
<p>I will try to be as specific here as I can, so I will give a direct example. And pleeeeease do not post any workarounds for this specific problem. I am not specifically interested how you can send an email much nicer with xyz.
I want to know how you generally deal with dependent, error prone statements.</p>
<p>My question is, how to handle exceptions nicely, ones that depend on one another, meaning:
Only if the first step was successful, try the next, and so on. One more criterion is: All exceptions have to be caught, this code has to be robust.</p>
<p>For your consideration, an example:</p>
<pre><code>try:
server = smtplib.SMTP(host) #can throw an exception
except smtplib.socket.gaierror:
#actually it can throw a lot more, this is just an example
pass
else: #only if no exception was thrown we may continue
try:
server.login(username, password)
except SMTPAuthenticationError:
pass # do some stuff here
finally:
#we can only run this when the first try...except was successful
#else this throws an exception itself!
server.quit()
else:
try:
# this is already the 3rd nested try...except
# for such a simple procedure! horrible
server.sendmail(addr, [to], msg.as_string())
return True
except Exception:
return False
finally:
server.quit()
return False
</code></pre>
<p>This looks extremely unpythonic to me, and the error handling code is triple the real business code, but on the other hand how can I handle several statements that are dependent on one another, meaning statement1 is prerequisite for statement2 and so on?</p>
<p>I am also interested in proper resource cleanup, even Python can manage that for itself. </p>
<p>Thanks, Tom</p>
| 25 | 2009-06-12T00:45:51Z | 984,682 | <p>Instead of using the try/except's else block, you could simply return when it errors:</p>
<pre><code>def send_message(addr, to, msg):
## Connect to host
try:
server = smtplib.SMTP(host) #can throw an exception
except smtplib.socket.gaierror:
return False
## Login
try:
server.login(username, password)
except SMTPAuthenticationError:
server.quit()
return False
## Send message
try:
server.sendmail(addr, [to], msg.as_string())
return True
except Exception: # try to avoid catching Exception unless you have too
return False
finally:
server.quit()
</code></pre>
<p>That's perfectly readable and Pythonic..</p>
<p>Another way of doing this is, rather than worry about the specific implementation, decide how you want your code to look, for example..</p>
<pre><code>sender = MyMailer("username", "password") # the except SocketError/AuthError could go here
try:
sender.message("addr..", ["to.."], "message...")
except SocketError:
print "Couldn't connect to server"
except AuthError:
print "Invalid username and/or password!"
else:
print "Message sent!"
</code></pre>
<p>Then write the code for the <code>message()</code> method, catching any errors you expect, and raising your own custom one, and handle that where it's relevant. Your class may look something like..</p>
<pre><code>class ConnectionError(Exception): pass
class AuthError(Exception): pass
class SendError(Exception): pass
class MyMailer:
def __init__(self, host, username, password):
self.host = host
self.username = username
self.password = password
def connect(self):
try:
self.server = smtp.SMTP(self.host)
except smtplib.socket.gaierror:
raise ConnectionError("Error connecting to %s" % (self.host))
def auth(self):
try:
self.server.login(self.username, self.password)
except SMTPAuthenticationError:
raise AuthError("Invalid username (%s) and/or password" % (self.username))
def message(self, addr, to, msg):
try:
server.sendmail(addr, [to], msg.as_string())
except smtplib.something.senderror, errormsg:
raise SendError("Couldn't send message: %s" % (errormsg))
except smtp.socket.timeout:
raise ConnectionError("Socket error while sending message")
</code></pre>
| 23 | 2009-06-12T01:53:55Z | [
"python",
"exception"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.