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
Matching text within P tags in HTML
923,472
<p>I'd like to match the contents within each paragraph in html using a python regular expression. These paragraphs always have BR tags inside them like so:</p> <pre><code>&lt;p class="thisClass"&gt;this is nice &lt;br /&gt;&lt;br /&gt; isn't it?&lt;/p&gt; </code></pre> <p>I'm currently using this pattern:</p> <pre><code>pattern = re.compile('&lt;p class=\"thisClass\"&gt;(.*?)&lt;\/p&gt;') </code></pre> <p>Then I'm using:</p> <pre><code>pattern.findall(html) </code></pre> <p>to find all the matches. However, it only matches two of 28 paragraphs I have, and it looks like that's because those two don't have BR tags inside of them and the rest do. What am I doing wrong? What can I do to fix it? Thanks!</p>
2
2009-05-28T22:16:13Z
923,530
<p>It turns out the answer was to include re.S as a flag which allows the "." character to match newlines as well.</p> <pre><code>pattern = re.compile('&lt;p class=\"thisClass\"&gt;(.*?)&lt;\/p&gt;', re.S) </code></pre> <p>This works perfectly.</p>
3
2009-05-28T22:31:34Z
[ "python", "html", "regex" ]
python - match on array return value
923,553
<p>I want to do a functional like pattern match to get the first two elements, and then the rest of an array return value.</p> <p>For example, assume that perms(x) returns a list of values, and I want to do this:</p> <pre><code>seq=perms(x) a = seq[0] b = seq[1] rest = seq[2:] </code></pre> <p>Of course I can shorten to:</p> <pre><code>[a,b] = seq[0:2] rest = seq[2:] </code></pre> <p>Can I use some notation to do this?</p> <pre><code>[a,b,more] = perms(x) </code></pre> <p>or conceptually:</p> <pre><code>[a,b,more..] = perms(x) </code></pre> <p>PROLOG &amp; functional languages do list decomposition so nicely like this!</p>
2
2009-05-28T22:37:42Z
923,562
<p>You can do it in Python 3 like this:</p> <pre><code>(a, b, *rest) = seq </code></pre> <p>See the <a href="http://www.python.org/dev/peps/pep-3132/" rel="nofollow">extended iterable unpacking PEP</a> for more details.</p>
6
2009-05-28T22:41:11Z
[ "python", "list" ]
python - match on array return value
923,553
<p>I want to do a functional like pattern match to get the first two elements, and then the rest of an array return value.</p> <p>For example, assume that perms(x) returns a list of values, and I want to do this:</p> <pre><code>seq=perms(x) a = seq[0] b = seq[1] rest = seq[2:] </code></pre> <p>Of course I can shorten to:</p> <pre><code>[a,b] = seq[0:2] rest = seq[2:] </code></pre> <p>Can I use some notation to do this?</p> <pre><code>[a,b,more] = perms(x) </code></pre> <p>or conceptually:</p> <pre><code>[a,b,more..] = perms(x) </code></pre> <p>PROLOG &amp; functional languages do list decomposition so nicely like this!</p>
2
2009-05-28T22:37:42Z
923,571
<p>For Python 2, I know you can do it with a function:</p> <pre><code>&gt;&gt;&gt; def getValues(a, b, *more): return a, b, more &gt;&gt;&gt; seq = [1,2,3,4,5] &gt;&gt;&gt; a, b, more = getValues(*seq) &gt;&gt;&gt; a 1 &gt;&gt;&gt; b 2 &gt;&gt;&gt; more (3, 4, 5) </code></pre> <p>But not sure if there's any way of doing it like <a href="http://stackoverflow.com/questions/923553/python-match-on-array-return-value/923562#923562">Ayman's Python 3 suggestion</a></p>
2
2009-05-28T22:43:54Z
[ "python", "list" ]
python - match on array return value
923,553
<p>I want to do a functional like pattern match to get the first two elements, and then the rest of an array return value.</p> <p>For example, assume that perms(x) returns a list of values, and I want to do this:</p> <pre><code>seq=perms(x) a = seq[0] b = seq[1] rest = seq[2:] </code></pre> <p>Of course I can shorten to:</p> <pre><code>[a,b] = seq[0:2] rest = seq[2:] </code></pre> <p>Can I use some notation to do this?</p> <pre><code>[a,b,more] = perms(x) </code></pre> <p>or conceptually:</p> <pre><code>[a,b,more..] = perms(x) </code></pre> <p>PROLOG &amp; functional languages do list decomposition so nicely like this!</p>
2
2009-05-28T22:37:42Z
923,574
<p>In python 2, your question is very close to an answer already:</p> <pre><code>a, b, more = (seq[0], seq[1], seq[2:]) </code></pre> <p>or:</p> <pre><code>(a, b), more = (seq[0:2], seq[2:]) </code></pre>
3
2009-05-28T22:44:22Z
[ "python", "list" ]
python - match on array return value
923,553
<p>I want to do a functional like pattern match to get the first two elements, and then the rest of an array return value.</p> <p>For example, assume that perms(x) returns a list of values, and I want to do this:</p> <pre><code>seq=perms(x) a = seq[0] b = seq[1] rest = seq[2:] </code></pre> <p>Of course I can shorten to:</p> <pre><code>[a,b] = seq[0:2] rest = seq[2:] </code></pre> <p>Can I use some notation to do this?</p> <pre><code>[a,b,more] = perms(x) </code></pre> <p>or conceptually:</p> <pre><code>[a,b,more..] = perms(x) </code></pre> <p>PROLOG &amp; functional languages do list decomposition so nicely like this!</p>
2
2009-05-28T22:37:42Z
975,403
<p>Very nice, thanks.</p> <p>The suggestions where one dissects the array on the fight-hand side don't work so well for me, as I actually wanted to pattern match on the returns from a generator expression.</p> <p>for (a, b, more) in perms(seq): ...</p> <p>I like the P3 solution, but have to wait for Komodo to support it!</p>
0
2009-06-10T12:59:16Z
[ "python", "list" ]
Python Environment Variables in Windows?
923,586
<p>I'm developing a script that runs a program with other scripts over and over for testing purposes.</p> <p>How it currently works is I have one Python script which I launch. That script calls the program and loads the other scripts. It kills the program after 60 seconds to launch the program again with the next script.</p> <p>For some scripts, 60 seconds is too long, so I was wondering if I am able to set a FLAG variable (not in the main script), such that when the script finishes, it sets FLAG, so the main script and read FLAG and kill the process?</p> <p>Thanks for the help, my writing may be confusing, so please let me know if you cannot fully understand.</p>
0
2009-05-28T22:48:17Z
923,787
<p>You could use <a href="http://docs.python.org/library/atexit.html" rel="nofollow">atexit</a> to write a small file (flag.txt) when script1.py exits. mainscript.py could regularly be checking for the existence of flag.txt and when it finds it, will kill program.exe and exit.</p> <p>Edit: I've set persistent environment variables using <a href="http://code.activestate.com/recipes/416087/" rel="nofollow">this</a>, but I only use it for python-based installation scripts. Usually I'm pretty shy about messing with the registry. (this is for windows btw) </p>
1
2009-05-28T23:55:33Z
[ "python", "windows", "testing", "environment-variables" ]
Python Environment Variables in Windows?
923,586
<p>I'm developing a script that runs a program with other scripts over and over for testing purposes.</p> <p>How it currently works is I have one Python script which I launch. That script calls the program and loads the other scripts. It kills the program after 60 seconds to launch the program again with the next script.</p> <p>For some scripts, 60 seconds is too long, so I was wondering if I am able to set a FLAG variable (not in the main script), such that when the script finishes, it sets FLAG, so the main script and read FLAG and kill the process?</p> <p>Thanks for the help, my writing may be confusing, so please let me know if you cannot fully understand.</p>
0
2009-05-28T22:48:17Z
924,069
<p>This seems like a perfect use case for sockets, in particular <a href="http://docs.python.org/library/asyncore.html" rel="nofollow">asyncore</a>.</p>
0
2009-05-29T01:54:30Z
[ "python", "windows", "testing", "environment-variables" ]
Python Environment Variables in Windows?
923,586
<p>I'm developing a script that runs a program with other scripts over and over for testing purposes.</p> <p>How it currently works is I have one Python script which I launch. That script calls the program and loads the other scripts. It kills the program after 60 seconds to launch the program again with the next script.</p> <p>For some scripts, 60 seconds is too long, so I was wondering if I am able to set a FLAG variable (not in the main script), such that when the script finishes, it sets FLAG, so the main script and read FLAG and kill the process?</p> <p>Thanks for the help, my writing may be confusing, so please let me know if you cannot fully understand.</p>
0
2009-05-28T22:48:17Z
2,318,893
<p>You cannot use environment variables in this way. As you have discovered it is not persistent after the setting application completes</p>
0
2010-02-23T14:36:00Z
[ "python", "windows", "testing", "environment-variables" ]
When calling a Python script from a PHP script, temporary file that is created on a console run, is not created via the PHP invocation
923,680
<p>Scenario:</p> <p>I have a php page in which I call a python script. </p> <p>Python script when run on the command line (Linux) shows output on the command line, as well as writes the output to a file.</p> <p>Python script when run through php, doesn't do either.</p> <p>Elaboration:</p> <p>I use a simple system command in PHP to run the python script as:</p> <p>/var/www/html/1.php: system('/usr/python/bin/python3 ../cgi-bin/tabular.py 1');</p> <p>/var/www/cgi-bin/tabular.py --This python file basically parses a data file, uses python's regular expression to search for specific headings and outputs the headings to the stdout, as well as write it to a file.</p> <p>This python script has a few routines in it which get executed, so I put print statements to debug. I noticed only a few initial print statements' output in the PHP page, all the ones from the function that actually does something are not seen.</p> <p>Also, as part of my test, I thought well the py script is in a different folder so let me change it to the /var/www/html folder, no go.</p> <p>I hope I captured the problem statement with sufficient detail and someone is able to reproduce this issue at their end. If I make any progress on this one myself, I'll annotate this question. Thanks everyone.</p> <p>Gaurav</p>
1
2009-05-28T23:21:44Z
923,761
<p>Check that the user the python script is running is has write permissions in CWD. Also, try shell_exec() or passthru() to call the script, rather than system().</p>
0
2009-05-28T23:48:39Z
[ "php", "python", "linux" ]
When calling a Python script from a PHP script, temporary file that is created on a console run, is not created via the PHP invocation
923,680
<p>Scenario:</p> <p>I have a php page in which I call a python script. </p> <p>Python script when run on the command line (Linux) shows output on the command line, as well as writes the output to a file.</p> <p>Python script when run through php, doesn't do either.</p> <p>Elaboration:</p> <p>I use a simple system command in PHP to run the python script as:</p> <p>/var/www/html/1.php: system('/usr/python/bin/python3 ../cgi-bin/tabular.py 1');</p> <p>/var/www/cgi-bin/tabular.py --This python file basically parses a data file, uses python's regular expression to search for specific headings and outputs the headings to the stdout, as well as write it to a file.</p> <p>This python script has a few routines in it which get executed, so I put print statements to debug. I noticed only a few initial print statements' output in the PHP page, all the ones from the function that actually does something are not seen.</p> <p>Also, as part of my test, I thought well the py script is in a different folder so let me change it to the /var/www/html folder, no go.</p> <p>I hope I captured the problem statement with sufficient detail and someone is able to reproduce this issue at their end. If I make any progress on this one myself, I'll annotate this question. Thanks everyone.</p> <p>Gaurav</p>
1
2009-05-28T23:21:44Z
924,481
<p><strong>A permission problem</strong> is most likely the case.</p> <p>If apache is running as <code>apache</code>, then it will not have access to write to a file unless</p> <ol> <li>The file is owned by <code>apache</code></li> <li>The file is in the group <code>apache</code> and group writable</li> <li>The file is world writable</li> </ol> <p>This is a "sticky" problem on a multi-user machine, as different people have access to Apache. </p> <p>Try <code>chmod 666 output.txt</code> on the file and then re-run your test.</p> <p><hr /></p> <p><strong>Considerations:</strong></p> <ol> <li>Have the python script write the output to a database</li> <li>Use PHP's popen functionality to open the process and communicate over pipes</li> <li>Re-write using PHP's regular expressions</li> <li>Write the output file to /tmp and then read the results using PHP as soon as the python script is done.</li> <li>etc...</li> </ol>
1
2009-05-29T05:14:54Z
[ "php", "python", "linux" ]
When calling a Python script from a PHP script, temporary file that is created on a console run, is not created via the PHP invocation
923,680
<p>Scenario:</p> <p>I have a php page in which I call a python script. </p> <p>Python script when run on the command line (Linux) shows output on the command line, as well as writes the output to a file.</p> <p>Python script when run through php, doesn't do either.</p> <p>Elaboration:</p> <p>I use a simple system command in PHP to run the python script as:</p> <p>/var/www/html/1.php: system('/usr/python/bin/python3 ../cgi-bin/tabular.py 1');</p> <p>/var/www/cgi-bin/tabular.py --This python file basically parses a data file, uses python's regular expression to search for specific headings and outputs the headings to the stdout, as well as write it to a file.</p> <p>This python script has a few routines in it which get executed, so I put print statements to debug. I noticed only a few initial print statements' output in the PHP page, all the ones from the function that actually does something are not seen.</p> <p>Also, as part of my test, I thought well the py script is in a different folder so let me change it to the /var/www/html folder, no go.</p> <p>I hope I captured the problem statement with sufficient detail and someone is able to reproduce this issue at their end. If I make any progress on this one myself, I'll annotate this question. Thanks everyone.</p> <p>Gaurav</p>
1
2009-05-28T23:21:44Z
925,872
<p>I bet your py script has some bug which couses it to break when called from inside PHP. Try</p> <pre><code>passthru('/usr/python/bin/python3 ../cgi-bin/tabular.py 1 2&gt;&amp;1'); </code></pre> <p>to investigate (notice <strong>2>&amp;1</strong> which causess stderr to be written to stdout).</p>
2
2009-05-29T13:09:39Z
[ "php", "python", "linux" ]
How to start a process on a remote server, disconnect, then later collect output?
923,691
<p>I am writing automation code in python to test the behavior of a network application. As such, my code needs to be able to start a process/script (say, tcpdump or a python script) on a server in the network, disconnect, run other processes and then later return and shutdown/evaluate the process started earlier. My network is a mix of windows and linux machines and all of the machines have sshd and python running (via Cygwin for the windows machines). </p> <p>I've considered a couple of ideas, namely: - Starting a process and moving it to the background via a trailing ampersand (&amp;) - Using screen in some fashion - Using python threads</p> <p>What else should I be considering? In your experience what have you found to be the best way to accomplish a task like this?</p>
1
2009-05-28T23:25:14Z
923,703
<p>nohup for starters (at least on *nix boxes) - and redirect the output to some log file where you can come back and monitor it of course.</p>
3
2009-05-28T23:28:15Z
[ "python", "testing", "scripting" ]
How to start a process on a remote server, disconnect, then later collect output?
923,691
<p>I am writing automation code in python to test the behavior of a network application. As such, my code needs to be able to start a process/script (say, tcpdump or a python script) on a server in the network, disconnect, run other processes and then later return and shutdown/evaluate the process started earlier. My network is a mix of windows and linux machines and all of the machines have sshd and python running (via Cygwin for the windows machines). </p> <p>I've considered a couple of ideas, namely: - Starting a process and moving it to the background via a trailing ampersand (&amp;) - Using screen in some fashion - Using python threads</p> <p>What else should I be considering? In your experience what have you found to be the best way to accomplish a task like this?</p>
1
2009-05-28T23:25:14Z
923,708
<p>So now that I understand what you really want, I think the best solution would be to create a lite daemon to run whatever process you want. The daemon could then dump the output to a log file so if it takes a shorter amount of time to run than you expect, you can still get the output. This would be more reliable than fiddling with screen. It should be pointed out however, that this could potentially be a security risk. If this is a task you run every N time periods, cron would work much better.</p> <p><strong>Original Answer</strong></p> <p><a href="http://www.gnu.org/software/screen/" rel="nofollow">GNU Screen</a> is a good way to handle this.</p> <p><strong>Edit:</strong> After re-reading your question, I think I misunderstood you. Are you looking to run a python script on the local machine that will connect to a remote one and run some arbitrary process and then be able to connect to the remote machine again and examine a log or something?</p>
3
2009-05-28T23:29:23Z
[ "python", "testing", "scripting" ]
How to start a process on a remote server, disconnect, then later collect output?
923,691
<p>I am writing automation code in python to test the behavior of a network application. As such, my code needs to be able to start a process/script (say, tcpdump or a python script) on a server in the network, disconnect, run other processes and then later return and shutdown/evaluate the process started earlier. My network is a mix of windows and linux machines and all of the machines have sshd and python running (via Cygwin for the windows machines). </p> <p>I've considered a couple of ideas, namely: - Starting a process and moving it to the background via a trailing ampersand (&amp;) - Using screen in some fashion - Using python threads</p> <p>What else should I be considering? In your experience what have you found to be the best way to accomplish a task like this?</p>
1
2009-05-28T23:25:14Z
923,719
<p>As @Gandalf mentions, you'll need <code>nohup</code> in addition to the backgrounding &amp;, or the process will be SIGKILLed when the login session terminates. If you redirect your output to a log file, you'll be able to look at it later easily (and not have to install screen on all your machines).</p>
0
2009-05-28T23:31:34Z
[ "python", "testing", "scripting" ]
How to start a process on a remote server, disconnect, then later collect output?
923,691
<p>I am writing automation code in python to test the behavior of a network application. As such, my code needs to be able to start a process/script (say, tcpdump or a python script) on a server in the network, disconnect, run other processes and then later return and shutdown/evaluate the process started earlier. My network is a mix of windows and linux machines and all of the machines have sshd and python running (via Cygwin for the windows machines). </p> <p>I've considered a couple of ideas, namely: - Starting a process and moving it to the background via a trailing ampersand (&amp;) - Using screen in some fashion - Using python threads</p> <p>What else should I be considering? In your experience what have you found to be the best way to accomplish a task like this?</p>
1
2009-05-28T23:25:14Z
923,720
<p>Most commercial products install an "Agent" on the remote machines.</p> <p>In the linux world, you have numerous such agents. rexec and rlogin and rsh all jump to mind.</p> <p>These are all clients that communication with daemons running on the remote hosts.</p> <p>If you don't want to use these agents, you can read about them and reinvent these wheels in pure Python. Essentially, the client (rexec for example) communicates with the server (rexecd) to send work requests.</p>
0
2009-05-28T23:32:11Z
[ "python", "testing", "scripting" ]
How to start a process on a remote server, disconnect, then later collect output?
923,691
<p>I am writing automation code in python to test the behavior of a network application. As such, my code needs to be able to start a process/script (say, tcpdump or a python script) on a server in the network, disconnect, run other processes and then later return and shutdown/evaluate the process started earlier. My network is a mix of windows and linux machines and all of the machines have sshd and python running (via Cygwin for the windows machines). </p> <p>I've considered a couple of ideas, namely: - Starting a process and moving it to the background via a trailing ampersand (&amp;) - Using screen in some fashion - Using python threads</p> <p>What else should I be considering? In your experience what have you found to be the best way to accomplish a task like this?</p>
1
2009-05-28T23:25:14Z
923,726
<p>For a quick, lightweight solution you can't beat <a href="http://www.gnu.org/software/screen/" rel="nofollow">screen</a>. If you want to automate things completely it makes sense to set up the process to <strong>run as a daemon</strong> and write to the system log using <code>syslog</code>. Your system may have a <code>start-stop-daemon</code> script, and for C code it may also have a <code>daemon(3)</code> call in the C library.</p>
1
2009-05-28T23:34:40Z
[ "python", "testing", "scripting" ]
How to start a process on a remote server, disconnect, then later collect output?
923,691
<p>I am writing automation code in python to test the behavior of a network application. As such, my code needs to be able to start a process/script (say, tcpdump or a python script) on a server in the network, disconnect, run other processes and then later return and shutdown/evaluate the process started earlier. My network is a mix of windows and linux machines and all of the machines have sshd and python running (via Cygwin for the windows machines). </p> <p>I've considered a couple of ideas, namely: - Starting a process and moving it to the background via a trailing ampersand (&amp;) - Using screen in some fashion - Using python threads</p> <p>What else should I be considering? In your experience what have you found to be the best way to accomplish a task like this?</p>
1
2009-05-28T23:25:14Z
923,729
<p>If you want a script to continue after you leave, you could call it through "nohup" (man nohup). You could also put code in the script you call to have it daemonize itself... it forks, makes the child into a daemon, and then exits. A quick search turned up: <a href="http://code.activestate.com/recipes/278731/" rel="nofollow">http://code.activestate.com/recipes/278731/</a></p>
1
2009-05-28T23:35:58Z
[ "python", "testing", "scripting" ]
How to start a process on a remote server, disconnect, then later collect output?
923,691
<p>I am writing automation code in python to test the behavior of a network application. As such, my code needs to be able to start a process/script (say, tcpdump or a python script) on a server in the network, disconnect, run other processes and then later return and shutdown/evaluate the process started earlier. My network is a mix of windows and linux machines and all of the machines have sshd and python running (via Cygwin for the windows machines). </p> <p>I've considered a couple of ideas, namely: - Starting a process and moving it to the background via a trailing ampersand (&amp;) - Using screen in some fashion - Using python threads</p> <p>What else should I be considering? In your experience what have you found to be the best way to accomplish a task like this?</p>
1
2009-05-28T23:25:14Z
926,177
<p>Instead of screen, since it's for a single process, I would suggest its lightweight sibling, <a href="http://dtach.sourceforge.net/" rel="nofollow">dtach</a>.</p> <p>For a fairly complete recipe of dæmonizing a process in Python, see the <a href="http://code.activestate.com/recipes/278731/" rel="nofollow">Creating a daemon the Python way</a> from the ActiveState cookbook.</p>
0
2009-05-29T14:11:33Z
[ "python", "testing", "scripting" ]
How to start a process on a remote server, disconnect, then later collect output?
923,691
<p>I am writing automation code in python to test the behavior of a network application. As such, my code needs to be able to start a process/script (say, tcpdump or a python script) on a server in the network, disconnect, run other processes and then later return and shutdown/evaluate the process started earlier. My network is a mix of windows and linux machines and all of the machines have sshd and python running (via Cygwin for the windows machines). </p> <p>I've considered a couple of ideas, namely: - Starting a process and moving it to the background via a trailing ampersand (&amp;) - Using screen in some fashion - Using python threads</p> <p>What else should I be considering? In your experience what have you found to be the best way to accomplish a task like this?</p>
1
2009-05-28T23:25:14Z
20,889,031
<p>If you are using python to run the automation... I would attempt to automate everything using paramiko. It's a versatile ssh library for python. Instead of going back to the output, you could collect multiple lines of output live and then disconnect when you no longer need the process and let ssh do the killing for you. </p>
0
2014-01-02T18:09:41Z
[ "python", "testing", "scripting" ]
Python taskbar applet
923,701
<p>I want to code up a panel that will be used both in Linux and Windows. Ideally it will be written in Python using PyQT.</p> <p>What I've found so far is the QSystemTrayIcon widget, and while that is quite useful, that's not quite what I'm looking for. That widget lets you attach a menu to the left and right clicks of an icon on the system tray and then you can have a dialog open in certain situations.</p> <p>I'm looking for something that will let me write up something like the tools that Gnome lets you add to the taskbar (they call them panels). Such as a weather feed, or processor usage, right on the taskbar. And also not in the system tray area.</p> <p>I'm writing more of a tool than something reflects a status.</p> <p>I know that I could write this natively in both OSes using GTK and its ilk, but anyway to write in PyQT or WxWidget so I don't have to deal with dependancy issues?</p>
4
2009-05-28T23:28:09Z
923,757
<p>Widgets inside the GNOME panel are called applets, and to my knowledge it's not possible to write them with anything but Gtk, since you have to use the respective GNOME library libpanel-applet (in either C, C++ or Python). </p> <p>System tray icons are different, because they only allow icons to be displayed inside the notification area, since Windows only supports icons there. </p> <p>The panel mechanism on Windows (Vista, XP does only have the notification area) is quite different, I would assume. Unless somebody already wrote a library that abstracts the differences of the GNOME panel and the Vista side bar, you would have to do that yourself. </p>
5
2009-05-28T23:44:38Z
[ "python", "qt4", "pyqt" ]
Python taskbar applet
923,701
<p>I want to code up a panel that will be used both in Linux and Windows. Ideally it will be written in Python using PyQT.</p> <p>What I've found so far is the QSystemTrayIcon widget, and while that is quite useful, that's not quite what I'm looking for. That widget lets you attach a menu to the left and right clicks of an icon on the system tray and then you can have a dialog open in certain situations.</p> <p>I'm looking for something that will let me write up something like the tools that Gnome lets you add to the taskbar (they call them panels). Such as a weather feed, or processor usage, right on the taskbar. And also not in the system tray area.</p> <p>I'm writing more of a tool than something reflects a status.</p> <p>I know that I could write this natively in both OSes using GTK and its ilk, but anyway to write in PyQT or WxWidget so I don't have to deal with dependancy issues?</p>
4
2009-05-28T23:28:09Z
924,771
<p>Sounds like you are looking for <a href="http://www.youtube.com/watch?v=DzraMSNvhQI" rel="nofollow">Plasmoids</a>, which can be integrated into the task bar. There are a Plasmoid tutorials in <a href="http://techbase.kde.org/Development/Tutorials/Plasma/GettingStarted" rel="nofollow">C++</a> and <a href="http://techbase.kde.org/Development/Tutorials/Plasma/PythonPlasmoid" rel="nofollow">Python</a>.</p> <p>I can't say, however, whether it will work with <a href="http://windows.kde.org/" rel="nofollow">KDE on Windows</a>.</p>
-1
2009-05-29T07:16:27Z
[ "python", "qt4", "pyqt" ]
How do I call template defs with names only known at runtime in the Python template language Mako?
923,837
<p>I am trying to find a way of calling def templates determined by the data available in the context.</p> <p><strong>Edit:</strong> A simpler instance of the same question. </p> <p>It is possible to emit the value of an object in the context:</p> <pre><code># in python ctx = Context(buffer, website='stackoverflow.com') # in mako &lt;%def name="body()"&gt; I visit ${website} all the time. &lt;/%def&gt; </code></pre> <p>Produces:</p> <pre><code>I visit stackoverflow.com all the time. </code></pre> <p>I would like to allow a customization of the output, based upon the data.</p> <pre><code># in python ctx = Context(buffer, website='stackoverflow.com', format='text') # in mako &lt;%def name="body()"&gt; I visit ${(format + '_link')(website)} all the time. &lt;-- Made up syntax. &lt;/%def&gt; &lt;%def name='html_link(w)'&gt; &lt;a href='http://${w}'&gt;${w}&lt;/a&gt; &lt;/%def&gt; &lt;%def name='text_link(w)'&gt; ${w} &lt;/%def&gt; </code></pre> <p>Changing the <code>format</code> attribute in the context should change the output from</p> <pre><code>I visit stackoverflow.com all the time. </code></pre> <p>to </p> <pre><code>I visit &lt;a href='http://stackoverflow.com'&gt;stackoverflow.com&lt;/a&gt; all the time. </code></pre> <p>The <strong>made up syntax</strong> I have used in the <code>body</code> <code>def</code> is obviously wrong. What would I need to dynamically specify a template, and then call it?</p>
0
2009-05-29T00:10:25Z
924,049
<p>How about if you first generate the template (from another template :), and then run that with your data?</p>
0
2009-05-29T01:48:31Z
[ "python", "templates", "mako" ]
How do I call template defs with names only known at runtime in the Python template language Mako?
923,837
<p>I am trying to find a way of calling def templates determined by the data available in the context.</p> <p><strong>Edit:</strong> A simpler instance of the same question. </p> <p>It is possible to emit the value of an object in the context:</p> <pre><code># in python ctx = Context(buffer, website='stackoverflow.com') # in mako &lt;%def name="body()"&gt; I visit ${website} all the time. &lt;/%def&gt; </code></pre> <p>Produces:</p> <pre><code>I visit stackoverflow.com all the time. </code></pre> <p>I would like to allow a customization of the output, based upon the data.</p> <pre><code># in python ctx = Context(buffer, website='stackoverflow.com', format='text') # in mako &lt;%def name="body()"&gt; I visit ${(format + '_link')(website)} all the time. &lt;-- Made up syntax. &lt;/%def&gt; &lt;%def name='html_link(w)'&gt; &lt;a href='http://${w}'&gt;${w}&lt;/a&gt; &lt;/%def&gt; &lt;%def name='text_link(w)'&gt; ${w} &lt;/%def&gt; </code></pre> <p>Changing the <code>format</code> attribute in the context should change the output from</p> <pre><code>I visit stackoverflow.com all the time. </code></pre> <p>to </p> <pre><code>I visit &lt;a href='http://stackoverflow.com'&gt;stackoverflow.com&lt;/a&gt; all the time. </code></pre> <p>The <strong>made up syntax</strong> I have used in the <code>body</code> <code>def</code> is obviously wrong. What would I need to dynamically specify a template, and then call it?</p>
0
2009-05-29T00:10:25Z
930,404
<p>Takes some playing with mako's <code>local</code> namespace, but here's a working example:</p> <pre><code>from mako.template import Template from mako.runtime import Context from StringIO import StringIO mytemplate = Template(""" &lt;%def name='html_link(w)'&gt; &lt;a href='http://${w}'&gt;${w}&lt;/a&gt; &lt;/%def&gt; &lt;%def name='text_link(w)'&gt; ${w} &lt;/%def&gt; &lt;%def name="body()"&gt; I visit ${getattr(local, format + '_link')(website)} all the time. &lt;/%def&gt; """) buf = StringIO() ctx = Context(buf, website='stackoverflow.com', format='html') mytemplate.render_context(ctx) print buf.getvalue() </code></pre> <p>As desired, this emits:</p> <pre><code>I visit &lt;a href='http://stackoverflow.com'&gt;stackoverflow.com&lt;/a&gt; all the time. </code></pre>
1
2009-05-30T19:33:33Z
[ "python", "templates", "mako" ]
Python RegEx - Getting multiple pieces of information out of a string
924,127
<p>I'm trying to use python to parse a log file and match 4 pieces of information in one regex. (epoch time, SERVICE NOTIFICATION, hostname and CRITICAL) I can't seem to get this to work. So Far I've been able to only match two of the four. Is it possible to do this? Below is an example of a string from the log file and the code I've gotten to work thus far. Any help would make me a happy noob.</p> <p>[1242248375] SERVICE ALERT: myhostname.com;DNS: Recursive;CRITICAL;SOFT;1;CRITICAL - Plugin timed out while executing system call</p> <pre><code>hostname = options.hostname n = open('/var/tmp/nagios.log', 'r') n.readline() l = [str(x) for x in n] for line in l: match = re.match (r'^\[(\d+)\] SERVICE NOTIFICATION: ', line) if match: timestamp = int(match.groups()[0]) print timestamp </code></pre>
2
2009-05-29T02:18:56Z
924,137
<p>You can use <code>|</code> to match any one of various possible things, and <code>re.findall</code> to get all non-overlapping matches to some RE.</p>
5
2009-05-29T02:25:19Z
[ "python", "regex" ]
Python RegEx - Getting multiple pieces of information out of a string
924,127
<p>I'm trying to use python to parse a log file and match 4 pieces of information in one regex. (epoch time, SERVICE NOTIFICATION, hostname and CRITICAL) I can't seem to get this to work. So Far I've been able to only match two of the four. Is it possible to do this? Below is an example of a string from the log file and the code I've gotten to work thus far. Any help would make me a happy noob.</p> <p>[1242248375] SERVICE ALERT: myhostname.com;DNS: Recursive;CRITICAL;SOFT;1;CRITICAL - Plugin timed out while executing system call</p> <pre><code>hostname = options.hostname n = open('/var/tmp/nagios.log', 'r') n.readline() l = [str(x) for x in n] for line in l: match = re.match (r'^\[(\d+)\] SERVICE NOTIFICATION: ', line) if match: timestamp = int(match.groups()[0]) print timestamp </code></pre>
2
2009-05-29T02:18:56Z
924,146
<p>Could it be as simple as "SERVICE NOTIFICATION" in your pattern doesn't match "SERVICE ALERT" in your example?</p>
0
2009-05-29T02:29:27Z
[ "python", "regex" ]
Python RegEx - Getting multiple pieces of information out of a string
924,127
<p>I'm trying to use python to parse a log file and match 4 pieces of information in one regex. (epoch time, SERVICE NOTIFICATION, hostname and CRITICAL) I can't seem to get this to work. So Far I've been able to only match two of the four. Is it possible to do this? Below is an example of a string from the log file and the code I've gotten to work thus far. Any help would make me a happy noob.</p> <p>[1242248375] SERVICE ALERT: myhostname.com;DNS: Recursive;CRITICAL;SOFT;1;CRITICAL - Plugin timed out while executing system call</p> <pre><code>hostname = options.hostname n = open('/var/tmp/nagios.log', 'r') n.readline() l = [str(x) for x in n] for line in l: match = re.match (r'^\[(\d+)\] SERVICE NOTIFICATION: ', line) if match: timestamp = int(match.groups()[0]) print timestamp </code></pre>
2
2009-05-29T02:18:56Z
924,166
<p>The question is a bit confusing. But you don't need to do <em>everything</em> with regular expressions, there are some good plain old string functions you might want to try, like 'split'.</p> <p>This version will also refrain from loading the entire file in memory at once, and it will close the file even when an exception is thrown. </p> <pre><code>regexp = re.compile(r'\[(\d+)\] SERVICE NOTIFICATION: (.+)') with open('var/tmp/nagios.log', 'r') as file: for line in file: fields = line.split(';') match = regexp.match(fields[0]) if match: timestamp = int(match.group(1)) hostname = match.group(2) </code></pre>
1
2009-05-29T02:33:57Z
[ "python", "regex" ]
Python RegEx - Getting multiple pieces of information out of a string
924,127
<p>I'm trying to use python to parse a log file and match 4 pieces of information in one regex. (epoch time, SERVICE NOTIFICATION, hostname and CRITICAL) I can't seem to get this to work. So Far I've been able to only match two of the four. Is it possible to do this? Below is an example of a string from the log file and the code I've gotten to work thus far. Any help would make me a happy noob.</p> <p>[1242248375] SERVICE ALERT: myhostname.com;DNS: Recursive;CRITICAL;SOFT;1;CRITICAL - Plugin timed out while executing system call</p> <pre><code>hostname = options.hostname n = open('/var/tmp/nagios.log', 'r') n.readline() l = [str(x) for x in n] for line in l: match = re.match (r'^\[(\d+)\] SERVICE NOTIFICATION: ', line) if match: timestamp = int(match.groups()[0]) print timestamp </code></pre>
2
2009-05-29T02:18:56Z
924,173
<p>If you are looking to split out those particular parts of the line then.</p> <p>Something along the lines of:</p> <pre><code>match = re.match(r'^\[(\d+)\] (.*?): (.*?);.*?;(.*?);',line) </code></pre> <p>Should give each of those parts in their respective index in groups.</p>
1
2009-05-29T02:38:31Z
[ "python", "regex" ]
Python RegEx - Getting multiple pieces of information out of a string
924,127
<p>I'm trying to use python to parse a log file and match 4 pieces of information in one regex. (epoch time, SERVICE NOTIFICATION, hostname and CRITICAL) I can't seem to get this to work. So Far I've been able to only match two of the four. Is it possible to do this? Below is an example of a string from the log file and the code I've gotten to work thus far. Any help would make me a happy noob.</p> <p>[1242248375] SERVICE ALERT: myhostname.com;DNS: Recursive;CRITICAL;SOFT;1;CRITICAL - Plugin timed out while executing system call</p> <pre><code>hostname = options.hostname n = open('/var/tmp/nagios.log', 'r') n.readline() l = [str(x) for x in n] for line in l: match = re.match (r'^\[(\d+)\] SERVICE NOTIFICATION: ', line) if match: timestamp = int(match.groups()[0]) print timestamp </code></pre>
2
2009-05-29T02:18:56Z
924,205
<p>You can use more than one group at a time, e.g.:</p> <pre><code>import re logstring = '[1242248375] SERVICE ALERT: myhostname.com;DNS: Recursive;CRITICAL;SOFT;1;CRITICAL - Plugin timed out while executing system call' exp = re.compile('^\[(\d+)\] ([A-Z ]+): ([A-Za-z0-9.\-]+);[^;]+;([A-Z]+);') m = exp.search(logstring) for s in m.groups(): print s </code></pre>
2
2009-05-29T02:55:00Z
[ "python", "regex" ]
Capturing Implicit Signals of Interest in Django
924,530
<p>To set the background: I'm interested in:</p> <ul> <li>Capturing implicit signals of interest in books as users browse around a site. The site is written in django (python) using mysql, memcached, ngnix, and apache</li> </ul> <p>Let's say, for instance, my site sells books. As a user browses around my site I'd like to keep track of which books they've viewed, and how many times they've viewed them.</p> <p>Not that I'd store the data this way, but ideally I could have on-the-fly access to a structure like:</p> <pre><code>{user_id : {book_id: number_of_views, book_id_2: number_of_views}} </code></pre> <p>I realize there are a few approaches here:</p> <ul> <li>Some flat-file log</li> <li>Writing an object to a database every time</li> <li>Writing to an object in memcached</li> </ul> <p>I don't really know the performance implications, but I'd rather not be writing to a database on every single page view, and the lag writing to a log and computing the structure later seems not quick enough to give good recommendations on-the-fly as you use the site, and the memcached appraoch seems fine, but there's a cost in keeping this obj in memory: you might lose it, and it never gets written somewhere 'permanent'.</p> <p>What approach would you suggest? (doesn't have to be one of the above) Thanks!</p>
0
2009-05-29T05:34:24Z
924,611
<p><em>What approach would you suggest? (doesn't have to be one of the above) Thanks!</em></p> <p>hmmmm ...this like been in a four walled room with only one door and saying i want to get out of room but not through the only door...</p> <p>There was an article i was reading sometime back (can't get the link now) that says memcache can handle huge (facebook uses it) sets of data in memory with very little degradation in performance...my advice is you will need to explore more on memcache, i think it will do the trick.</p>
1
2009-05-29T06:08:49Z
[ "python", "mysql", "django", "collaborative-filtering" ]
Capturing Implicit Signals of Interest in Django
924,530
<p>To set the background: I'm interested in:</p> <ul> <li>Capturing implicit signals of interest in books as users browse around a site. The site is written in django (python) using mysql, memcached, ngnix, and apache</li> </ul> <p>Let's say, for instance, my site sells books. As a user browses around my site I'd like to keep track of which books they've viewed, and how many times they've viewed them.</p> <p>Not that I'd store the data this way, but ideally I could have on-the-fly access to a structure like:</p> <pre><code>{user_id : {book_id: number_of_views, book_id_2: number_of_views}} </code></pre> <p>I realize there are a few approaches here:</p> <ul> <li>Some flat-file log</li> <li>Writing an object to a database every time</li> <li>Writing to an object in memcached</li> </ul> <p>I don't really know the performance implications, but I'd rather not be writing to a database on every single page view, and the lag writing to a log and computing the structure later seems not quick enough to give good recommendations on-the-fly as you use the site, and the memcached appraoch seems fine, but there's a cost in keeping this obj in memory: you might lose it, and it never gets written somewhere 'permanent'.</p> <p>What approach would you suggest? (doesn't have to be one of the above) Thanks!</p>
0
2009-05-29T05:34:24Z
924,649
<p>Either a document datastore (mongo/couchdb), or a persistent key value store (tokyodb, memcachedb etc) may be explored. </p> <p>No definite recommendations from me as the final solution depends on multiple factors - load, your willingness to learn/deploy a new technology, size of the data...</p>
1
2009-05-29T06:22:03Z
[ "python", "mysql", "django", "collaborative-filtering" ]
Capturing Implicit Signals of Interest in Django
924,530
<p>To set the background: I'm interested in:</p> <ul> <li>Capturing implicit signals of interest in books as users browse around a site. The site is written in django (python) using mysql, memcached, ngnix, and apache</li> </ul> <p>Let's say, for instance, my site sells books. As a user browses around my site I'd like to keep track of which books they've viewed, and how many times they've viewed them.</p> <p>Not that I'd store the data this way, but ideally I could have on-the-fly access to a structure like:</p> <pre><code>{user_id : {book_id: number_of_views, book_id_2: number_of_views}} </code></pre> <p>I realize there are a few approaches here:</p> <ul> <li>Some flat-file log</li> <li>Writing an object to a database every time</li> <li>Writing to an object in memcached</li> </ul> <p>I don't really know the performance implications, but I'd rather not be writing to a database on every single page view, and the lag writing to a log and computing the structure later seems not quick enough to give good recommendations on-the-fly as you use the site, and the memcached appraoch seems fine, but there's a cost in keeping this obj in memory: you might lose it, and it never gets written somewhere 'permanent'.</p> <p>What approach would you suggest? (doesn't have to be one of the above) Thanks!</p>
0
2009-05-29T05:34:24Z
924,944
<p>Seems to me that one approach could be to use memcached to keep the counter, but have a cron running regularly to store the value from memcached to the db or disk. That way you'd get all the performance of memcached, but in the case of a crash you wouldn't lose more than a couple of minutes' data.</p>
0
2009-05-29T08:20:00Z
[ "python", "mysql", "django", "collaborative-filtering" ]
Capturing Implicit Signals of Interest in Django
924,530
<p>To set the background: I'm interested in:</p> <ul> <li>Capturing implicit signals of interest in books as users browse around a site. The site is written in django (python) using mysql, memcached, ngnix, and apache</li> </ul> <p>Let's say, for instance, my site sells books. As a user browses around my site I'd like to keep track of which books they've viewed, and how many times they've viewed them.</p> <p>Not that I'd store the data this way, but ideally I could have on-the-fly access to a structure like:</p> <pre><code>{user_id : {book_id: number_of_views, book_id_2: number_of_views}} </code></pre> <p>I realize there are a few approaches here:</p> <ul> <li>Some flat-file log</li> <li>Writing an object to a database every time</li> <li>Writing to an object in memcached</li> </ul> <p>I don't really know the performance implications, but I'd rather not be writing to a database on every single page view, and the lag writing to a log and computing the structure later seems not quick enough to give good recommendations on-the-fly as you use the site, and the memcached appraoch seems fine, but there's a cost in keeping this obj in memory: you might lose it, and it never gets written somewhere 'permanent'.</p> <p>What approach would you suggest? (doesn't have to be one of the above) Thanks!</p>
0
2009-05-29T05:34:24Z
925,420
<p>If this data is not an unimportant statistic that might or might not be available I'd suggest taking the simple approach and using a model. It will surely hit the database everytime. </p> <p>Unless you are absolutely positively sure these queries <strong>are</strong> actually degrading overall experience there is no need to worry about it. Even if you optimize this one, there's a good chance other <em>unexpected</em> queries are wasting more CPU time. I assume you wouldn't be asking this question if you were testing all other queries. So why risk premature optimization on this one?</p> <p>An advantage of the model approach would be <em>having an API in place</em>. When you have tested and decided to optimize you can keep this API and change the underlying model with something else (which will most probably be more complex than a model).</p> <p>I'd definitely go with a model first and see how it performs. (and also how other parts of the project perform)</p>
3
2009-05-29T10:50:57Z
[ "python", "mysql", "django", "collaborative-filtering" ]
Best way to retrieve variable values from a text file - Python - Json
924,700
<p>Referring on <a href="http://stackoverflow.com/questions/868112/loading-files-into-variables-in-python">this question</a>, I have a similar -but not the same- problem..</p> <p>On my way, I'll have some text file, structured like:</p> <pre><code>var_a: 'home' var_b: 'car' var_c: 15.5 </code></pre> <p>And I need that python read the file and then create a variable named var_a with value 'home', and so on.</p> <p>Example:</p> <pre><code>#python stuff over here getVarFromFile(filename) #this is the function that im looking for print var_b #output: car, as string print var_c #output 15.5, as number. </code></pre> <p>Is this possible, I mean, even keep the var type?</p> <p>Notice that I have the full freedom to the text file structure, I can use the format I like if the one I proposed isn't the best.</p> <p><strong>EDIT</strong>: the ConfigParser can be a solution, but I don't like it so much, because in my script I'll have then to refer to the variables in the file with</p> <pre><code>config.get("set", "var_name") </code></pre> <p>But what I'll love is to refer to the variable directly, as I declared it in the python script...</p> <p>There is a way to import the file as a python dictionary?</p> <p>Oh, last thing, keep in mind that I don't know exactly how many variables would I have in the text file.</p> <p><strong>Edit 2</strong>: I'm very interested at stephan's JSON solution, because in that way the text file could be read simply with others languages (PHP, then via AJAX JavaScript, for example), but I fail in something while acting that solution:</p> <pre><code>#for the example, i dont load the file but create a var with the supposed file content file_content = "'var_a': 4, 'var_b': 'a string'" mydict = dict(file_content) #Error: ValueError: dictionary update sequence element #0 has length 1; 2 is required file_content_2 = "{'var_a': 4, 'var_b': 'a string'}" mydict_2 = dict(json.dump(file_content_2, True)) #Error: #Traceback (most recent call last): #File "&lt;pyshell#5&gt;", line 1, in &lt;module&gt; #mydict_2 = dict(json.dump(file_content_2, True)) #File "C:\Python26\lib\json\__init__.py", line 181, in dump #fp.write(chunk) #AttributeError: 'bool' object has no attribute 'write' </code></pre> <p>In what kind of issues can I fall with the JSON format? And, how can I read a JSON array in a text file, and transform it in a python dict?</p> <p>P.S: I don't like the solution using .py files; I'll prefer .txt, .inc, .whatever is not restrictive to one language.</p>
20
2009-05-29T06:48:30Z
924,719
<p>You can <em>treat</em> your text file as a python module and load it dynamically using <a href="https://docs.python.org/2/library/imp.html#imp.load_source" rel="nofollow"><code>imp.load_source</code></a>:</p> <pre><code>import imp imp.load_source( name, pathname[, file]) </code></pre> <p>Example:</p> <pre><code>// mydata.txt var1 = 'hi' var2 = 'how are you?' var3 = { 1:'elem1', 2:'elem2' } //... // In your script file def getVarFromFile(filename): import imp f = open(filename) global data data = imp.load_source('data', '', f) f.close() # path to "config" file getVarFromFile('c:/mydata.txt') print data.var1 print data.var2 print data.var3 ... </code></pre>
13
2009-05-29T06:56:12Z
[ "python", "json", "variables", "text-files" ]
Best way to retrieve variable values from a text file - Python - Json
924,700
<p>Referring on <a href="http://stackoverflow.com/questions/868112/loading-files-into-variables-in-python">this question</a>, I have a similar -but not the same- problem..</p> <p>On my way, I'll have some text file, structured like:</p> <pre><code>var_a: 'home' var_b: 'car' var_c: 15.5 </code></pre> <p>And I need that python read the file and then create a variable named var_a with value 'home', and so on.</p> <p>Example:</p> <pre><code>#python stuff over here getVarFromFile(filename) #this is the function that im looking for print var_b #output: car, as string print var_c #output 15.5, as number. </code></pre> <p>Is this possible, I mean, even keep the var type?</p> <p>Notice that I have the full freedom to the text file structure, I can use the format I like if the one I proposed isn't the best.</p> <p><strong>EDIT</strong>: the ConfigParser can be a solution, but I don't like it so much, because in my script I'll have then to refer to the variables in the file with</p> <pre><code>config.get("set", "var_name") </code></pre> <p>But what I'll love is to refer to the variable directly, as I declared it in the python script...</p> <p>There is a way to import the file as a python dictionary?</p> <p>Oh, last thing, keep in mind that I don't know exactly how many variables would I have in the text file.</p> <p><strong>Edit 2</strong>: I'm very interested at stephan's JSON solution, because in that way the text file could be read simply with others languages (PHP, then via AJAX JavaScript, for example), but I fail in something while acting that solution:</p> <pre><code>#for the example, i dont load the file but create a var with the supposed file content file_content = "'var_a': 4, 'var_b': 'a string'" mydict = dict(file_content) #Error: ValueError: dictionary update sequence element #0 has length 1; 2 is required file_content_2 = "{'var_a': 4, 'var_b': 'a string'}" mydict_2 = dict(json.dump(file_content_2, True)) #Error: #Traceback (most recent call last): #File "&lt;pyshell#5&gt;", line 1, in &lt;module&gt; #mydict_2 = dict(json.dump(file_content_2, True)) #File "C:\Python26\lib\json\__init__.py", line 181, in dump #fp.write(chunk) #AttributeError: 'bool' object has no attribute 'write' </code></pre> <p>In what kind of issues can I fall with the JSON format? And, how can I read a JSON array in a text file, and transform it in a python dict?</p> <p>P.S: I don't like the solution using .py files; I'll prefer .txt, .inc, .whatever is not restrictive to one language.</p>
20
2009-05-29T06:48:30Z
924,723
<p>Use ConfigParser.</p> <p>Your config:</p> <pre><code>[myvars] var_a: 'home' var_b: 'car' var_c: 15.5 </code></pre> <p>Your python code:</p> <pre><code>import ConfigParser config = ConfigParser.ConfigParser() config.read("config.ini") var_a = config.get("myvars", "var_a") var_b = config.get("myvars", "var_b") var_c = config.get("myvars", "var_c") </code></pre>
18
2009-05-29T06:57:58Z
[ "python", "json", "variables", "text-files" ]
Best way to retrieve variable values from a text file - Python - Json
924,700
<p>Referring on <a href="http://stackoverflow.com/questions/868112/loading-files-into-variables-in-python">this question</a>, I have a similar -but not the same- problem..</p> <p>On my way, I'll have some text file, structured like:</p> <pre><code>var_a: 'home' var_b: 'car' var_c: 15.5 </code></pre> <p>And I need that python read the file and then create a variable named var_a with value 'home', and so on.</p> <p>Example:</p> <pre><code>#python stuff over here getVarFromFile(filename) #this is the function that im looking for print var_b #output: car, as string print var_c #output 15.5, as number. </code></pre> <p>Is this possible, I mean, even keep the var type?</p> <p>Notice that I have the full freedom to the text file structure, I can use the format I like if the one I proposed isn't the best.</p> <p><strong>EDIT</strong>: the ConfigParser can be a solution, but I don't like it so much, because in my script I'll have then to refer to the variables in the file with</p> <pre><code>config.get("set", "var_name") </code></pre> <p>But what I'll love is to refer to the variable directly, as I declared it in the python script...</p> <p>There is a way to import the file as a python dictionary?</p> <p>Oh, last thing, keep in mind that I don't know exactly how many variables would I have in the text file.</p> <p><strong>Edit 2</strong>: I'm very interested at stephan's JSON solution, because in that way the text file could be read simply with others languages (PHP, then via AJAX JavaScript, for example), but I fail in something while acting that solution:</p> <pre><code>#for the example, i dont load the file but create a var with the supposed file content file_content = "'var_a': 4, 'var_b': 'a string'" mydict = dict(file_content) #Error: ValueError: dictionary update sequence element #0 has length 1; 2 is required file_content_2 = "{'var_a': 4, 'var_b': 'a string'}" mydict_2 = dict(json.dump(file_content_2, True)) #Error: #Traceback (most recent call last): #File "&lt;pyshell#5&gt;", line 1, in &lt;module&gt; #mydict_2 = dict(json.dump(file_content_2, True)) #File "C:\Python26\lib\json\__init__.py", line 181, in dump #fp.write(chunk) #AttributeError: 'bool' object has no attribute 'write' </code></pre> <p>In what kind of issues can I fall with the JSON format? And, how can I read a JSON array in a text file, and transform it in a python dict?</p> <p>P.S: I don't like the solution using .py files; I'll prefer .txt, .inc, .whatever is not restrictive to one language.</p>
20
2009-05-29T06:48:30Z
924,835
<p>Load your file with <a href="http://docs.python.org/library/json.html" rel="nofollow">JSON</a> or <a href="http://pyyaml.org/wiki/PyYAML" rel="nofollow">PyYAML</a> into a dictionary <code>the_dict</code> (see doc for JSON or PyYAML for this step, both can store data type) and add the dictionary to your globals dictionary, e.g. using <code>globals().update(the_dict)</code>.</p> <p>If you want it in a local dictionary instead (e.g. inside a function), you can do it like this:</p> <pre><code>for (n, v) in the_dict.items(): exec('%s=%s' % (n, repr(v))) </code></pre> <p>as long as it is safe to use <code>exec</code>. If not, you can use the dictionary directly.</p>
11
2009-05-29T07:42:27Z
[ "python", "json", "variables", "text-files" ]
Best way to retrieve variable values from a text file - Python - Json
924,700
<p>Referring on <a href="http://stackoverflow.com/questions/868112/loading-files-into-variables-in-python">this question</a>, I have a similar -but not the same- problem..</p> <p>On my way, I'll have some text file, structured like:</p> <pre><code>var_a: 'home' var_b: 'car' var_c: 15.5 </code></pre> <p>And I need that python read the file and then create a variable named var_a with value 'home', and so on.</p> <p>Example:</p> <pre><code>#python stuff over here getVarFromFile(filename) #this is the function that im looking for print var_b #output: car, as string print var_c #output 15.5, as number. </code></pre> <p>Is this possible, I mean, even keep the var type?</p> <p>Notice that I have the full freedom to the text file structure, I can use the format I like if the one I proposed isn't the best.</p> <p><strong>EDIT</strong>: the ConfigParser can be a solution, but I don't like it so much, because in my script I'll have then to refer to the variables in the file with</p> <pre><code>config.get("set", "var_name") </code></pre> <p>But what I'll love is to refer to the variable directly, as I declared it in the python script...</p> <p>There is a way to import the file as a python dictionary?</p> <p>Oh, last thing, keep in mind that I don't know exactly how many variables would I have in the text file.</p> <p><strong>Edit 2</strong>: I'm very interested at stephan's JSON solution, because in that way the text file could be read simply with others languages (PHP, then via AJAX JavaScript, for example), but I fail in something while acting that solution:</p> <pre><code>#for the example, i dont load the file but create a var with the supposed file content file_content = "'var_a': 4, 'var_b': 'a string'" mydict = dict(file_content) #Error: ValueError: dictionary update sequence element #0 has length 1; 2 is required file_content_2 = "{'var_a': 4, 'var_b': 'a string'}" mydict_2 = dict(json.dump(file_content_2, True)) #Error: #Traceback (most recent call last): #File "&lt;pyshell#5&gt;", line 1, in &lt;module&gt; #mydict_2 = dict(json.dump(file_content_2, True)) #File "C:\Python26\lib\json\__init__.py", line 181, in dump #fp.write(chunk) #AttributeError: 'bool' object has no attribute 'write' </code></pre> <p>In what kind of issues can I fall with the JSON format? And, how can I read a JSON array in a text file, and transform it in a python dict?</p> <p>P.S: I don't like the solution using .py files; I'll prefer .txt, .inc, .whatever is not restrictive to one language.</p>
20
2009-05-29T06:48:30Z
924,866
<blockquote> <p>But what i'll love is to refer to the variable direclty, as i declared it in the python script..</p> </blockquote> <p>Assuming you're happy to change your syntax slightly, just use python and import the "config" module.</p> <pre><code># myconfig.py: var_a = 'home' var_b = 'car' var_c = 15.5 </code></pre> <p>Then do </p> <pre><code>from myconfig import * </code></pre> <p>And you can reference them by name in your current context.</p>
39
2009-05-29T07:54:55Z
[ "python", "json", "variables", "text-files" ]
Best way to retrieve variable values from a text file - Python - Json
924,700
<p>Referring on <a href="http://stackoverflow.com/questions/868112/loading-files-into-variables-in-python">this question</a>, I have a similar -but not the same- problem..</p> <p>On my way, I'll have some text file, structured like:</p> <pre><code>var_a: 'home' var_b: 'car' var_c: 15.5 </code></pre> <p>And I need that python read the file and then create a variable named var_a with value 'home', and so on.</p> <p>Example:</p> <pre><code>#python stuff over here getVarFromFile(filename) #this is the function that im looking for print var_b #output: car, as string print var_c #output 15.5, as number. </code></pre> <p>Is this possible, I mean, even keep the var type?</p> <p>Notice that I have the full freedom to the text file structure, I can use the format I like if the one I proposed isn't the best.</p> <p><strong>EDIT</strong>: the ConfigParser can be a solution, but I don't like it so much, because in my script I'll have then to refer to the variables in the file with</p> <pre><code>config.get("set", "var_name") </code></pre> <p>But what I'll love is to refer to the variable directly, as I declared it in the python script...</p> <p>There is a way to import the file as a python dictionary?</p> <p>Oh, last thing, keep in mind that I don't know exactly how many variables would I have in the text file.</p> <p><strong>Edit 2</strong>: I'm very interested at stephan's JSON solution, because in that way the text file could be read simply with others languages (PHP, then via AJAX JavaScript, for example), but I fail in something while acting that solution:</p> <pre><code>#for the example, i dont load the file but create a var with the supposed file content file_content = "'var_a': 4, 'var_b': 'a string'" mydict = dict(file_content) #Error: ValueError: dictionary update sequence element #0 has length 1; 2 is required file_content_2 = "{'var_a': 4, 'var_b': 'a string'}" mydict_2 = dict(json.dump(file_content_2, True)) #Error: #Traceback (most recent call last): #File "&lt;pyshell#5&gt;", line 1, in &lt;module&gt; #mydict_2 = dict(json.dump(file_content_2, True)) #File "C:\Python26\lib\json\__init__.py", line 181, in dump #fp.write(chunk) #AttributeError: 'bool' object has no attribute 'write' </code></pre> <p>In what kind of issues can I fall with the JSON format? And, how can I read a JSON array in a text file, and transform it in a python dict?</p> <p>P.S: I don't like the solution using .py files; I'll prefer .txt, .inc, .whatever is not restrictive to one language.</p>
20
2009-05-29T06:48:30Z
924,870
<p>What you want appear to want is the following, but this is <strong>NOT RECOMMENDED</strong>:</p> <pre><code>&gt;&gt;&gt; for line in open('dangerous.txt'): ... exec('%s = %s' % tuple(line.split(':', 1))) ... &gt;&gt;&gt; var_a 'home' </code></pre> <p>This creates somewhat similar behavior to PHP's <a href="http://php.chinaunix.net/manual/en/security.globals.php" rel="nofollow"><code>register_globals</code></a> and hence has the same security issues. Additionally, the use of <code>exec</code> that I showed allows arbitrary code execution. <em>Only</em> use this if you are absolutely sure that the contents of the text file can be trusted under all circumstances.</p> <p>You should really consider binding the variables not to the local scope, but to an object, and use a library that parses the file contents such that no code is executed. So: go with any of the other solutions provided here.</p> <p>(Please note: I added this answer not as a solution, but as an explicit <em>non-solution</em>.)</p>
1
2009-05-29T07:55:57Z
[ "python", "json", "variables", "text-files" ]
Best way to retrieve variable values from a text file - Python - Json
924,700
<p>Referring on <a href="http://stackoverflow.com/questions/868112/loading-files-into-variables-in-python">this question</a>, I have a similar -but not the same- problem..</p> <p>On my way, I'll have some text file, structured like:</p> <pre><code>var_a: 'home' var_b: 'car' var_c: 15.5 </code></pre> <p>And I need that python read the file and then create a variable named var_a with value 'home', and so on.</p> <p>Example:</p> <pre><code>#python stuff over here getVarFromFile(filename) #this is the function that im looking for print var_b #output: car, as string print var_c #output 15.5, as number. </code></pre> <p>Is this possible, I mean, even keep the var type?</p> <p>Notice that I have the full freedom to the text file structure, I can use the format I like if the one I proposed isn't the best.</p> <p><strong>EDIT</strong>: the ConfigParser can be a solution, but I don't like it so much, because in my script I'll have then to refer to the variables in the file with</p> <pre><code>config.get("set", "var_name") </code></pre> <p>But what I'll love is to refer to the variable directly, as I declared it in the python script...</p> <p>There is a way to import the file as a python dictionary?</p> <p>Oh, last thing, keep in mind that I don't know exactly how many variables would I have in the text file.</p> <p><strong>Edit 2</strong>: I'm very interested at stephan's JSON solution, because in that way the text file could be read simply with others languages (PHP, then via AJAX JavaScript, for example), but I fail in something while acting that solution:</p> <pre><code>#for the example, i dont load the file but create a var with the supposed file content file_content = "'var_a': 4, 'var_b': 'a string'" mydict = dict(file_content) #Error: ValueError: dictionary update sequence element #0 has length 1; 2 is required file_content_2 = "{'var_a': 4, 'var_b': 'a string'}" mydict_2 = dict(json.dump(file_content_2, True)) #Error: #Traceback (most recent call last): #File "&lt;pyshell#5&gt;", line 1, in &lt;module&gt; #mydict_2 = dict(json.dump(file_content_2, True)) #File "C:\Python26\lib\json\__init__.py", line 181, in dump #fp.write(chunk) #AttributeError: 'bool' object has no attribute 'write' </code></pre> <p>In what kind of issues can I fall with the JSON format? And, how can I read a JSON array in a text file, and transform it in a python dict?</p> <p>P.S: I don't like the solution using .py files; I'll prefer .txt, .inc, .whatever is not restrictive to one language.</p>
20
2009-05-29T06:48:30Z
924,967
<p>How reliable is your format? If the seperator is always exactly ': ', the following works. If not, a comparatively simple regex should do the job.</p> <p>As long as you're working with fairly simple variable types, Python's eval function makes persisting variables to files surprisingly easy.</p> <p>(The below gives you a dictionary, btw, which you mentioned was one of your prefered solutions).</p> <pre><code>def read_config(filename): f = open(filename) config_dict = {} for lines in f: items = lines.split(': ', 1) config_dict[items[0]] = eval(items[1]) return config_dict </code></pre>
2
2009-05-29T08:27:04Z
[ "python", "json", "variables", "text-files" ]
Best way to retrieve variable values from a text file - Python - Json
924,700
<p>Referring on <a href="http://stackoverflow.com/questions/868112/loading-files-into-variables-in-python">this question</a>, I have a similar -but not the same- problem..</p> <p>On my way, I'll have some text file, structured like:</p> <pre><code>var_a: 'home' var_b: 'car' var_c: 15.5 </code></pre> <p>And I need that python read the file and then create a variable named var_a with value 'home', and so on.</p> <p>Example:</p> <pre><code>#python stuff over here getVarFromFile(filename) #this is the function that im looking for print var_b #output: car, as string print var_c #output 15.5, as number. </code></pre> <p>Is this possible, I mean, even keep the var type?</p> <p>Notice that I have the full freedom to the text file structure, I can use the format I like if the one I proposed isn't the best.</p> <p><strong>EDIT</strong>: the ConfigParser can be a solution, but I don't like it so much, because in my script I'll have then to refer to the variables in the file with</p> <pre><code>config.get("set", "var_name") </code></pre> <p>But what I'll love is to refer to the variable directly, as I declared it in the python script...</p> <p>There is a way to import the file as a python dictionary?</p> <p>Oh, last thing, keep in mind that I don't know exactly how many variables would I have in the text file.</p> <p><strong>Edit 2</strong>: I'm very interested at stephan's JSON solution, because in that way the text file could be read simply with others languages (PHP, then via AJAX JavaScript, for example), but I fail in something while acting that solution:</p> <pre><code>#for the example, i dont load the file but create a var with the supposed file content file_content = "'var_a': 4, 'var_b': 'a string'" mydict = dict(file_content) #Error: ValueError: dictionary update sequence element #0 has length 1; 2 is required file_content_2 = "{'var_a': 4, 'var_b': 'a string'}" mydict_2 = dict(json.dump(file_content_2, True)) #Error: #Traceback (most recent call last): #File "&lt;pyshell#5&gt;", line 1, in &lt;module&gt; #mydict_2 = dict(json.dump(file_content_2, True)) #File "C:\Python26\lib\json\__init__.py", line 181, in dump #fp.write(chunk) #AttributeError: 'bool' object has no attribute 'write' </code></pre> <p>In what kind of issues can I fall with the JSON format? And, how can I read a JSON array in a text file, and transform it in a python dict?</p> <p>P.S: I don't like the solution using .py files; I'll prefer .txt, .inc, .whatever is not restrictive to one language.</p>
20
2009-05-29T06:48:30Z
9,816,149
<p>Suppose that you have a file Called "test.txt" with:</p> <pre><code>a=1.251 b=2.65415 c=3.54 d=549.5645 e=4684.65489 </code></pre> <p>And you want to find a variable (a,b,c,d or e):</p> <pre><code>ffile=open('test.txt','r').read() variable=raw_input('Wich is the variable you are looking for?\n') ini=ffile.find(variable)+(len(variable)+1) rest=ffile[ini:] search_enter=rest.find('\n') number=float(rest[:search_enter]) print "value:",number </code></pre>
3
2012-03-22T03:43:22Z
[ "python", "json", "variables", "text-files" ]
Best way to retrieve variable values from a text file - Python - Json
924,700
<p>Referring on <a href="http://stackoverflow.com/questions/868112/loading-files-into-variables-in-python">this question</a>, I have a similar -but not the same- problem..</p> <p>On my way, I'll have some text file, structured like:</p> <pre><code>var_a: 'home' var_b: 'car' var_c: 15.5 </code></pre> <p>And I need that python read the file and then create a variable named var_a with value 'home', and so on.</p> <p>Example:</p> <pre><code>#python stuff over here getVarFromFile(filename) #this is the function that im looking for print var_b #output: car, as string print var_c #output 15.5, as number. </code></pre> <p>Is this possible, I mean, even keep the var type?</p> <p>Notice that I have the full freedom to the text file structure, I can use the format I like if the one I proposed isn't the best.</p> <p><strong>EDIT</strong>: the ConfigParser can be a solution, but I don't like it so much, because in my script I'll have then to refer to the variables in the file with</p> <pre><code>config.get("set", "var_name") </code></pre> <p>But what I'll love is to refer to the variable directly, as I declared it in the python script...</p> <p>There is a way to import the file as a python dictionary?</p> <p>Oh, last thing, keep in mind that I don't know exactly how many variables would I have in the text file.</p> <p><strong>Edit 2</strong>: I'm very interested at stephan's JSON solution, because in that way the text file could be read simply with others languages (PHP, then via AJAX JavaScript, for example), but I fail in something while acting that solution:</p> <pre><code>#for the example, i dont load the file but create a var with the supposed file content file_content = "'var_a': 4, 'var_b': 'a string'" mydict = dict(file_content) #Error: ValueError: dictionary update sequence element #0 has length 1; 2 is required file_content_2 = "{'var_a': 4, 'var_b': 'a string'}" mydict_2 = dict(json.dump(file_content_2, True)) #Error: #Traceback (most recent call last): #File "&lt;pyshell#5&gt;", line 1, in &lt;module&gt; #mydict_2 = dict(json.dump(file_content_2, True)) #File "C:\Python26\lib\json\__init__.py", line 181, in dump #fp.write(chunk) #AttributeError: 'bool' object has no attribute 'write' </code></pre> <p>In what kind of issues can I fall with the JSON format? And, how can I read a JSON array in a text file, and transform it in a python dict?</p> <p>P.S: I don't like the solution using .py files; I'll prefer .txt, .inc, .whatever is not restrictive to one language.</p>
20
2009-05-29T06:48:30Z
11,799,592
<p>The other solutions posted here didn't work for me, because: </p> <ul> <li>i just needed parameters from a file for a normal script</li> <li><code>import *</code> didn't work for me, as i need a way to override them by choosing another file</li> <li>Just a file with a dict wasn't fine, as I needed comments in it.</li> </ul> <p>So I ended up using <code>Configparser</code> and <code>globals().update()</code></p> <p>Test file:</p> <pre><code>#File parametertest.cfg: [Settings] #Comments are no Problem test= True bla= False #Here neither #that neither </code></pre> <p>And that's my demo script:</p> <pre><code>import ConfigParser cfg = ConfigParser.RawConfigParser() cfg.read('parametertest.cfg') # Read file #print cfg.getboolean('Settings','bla') # Manual Way to acess them par=dict(cfg.items("Settings")) for p in par: par[p]=par[p].split("#",1)[0].strip() # To get rid of inline comments globals().update(par) #Make them availible globally print bla </code></pre> <p>It's just for a file with one section now, but that will be easy to adopt.</p> <p>Hope it will be helpful for someone :)</p>
3
2012-08-03T16:21:55Z
[ "python", "json", "variables", "text-files" ]
Best way to retrieve variable values from a text file - Python - Json
924,700
<p>Referring on <a href="http://stackoverflow.com/questions/868112/loading-files-into-variables-in-python">this question</a>, I have a similar -but not the same- problem..</p> <p>On my way, I'll have some text file, structured like:</p> <pre><code>var_a: 'home' var_b: 'car' var_c: 15.5 </code></pre> <p>And I need that python read the file and then create a variable named var_a with value 'home', and so on.</p> <p>Example:</p> <pre><code>#python stuff over here getVarFromFile(filename) #this is the function that im looking for print var_b #output: car, as string print var_c #output 15.5, as number. </code></pre> <p>Is this possible, I mean, even keep the var type?</p> <p>Notice that I have the full freedom to the text file structure, I can use the format I like if the one I proposed isn't the best.</p> <p><strong>EDIT</strong>: the ConfigParser can be a solution, but I don't like it so much, because in my script I'll have then to refer to the variables in the file with</p> <pre><code>config.get("set", "var_name") </code></pre> <p>But what I'll love is to refer to the variable directly, as I declared it in the python script...</p> <p>There is a way to import the file as a python dictionary?</p> <p>Oh, last thing, keep in mind that I don't know exactly how many variables would I have in the text file.</p> <p><strong>Edit 2</strong>: I'm very interested at stephan's JSON solution, because in that way the text file could be read simply with others languages (PHP, then via AJAX JavaScript, for example), but I fail in something while acting that solution:</p> <pre><code>#for the example, i dont load the file but create a var with the supposed file content file_content = "'var_a': 4, 'var_b': 'a string'" mydict = dict(file_content) #Error: ValueError: dictionary update sequence element #0 has length 1; 2 is required file_content_2 = "{'var_a': 4, 'var_b': 'a string'}" mydict_2 = dict(json.dump(file_content_2, True)) #Error: #Traceback (most recent call last): #File "&lt;pyshell#5&gt;", line 1, in &lt;module&gt; #mydict_2 = dict(json.dump(file_content_2, True)) #File "C:\Python26\lib\json\__init__.py", line 181, in dump #fp.write(chunk) #AttributeError: 'bool' object has no attribute 'write' </code></pre> <p>In what kind of issues can I fall with the JSON format? And, how can I read a JSON array in a text file, and transform it in a python dict?</p> <p>P.S: I don't like the solution using .py files; I'll prefer .txt, .inc, .whatever is not restrictive to one language.</p>
20
2009-05-29T06:48:30Z
35,526,906
<p>hbn's answer won't work out of the box if the file to load <a href="http://stackoverflow.com/q/1260792/812102">is in a subdirectory</a> or <a href="http://stackoverflow.com/q/8350853/812102">is named with dashes</a>.</p> <p>In such a case you may consider this alternative :</p> <pre><code>exec open(myconfig.py).read() </code></pre> <p>Or the simpler but deprecated in python3 :</p> <pre><code>execfile(myconfig.py) </code></pre> <p>I guess Stephan202's warning applies to both options, though, and maybe the loop on lines is safer.</p>
0
2016-02-20T17:55:43Z
[ "python", "json", "variables", "text-files" ]
How can I remove the top and right axis in matplotlib?
925,024
<p>Instead of the default "boxed" axis style I want to have only the left and bottom axis, i.e.:</p> <pre><code>+------+ | | | | | | ---&gt; | | | | +------+ +------- </code></pre> <p>This should be easy, but I can't find the necessary options in the docs.</p>
45
2009-05-29T08:45:12Z
925,141
<p>[edit] matplotlib in now (2013-10) on version 1.3.0 which includes this</p> <p>That ability was actually just added, and you need the Subversion version for it. You can see the example code <a href="http://matplotlib.org/examples/pylab_examples/spine_placement_demo.html">here</a>.</p> <p>I am just updating to say that there's a better <a href="https://github.com/matplotlib/matplotlib/blob/master/doc/mpl_toolkits/axes_grid/figures/simple_axisline3.py">example</a> online now. Still need the Subversion version though, there hasn't been a release with this yet.</p> <p>[edit] Matplotlib 0.99.0 RC1 was just released, and includes this capability.</p>
24
2009-05-29T09:21:20Z
[ "python", "matplotlib" ]
How can I remove the top and right axis in matplotlib?
925,024
<p>Instead of the default "boxed" axis style I want to have only the left and bottom axis, i.e.:</p> <pre><code>+------+ | | | | | | ---&gt; | | | | +------+ +------- </code></pre> <p>This should be easy, but I can't find the necessary options in the docs.</p>
45
2009-05-29T08:45:12Z
925,289
<p>If you don't need ticks and such (e.g. for plotting qualitative illustrations) you could also use this quick workaround: </p> <p>Make the axis invisible (e.g. with <code>plt.gca().axison = False</code>) and then draw them manually with <code>plt.arrow</code>.</p>
6
2009-05-29T10:06:22Z
[ "python", "matplotlib" ]
How can I remove the top and right axis in matplotlib?
925,024
<p>Instead of the default "boxed" axis style I want to have only the left and bottom axis, i.e.:</p> <pre><code>+------+ | | | | | | ---&gt; | | | | +------+ +------- </code></pre> <p>This should be easy, but I can't find the necessary options in the docs.</p>
45
2009-05-29T08:45:12Z
8,011,585
<p>Alternatively, this</p> <pre><code>def simpleaxis(ax): ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) ax.get_xaxis().tick_bottom() ax.get_yaxis().tick_left() </code></pre> <p>seems to achieve the same effect on an axis without losing rotated label support.</p> <p>(Matplotlib 1.0.1; solution inspired by <a href="http://www.shocksolution.com/2011/08/removing-an-axis-or-both-axes-from-a-matplotlib-plot/">this</a>).</p>
41
2011-11-04T15:20:04Z
[ "python", "matplotlib" ]
How can I remove the top and right axis in matplotlib?
925,024
<p>Instead of the default "boxed" axis style I want to have only the left and bottom axis, i.e.:</p> <pre><code>+------+ | | | | | | ---&gt; | | | | +------+ +------- </code></pre> <p>This should be easy, but I can't find the necessary options in the docs.</p>
45
2009-05-29T08:45:12Z
27,361,819
<p>This is the suggested Matplotlib 1.4 solution from the official website <a href="http://matplotlib.org/examples/ticks_and_spines/spines_demo.html">HERE</a>:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt x = np.linspace(0, 2*np.pi, 100) y = np.sin(x) ax = plt.subplot(111) ax.plot(x, y) # Hide the right and top spines ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False) # Only show ticks on the left and bottom spines ax.yaxis.set_ticks_position('left') ax.xaxis.set_ticks_position('bottom') plt.show() </code></pre> <p><img src="http://i.stack.imgur.com/3dwiV.png" alt="enter image description here"></p>
16
2014-12-08T15:58:27Z
[ "python", "matplotlib" ]
How can I remove the top and right axis in matplotlib?
925,024
<p>Instead of the default "boxed" axis style I want to have only the left and bottom axis, i.e.:</p> <pre><code>+------+ | | | | | | ---&gt; | | | | +------+ +------- </code></pre> <p>This should be easy, but I can't find the necessary options in the docs.</p>
45
2009-05-29T08:45:12Z
34,714,905
<p>This is much more rudimentary, but might do the trick:</p> <p>remove_border()</p>
0
2016-01-11T05:44:38Z
[ "python", "matplotlib" ]
A Python walker that can ignore directories
925,056
<p>I need a file system walker that I could instruct to ignore traversing directories that I want to leave untouched, including all subdirectories below that branch. The os.walk and os.path.walk just don't do it.</p>
8
2009-05-29T08:52:46Z
925,081
<p>So I made this home-roles walker function:</p> <pre><code>import os from os.path import join, isdir, islink, isfile def mywalk(top, topdown=True, onerror=None, ignore_list=('.ignore',)): try: # Note that listdir and error are globals in this module due # to earlier import-*. names = os.listdir(top) except Exception, err: if onerror is not None: onerror(err) return if len([1 for x in names if x in ignore_list]): return dirs, nondirs = [], [] for name in names: if isdir(join(top, name)): dirs.append(name) else: nondirs.append(name) if topdown: yield top, dirs, nondirs for name in dirs: path = join(top, name) if not islink(path): for x in mywalk(path, topdown, onerror, ignore_list): yield x if not topdown: yield top, dirs, nondirs </code></pre>
1
2009-05-29T08:59:52Z
[ "python", "directory-walk", "ignore-files" ]
A Python walker that can ignore directories
925,056
<p>I need a file system walker that I could instruct to ignore traversing directories that I want to leave untouched, including all subdirectories below that branch. The os.walk and os.path.walk just don't do it.</p>
8
2009-05-29T08:52:46Z
925,287
<p>It is possible to modify the second element of <a href="http://docs.python.org/library/os.html#module-os"><code>os.walk</code></a>'s return values in-place:</p> <blockquote> <p>[...] the caller can modify the dirnames list in-place (perhaps using del or slice assignment), and walk() will only recurse into the subdirectories whose names remain in dirnames; this can be used to prune the search [...]</p> </blockquote> <pre><code>def fwalk(root, predicate): for dirpath, dirnames, filenames in os.walk(root): dirnames[:] = [d for d in dirnames if predicate(r, d)] yield dirpath, dirnames, filenames </code></pre> <p>Now, you can just hand in a predicate for subdirectories:</p> <pre><code>&gt;&gt;&gt; ignore_list = [...] &gt;&gt;&gt; list(fwalk("some/root", lambda r, d: d not in ignore_list)) </code></pre>
7
2009-05-29T10:05:38Z
[ "python", "directory-walk", "ignore-files" ]
A Python walker that can ignore directories
925,056
<p>I need a file system walker that I could instruct to ignore traversing directories that I want to leave untouched, including all subdirectories below that branch. The os.walk and os.path.walk just don't do it.</p>
8
2009-05-29T08:52:46Z
925,291
<p>Actually, <code>os.walk</code> may do exactly what you want. Say I have a list (perhaps a set) of directories to ignore in <code>ignore</code>. Then this should work:</p> <pre><code>def my_walk(top_dir, ignore): for dirpath, dirnames, filenames in os.walk(top_dir): dirnames[:] = [ dn for dn in dirnames if os.path.join(dirpath, dn) not in ignore ] yield dirpath, dirnames, filenames </code></pre>
9
2009-05-29T10:06:40Z
[ "python", "directory-walk", "ignore-files" ]
A Python walker that can ignore directories
925,056
<p>I need a file system walker that I could instruct to ignore traversing directories that I want to leave untouched, including all subdirectories below that branch. The os.walk and os.path.walk just don't do it.</p>
8
2009-05-29T08:52:46Z
8,828,438
<p>Here's the best and simple solution. </p> <pre><code>def walk(ignores): global ignore path = os.getcwd() for root, dirs, files in os.walk(path): for ignore in ignores: if(ignore in dirs): dirs.remove(ignore) print root print dirs print files walk(['.git', '.svn']) </code></pre> <p>Remember, if you remove the folder name from dirs, it won't be explore by os.walk.</p> <p>hope it helps</p>
2
2012-01-11T23:55:17Z
[ "python", "directory-walk", "ignore-files" ]
Scope, using functions in current module
925,075
<p>I know this must be a trivial question, but I've tried many different ways, and searched quie a bit for a solution, but how do I create and reference subfunctions in the current module?</p> <p>For example, I am writing a program to parse through a text file, and for each of the 300 different names in it, I want to assign to a category.</p> <p>There are 300 of these, and I have a list of these structured to create a dict, so of the form lookup[key]=value (bonus question; any more efficient or sensible way to do this than a massive dict?).</p> <p>I would like to keep all of this in the same module, but with the functions (dict initialisation, etc) at the end of the file, so I dont have to scroll down 300 lines to see the code, i.e. as laid out as in the example below.</p> <p>When I run it as below, I get the error 'initlookups is not defined'. When I structure is so that it is initialisation, then function definition, then function use, no problem.</p> <p>I'm sure there must be an obvious way to initialise the functions and associated dict without keeping the code inline, but have tried quite a few so far without success. I can put it in an external module and import this, but would prefer not to for simplicity.</p> <p>What should I be doing in terms of module structure? Is there any better way than using a dict to store this lookup table (It is 300 unique text keys mapping on to approx 10 categories?</p> <p>Thanks,</p> <p>Brendan </p> <p><hr /></p> <pre><code>import ..... (initialisation code,etc ) initLookups() # **Should create the dict - How should this be referenced?** print getlookup(KEY) # **How should this be referenced?** def initLookups(): global lookup lookup={} lookup["A"]="AA" lookup["B"]="BB" (etc etc etc....) def getlookup(value) if name in lookup.keys(): getlookup=lookup[name] else: getlookup="" return getlookup </code></pre>
1
2009-05-29T08:58:04Z
925,089
<p>A function needs to be defined before it can be called. If you want to have the code that needs to be executed at the top of the file, just define a <code>main</code> function and call it from the bottom:</p> <pre><code>import sys def main(args): pass # All your other function definitions here if __name__ == '__main__': exit(main(sys.argv[1:])) </code></pre> <p>This way, whatever you reference in <code>main</code> will have been parsed and is hence known already. The reason for testing <a href="http://docs.python.org/3.0/library/%5F%5Fmain%5F%5F.html" rel="nofollow"><code>__name__</code></a> is that in this way the <code>main</code> method will only be run when the script is executed directly, not when it is imported by another file.</p> <p><hr /></p> <p>Side note: a <code>dict</code> with 300 keys is by no means massive, but you may want to either move the code that fills the <code>dict</code> to a separate module, or (perhaps more fancy) store the key/value pairs in a format like <a href="http://docs.python.org/3.0/library/json.html" rel="nofollow">JSON</a> and load it when the program starts.</p>
5
2009-05-29T09:04:40Z
[ "python", "function", "scope", "module", "structure" ]
Scope, using functions in current module
925,075
<p>I know this must be a trivial question, but I've tried many different ways, and searched quie a bit for a solution, but how do I create and reference subfunctions in the current module?</p> <p>For example, I am writing a program to parse through a text file, and for each of the 300 different names in it, I want to assign to a category.</p> <p>There are 300 of these, and I have a list of these structured to create a dict, so of the form lookup[key]=value (bonus question; any more efficient or sensible way to do this than a massive dict?).</p> <p>I would like to keep all of this in the same module, but with the functions (dict initialisation, etc) at the end of the file, so I dont have to scroll down 300 lines to see the code, i.e. as laid out as in the example below.</p> <p>When I run it as below, I get the error 'initlookups is not defined'. When I structure is so that it is initialisation, then function definition, then function use, no problem.</p> <p>I'm sure there must be an obvious way to initialise the functions and associated dict without keeping the code inline, but have tried quite a few so far without success. I can put it in an external module and import this, but would prefer not to for simplicity.</p> <p>What should I be doing in terms of module structure? Is there any better way than using a dict to store this lookup table (It is 300 unique text keys mapping on to approx 10 categories?</p> <p>Thanks,</p> <p>Brendan </p> <p><hr /></p> <pre><code>import ..... (initialisation code,etc ) initLookups() # **Should create the dict - How should this be referenced?** print getlookup(KEY) # **How should this be referenced?** def initLookups(): global lookup lookup={} lookup["A"]="AA" lookup["B"]="BB" (etc etc etc....) def getlookup(value) if name in lookup.keys(): getlookup=lookup[name] else: getlookup="" return getlookup </code></pre>
1
2009-05-29T08:58:04Z
925,358
<p>If your lookup dict is unchanging, the simplest way is to just make it a module scope variable. ie:</p> <pre><code>lookup = { 'A' : 'AA', 'B' : 'BB', ... } </code></pre> <p>If you may need to make changes, and later re-initialise it, you can do this in an initialisation function:</p> <pre><code>def initLookups(): global lookup lookup = { 'A' : 'AA', 'B' : 'BB', ... } </code></pre> <p>(Alternatively, lookup.update({'A':'AA', ...}) to change the dict in-place, affecting all callers with access to the old binding.)</p> <p>However, if you've got these lookups in some standard format, it may be simpler simply to load it from a file and create the dictionary from that.</p> <p>You can arrange your functions as you wish. The only rule about ordering is that the accessed variables must exist at the time the function is <strong>called</strong> - it's fine if the function has references to variables in the body that don't exist yet, so long as nothing actually tries to use that function. ie:</p> <pre><code>def foo(): print greeting, "World" # Note that greeting is not yet defined when foo() is created greeting = "Hello" foo() # Prints "Hello World" </code></pre> <p>But:</p> <pre><code>def foo(): print greeting, "World" foo() # Gives an error - greeting not yet defined. greeting = "Hello" </code></pre> <p>One further thing to note: your getlookup function is very inefficient. Using "<code>if name in lookup.keys()</code>" is actually getting a <strong>list</strong> of the keys from the dict, and then iterating over this list to find the item. This loses all the performance benefit the dict gives. Instead, "<code>if name in lookup</code>" would avoid this, or even better, use the fact that <code>.get</code> can be given a default to return if the key is not in the dictionary:</p> <pre><code>def getlookup(name) return lookup.get(name, "") </code></pre>
0
2009-05-29T10:32:39Z
[ "python", "function", "scope", "module", "structure" ]
Scope, using functions in current module
925,075
<p>I know this must be a trivial question, but I've tried many different ways, and searched quie a bit for a solution, but how do I create and reference subfunctions in the current module?</p> <p>For example, I am writing a program to parse through a text file, and for each of the 300 different names in it, I want to assign to a category.</p> <p>There are 300 of these, and I have a list of these structured to create a dict, so of the form lookup[key]=value (bonus question; any more efficient or sensible way to do this than a massive dict?).</p> <p>I would like to keep all of this in the same module, but with the functions (dict initialisation, etc) at the end of the file, so I dont have to scroll down 300 lines to see the code, i.e. as laid out as in the example below.</p> <p>When I run it as below, I get the error 'initlookups is not defined'. When I structure is so that it is initialisation, then function definition, then function use, no problem.</p> <p>I'm sure there must be an obvious way to initialise the functions and associated dict without keeping the code inline, but have tried quite a few so far without success. I can put it in an external module and import this, but would prefer not to for simplicity.</p> <p>What should I be doing in terms of module structure? Is there any better way than using a dict to store this lookup table (It is 300 unique text keys mapping on to approx 10 categories?</p> <p>Thanks,</p> <p>Brendan </p> <p><hr /></p> <pre><code>import ..... (initialisation code,etc ) initLookups() # **Should create the dict - How should this be referenced?** print getlookup(KEY) # **How should this be referenced?** def initLookups(): global lookup lookup={} lookup["A"]="AA" lookup["B"]="BB" (etc etc etc....) def getlookup(value) if name in lookup.keys(): getlookup=lookup[name] else: getlookup="" return getlookup </code></pre>
1
2009-05-29T08:58:04Z
925,361
<p>Here's a more pythonic ways to do this. There aren't a lot of choices, BTW.</p> <p>A function <em>must</em> be defined before it can be <em>used</em>. Period. </p> <p>However, you don't have to strictly order all functions for the compiler's benefit. You merely have to put your execution of the functions last. </p> <pre><code>import # (initialisation code,etc ) def initLookups(): # Definitions must come before actual use lookup={} lookup["A"]="AA" lookup["B"]="BB" (etc etc etc....) return lookup # Any functions initLookups uses, can be define here. # As long as they're findable in the same module. if __name__ == "__main__": # Use comes last lookup= initLookups() print lookup.get("Key","") </code></pre> <p>Note that you don't need the <code>getlookup</code> function, it's a built-in feature of a dict, named <a href="http://docs.python.org/library/stdtypes.html#dict.get" rel="nofollow">get</a>.</p> <p>Also, "initialisation code" is suspicious. An import should not "do" anything. It should define functions and classes, but not actually provide any executable code. In the long run, executable code that is processed by an import can become a maintenance nightmare. </p> <p>The most notable exception is a module-level Singleton object that gets created by default. Even then, be sure that the mystery object which makes a module work is clearly identified in the documentation.</p>
1
2009-05-29T10:34:29Z
[ "python", "function", "scope", "module", "structure" ]
Scope, using functions in current module
925,075
<p>I know this must be a trivial question, but I've tried many different ways, and searched quie a bit for a solution, but how do I create and reference subfunctions in the current module?</p> <p>For example, I am writing a program to parse through a text file, and for each of the 300 different names in it, I want to assign to a category.</p> <p>There are 300 of these, and I have a list of these structured to create a dict, so of the form lookup[key]=value (bonus question; any more efficient or sensible way to do this than a massive dict?).</p> <p>I would like to keep all of this in the same module, but with the functions (dict initialisation, etc) at the end of the file, so I dont have to scroll down 300 lines to see the code, i.e. as laid out as in the example below.</p> <p>When I run it as below, I get the error 'initlookups is not defined'. When I structure is so that it is initialisation, then function definition, then function use, no problem.</p> <p>I'm sure there must be an obvious way to initialise the functions and associated dict without keeping the code inline, but have tried quite a few so far without success. I can put it in an external module and import this, but would prefer not to for simplicity.</p> <p>What should I be doing in terms of module structure? Is there any better way than using a dict to store this lookup table (It is 300 unique text keys mapping on to approx 10 categories?</p> <p>Thanks,</p> <p>Brendan </p> <p><hr /></p> <pre><code>import ..... (initialisation code,etc ) initLookups() # **Should create the dict - How should this be referenced?** print getlookup(KEY) # **How should this be referenced?** def initLookups(): global lookup lookup={} lookup["A"]="AA" lookup["B"]="BB" (etc etc etc....) def getlookup(value) if name in lookup.keys(): getlookup=lookup[name] else: getlookup="" return getlookup </code></pre>
1
2009-05-29T08:58:04Z
933,125
<p>I think that keeping the names in a flat text file, and loading them at runtime would be a good alternative. I try to stick to the lowest level of complexity possible with my data, starting with plain text and working up to a RDMS (I lifted this idea from <a href="http://www.pragprog.com/the-pragmatic-programmer" rel="nofollow">The Pragmatic Programmer</a>).</p> <p>Dictionaries are very efficient in python. It's essentially what the whole language is built on. 300 items is well within the bounds of sane dict usage.</p> <p>names.txt:</p> <pre><code>A = AAA B = BBB C = CCC </code></pre> <p>getname.py:</p> <pre><code>import sys FILENAME = "names.txt" def main(key): pairs = (line.split("=") for line in open(FILENAME)) names = dict((x.strip(), y.strip()) for x,y in pairs) return names.get(key, "Not found") if __name__ == "__main__": print main(sys.argv[-1]) </code></pre> <p>If you really want to keep it all in one module for some reason, you could just stick a string at the top of the module. I think that a big swath of text is less distracting than a huge mess of dict initialization code (and easier to edit later):</p> <pre><code>import sys LINES = """ A = AAA B = BBB C = CCC D = DDD E = EEE""".strip().splitlines() PAIRS = (line.split("=") for line in LINES) NAMES = dict((x.strip(), y.strip()) for x,y in PAIRS) def main(key): return NAMES.get(key, "Not found") if __name__ == "__main__": print main(sys.argv[-1]) </code></pre>
0
2009-05-31T23:43:14Z
[ "python", "function", "scope", "module", "structure" ]
python queue & multiprocessing queue: how they behave?
925,100
<p>This sample code works (I can write something in the file):</p> <pre><code>from multiprocessing import Process, Queue queue = Queue() def _printer(self, queue): queue.put("hello world!!") def _cmdDisp(self, queue): f = file("Cmd.log", "w") print &gt;&gt; f, queue.get() f.close() </code></pre> <p>instead this other sample not: (errormsg: 'module' object is not callable)</p> <pre><code>import Queue queue = Queue() def _printer(self, queue): queue.put("hello world!!") def _cmdDisp(self, queue): f = file("Cmd.log", "w") print &gt;&gt; f, queue.get() f.close() </code></pre> <p>this other sample not (I cannot write something in the file):</p> <pre><code>import Queue queue = Queue.Queue() def _printer(self, queue): queue.put("hello world!!") def _cmdDisp(self, queue): f = file("Cmd.log", "w") print &gt;&gt; f, queue.get() f.close() </code></pre> <p>Can someone explain the differences? and the right to do?</p>
13
2009-05-29T09:08:28Z
925,241
<p>For your second example, you already gave the explanation yourself---<code>Queue</code> is a module, which cannot be called.</p> <p>For the third example: I assume that you use <code>Queue.Queue</code> together with <code>multiprocessing</code>. A <code>Queue.Queue</code> will not be shared between processes. If the <code>Queue.Queue</code> is declared before the processes then each process will receive a copy of it which is then independent of every other process. Items placed in the <code>Queue.Queue</code> by the parent before starting the children will be available to each child. Items placed in the <code>Queue.Queue</code> by the parent after starting the child will only be available to the parent. <code>Queue.Queue</code> is made for data interchange between different <strong>threads</strong> inside the same process (using the <a href="http://docs.python.org/library/threading.html#module-threading">threading</a> module). The multiprocessing queues are for data interchange between different Python <strong>processes</strong>. While the API looks similar (it's designed to be that way), the underlying mechanisms are fundamentally different.</p> <ul> <li><code>multiprocessing</code> queues exchange data by pickling (serializing) objects and sending them through pipes. </li> <li><code>Queue.Queue</code> uses a data structure that is shared between threads and locks/mutexes for correct behaviour.</li> </ul>
31
2009-05-29T09:53:20Z
[ "python", "queue" ]
Uploading multiple images in Django admin
925,305
<p>I'm currently building a portfolio site for a client, and I'm having trouble with one small area. I want to be able to upload multiple images (varying number) inline for each portfolio item, and I can't see an obvious way to do it.</p> <p>The most user-friendly way I can see would be a file upload form with a JavaScript control that allows the user to add more fields as required. Has anybody had any experience with an issue like this? Indeed, are there any custom libraries out there that would solve my problem?</p> <p>I've had little call for modifying the admin tool before now, so I don't really know where to start.</p> <p>Thank you to anybody who can shed some light.</p>
7
2009-05-29T10:12:53Z
925,339
<p><a href="http://code.google.com/p/django-photologue/">photologue</a> is a feature-rich photo app for django. it e.g. lets you upload galleries as zip files (which in a sense means uploading multiple files at once), automatically creates thumbnails of different custom sizes and can apply effects to images. I used it once on one project and the integration wasn't too hard. </p>
8
2009-05-29T10:26:07Z
[ "python", "django", "image-uploading" ]
Uploading multiple images in Django admin
925,305
<p>I'm currently building a portfolio site for a client, and I'm having trouble with one small area. I want to be able to upload multiple images (varying number) inline for each portfolio item, and I can't see an obvious way to do it.</p> <p>The most user-friendly way I can see would be a file upload form with a JavaScript control that allows the user to add more fields as required. Has anybody had any experience with an issue like this? Indeed, are there any custom libraries out there that would solve my problem?</p> <p>I've had little call for modifying the admin tool before now, so I don't really know where to start.</p> <p>Thank you to anybody who can shed some light.</p>
7
2009-05-29T10:12:53Z
925,590
<p>You can extend the Admin interface pretty easily using Javascript. There's a <a href="http://www.arnebrodowski.de/blog/507-Add-and-remove-Django-Admin-Inlines-with-JavaScript.html">good article</a> on doing exactly what you want with a bit of jQuery magic.</p> <p>You would just have to throw all of his code into one Javascript file and then include the following in your admin.py:</p> <pre><code>class Photo(admin.ModelAdmin): class Media: js = ('jquery.js', 'inlines.js',) </code></pre> <p>Looking at his source, you would also have to dynamically add the link to add more inlines using Javascript, but that's pretty easy to do:</p> <pre><code>$(document).ready(function(){ // Note the name passed in is the model's name, all lower case $('div.last-related').after('&lt;div&gt;&lt;a class="add" href="#" onclick="return add_inline_form(\'photos\')"&gt;'); }); </code></pre> <p>You probably need to do some styling to make it all look right, but that should get you started in the right direction.</p> <p>Also, since you're in <code>inline</code> land, check out the <a href="http://www.djangosnippets.org/snippets/1053/">inline sort snippet</a>.</p>
9
2009-05-29T11:36:35Z
[ "python", "django", "image-uploading" ]
Giving anonymous users the same functionality as registered ones
925,456
<p>I'm working on an online store in Django (just a basic shopping cart right now), and I'm planning to add functionality for users to mark items as favorite (just like in stackoverflow). Models for the cart look something like this:</p> <pre><code>class Cart(models.Model): user = models.OneToOneField(User) class CartItem(models.Model): cart = models.ForeignKey(Cart) product = models.ForeignKey(Product, verbose_name="produs") </code></pre> <p>The favorites model would be just a table with two rows: user and product.</p> <p>The problem is that this would only work for registered users, as I need a user object. How can I also let unregistered users use these features, saving the data in cookies/sessions, and when and if they decides to register, moving the data to their user?</p> <p>I guess one option would be some kind of generic relations, but I think that's a little to complicated. Maybe having an extra row after <em>user</em> that's a session object (I haven't really used sessions in django until now), and if the User is set to None, use that?</p> <p>So basically, what I want to ask, is if you've had this problem before, how did you solve it, what would be the best approach?</p>
6
2009-05-29T11:00:55Z
925,465
<p>I haven't done this before but from reading your description I would simply create a user object when someone needs to do something that requires it. You then send the user a cookie which links to this user object, so if someone comes back (without clearing their cookies) they get the same skeleton user object.</p> <p>This means that you can use your current code with minimal changes and when they want to migrate to a full registered user you can just populate the skeleton user object with their details.</p> <p>If you wanted to keep your DB tidy-ish you could add a task that deletes all skeleton Users that haven't been used in say the last 30 days.</p>
9
2009-05-29T11:04:43Z
[ "python", "django", "session" ]
Giving anonymous users the same functionality as registered ones
925,456
<p>I'm working on an online store in Django (just a basic shopping cart right now), and I'm planning to add functionality for users to mark items as favorite (just like in stackoverflow). Models for the cart look something like this:</p> <pre><code>class Cart(models.Model): user = models.OneToOneField(User) class CartItem(models.Model): cart = models.ForeignKey(Cart) product = models.ForeignKey(Product, verbose_name="produs") </code></pre> <p>The favorites model would be just a table with two rows: user and product.</p> <p>The problem is that this would only work for registered users, as I need a user object. How can I also let unregistered users use these features, saving the data in cookies/sessions, and when and if they decides to register, moving the data to their user?</p> <p>I guess one option would be some kind of generic relations, but I think that's a little to complicated. Maybe having an extra row after <em>user</em> that's a session object (I haven't really used sessions in django until now), and if the User is set to None, use that?</p> <p>So basically, what I want to ask, is if you've had this problem before, how did you solve it, what would be the best approach?</p>
6
2009-05-29T11:00:55Z
925,483
<p>Just save the user data the user table and don't populate then userid/password tables.</p> <p>if a user registers then you just have to populate those fields.</p> <p>You will have to have some "cleanup" script run periodically to clear out any users who haven't visited in some arbitrary period. I'd make this cleanup optional. and have a script that can be run serverside (or via a web admin interface) to clear out in case your client wants to do it manually.</p> <p>remember to deleted all related entries as well as the user entry.</p>
2
2009-05-29T11:12:19Z
[ "python", "django", "session" ]
Giving anonymous users the same functionality as registered ones
925,456
<p>I'm working on an online store in Django (just a basic shopping cart right now), and I'm planning to add functionality for users to mark items as favorite (just like in stackoverflow). Models for the cart look something like this:</p> <pre><code>class Cart(models.Model): user = models.OneToOneField(User) class CartItem(models.Model): cart = models.ForeignKey(Cart) product = models.ForeignKey(Product, verbose_name="produs") </code></pre> <p>The favorites model would be just a table with two rows: user and product.</p> <p>The problem is that this would only work for registered users, as I need a user object. How can I also let unregistered users use these features, saving the data in cookies/sessions, and when and if they decides to register, moving the data to their user?</p> <p>I guess one option would be some kind of generic relations, but I think that's a little to complicated. Maybe having an extra row after <em>user</em> that's a session object (I haven't really used sessions in django until now), and if the User is set to None, use that?</p> <p>So basically, what I want to ask, is if you've had this problem before, how did you solve it, what would be the best approach?</p>
6
2009-05-29T11:00:55Z
925,514
<p>Seems to me that the easiest way to do this would be to store both the user id or the session id:</p> <pre><code>class Cart(models.Model): user = models.ForeignKey(User, null=True) session = models.CharField(max_length=32, null=True) </code></pre> <p>Then, when a user registers, you can take their <code>request.session.session_key</code> and update all rows with their new user id.</p> <p>Better yet, you could define a "<code>UserProxy</code>" model:</p> <pre><code>class Cart(models.Model): user = models.ForeignKey(UserProxy) class UserProxy(models.Model): user = models.ForeignKey(User, unique=True, null=True) session = models.CharField(max_length=32, null=True) </code></pre> <p>So then you just have to update the UserProxy table when they register, and nothing about the cart has to change.</p>
4
2009-05-29T11:18:41Z
[ "python", "django", "session" ]
Giving anonymous users the same functionality as registered ones
925,456
<p>I'm working on an online store in Django (just a basic shopping cart right now), and I'm planning to add functionality for users to mark items as favorite (just like in stackoverflow). Models for the cart look something like this:</p> <pre><code>class Cart(models.Model): user = models.OneToOneField(User) class CartItem(models.Model): cart = models.ForeignKey(Cart) product = models.ForeignKey(Product, verbose_name="produs") </code></pre> <p>The favorites model would be just a table with two rows: user and product.</p> <p>The problem is that this would only work for registered users, as I need a user object. How can I also let unregistered users use these features, saving the data in cookies/sessions, and when and if they decides to register, moving the data to their user?</p> <p>I guess one option would be some kind of generic relations, but I think that's a little to complicated. Maybe having an extra row after <em>user</em> that's a session object (I haven't really used sessions in django until now), and if the User is set to None, use that?</p> <p>So basically, what I want to ask, is if you've had this problem before, how did you solve it, what would be the best approach?</p>
6
2009-05-29T11:00:55Z
927,303
<p>I think you were on the right track thinking about using sessions. I would store a list of Product id's in the users session and then when the user registers, create a cart as you have defined and then add the items. Check out the <a href="http://docs.djangoproject.com/en/dev/topics/http/sessions/" rel="nofollow">session docs</a>. </p> <p>You could allow people that are either not logged in or don't have an account to add items to a 'temp' cart. When the person logs in to either account or creates a new account, add those items to their 'real' cart. Then by just adding a few lines to your 'add item to cart' and login functions, you can use your existing models.</p>
0
2009-05-29T17:57:18Z
[ "python", "django", "session" ]
Need help for facebook fql query
925,476
<p>I wanted to know why is this code wrong.</p> <pre><code>new_query = "SELECT time,message FROM status WHERE (uid=%s % request.facebook.uid) AND time &gt; someval.time" new_result = request.facebook.fql.query(new_query) </code></pre> <p>Someval.time is correct time format according to facebook time format. So why does it gives me wrong code??</p> <pre><code>new_query = "SELECT time,message FROM status WHERE (uid=%s % request.facebook.uid) </code></pre> <p>gives me correct value.</p> <p>Thanks</p>
1
2009-05-29T11:10:42Z
925,591
<p>Did you mean:</p> <pre><code>new_query = "SELECT ... AND time &gt; %s" % someval.time </code></pre> <p>or similar?</p> <p><strong>Edit</strong>:</p> <p>You've posted several pieces of code that look like this:</p> <pre><code>"Select something WHERE x=%s % something" </code></pre> <p>with the percent operator and its argument both within the quotes. You need to do something like this:</p> <pre><code>new_query = "SELECT time,message FROM status WHERE (uid=%s) AND (time&gt;%s)" % \ (request.facebook.uid, someval.time) </code></pre>
0
2009-05-29T11:36:42Z
[ "python", "django", "facebook" ]
Need help for facebook fql query
925,476
<p>I wanted to know why is this code wrong.</p> <pre><code>new_query = "SELECT time,message FROM status WHERE (uid=%s % request.facebook.uid) AND time &gt; someval.time" new_result = request.facebook.fql.query(new_query) </code></pre> <p>Someval.time is correct time format according to facebook time format. So why does it gives me wrong code??</p> <pre><code>new_query = "SELECT time,message FROM status WHERE (uid=%s % request.facebook.uid) </code></pre> <p>gives me correct value.</p> <p>Thanks</p>
1
2009-05-29T11:10:42Z
9,019,596
<p>Use the <code>me()</code> FQL shorthand to get at the user id for whom the token is issued for</p> <p><code>SELECT time,message FROM status WHERE uid=me()</code></p>
0
2012-01-26T14:29:43Z
[ "python", "django", "facebook" ]
Is there a uniform python library to transfer files using different protocols
925,716
<p>I know there is <code>ftplib</code> for ftp, <code>shutil</code> for local files, what about NFS? I know urllib2 can <strong>get</strong> files via HTTP/HTTPS/FTP/FTPS, but it can't <strong>put</strong> files.</p> <p>If there is a uniform library that automatically detects the protocol (FTP/NFS/LOCAL) with URI and deals with file transfer (get/put) transparently, it's even better, does it exist?</p>
3
2009-05-29T12:22:05Z
926,044
<p>Have a look at KDE IOSlaves. They can manage all the protocol you describe, plus a few others (samba, ssh, ...).</p> <p>You can instantiates IOSlaves through PyKDE or if that dependency is too big, you can probably manage the ioslave from python with the subprocess module.</p>
1
2009-05-29T13:45:36Z
[ "python", "file", "ftp", "networking", "nfs" ]
Is there a uniform python library to transfer files using different protocols
925,716
<p>I know there is <code>ftplib</code> for ftp, <code>shutil</code> for local files, what about NFS? I know urllib2 can <strong>get</strong> files via HTTP/HTTPS/FTP/FTPS, but it can't <strong>put</strong> files.</p> <p>If there is a uniform library that automatically detects the protocol (FTP/NFS/LOCAL) with URI and deals with file transfer (get/put) transparently, it's even better, does it exist?</p>
3
2009-05-29T12:22:05Z
927,764
<p>You want to look up and use pycurl/libcurl. Libcurl: <a href="http://curl.haxx.se/" rel="nofollow">http://curl.haxx.se/</a> PyCurl: <a href="http://pycurl.sourceforge.net/" rel="nofollow">http://pycurl.sourceforge.net/</a> - curl supports the http://, file://, and ftp:// uris. I have used it with much success.</p>
2
2009-05-29T19:40:07Z
[ "python", "file", "ftp", "networking", "nfs" ]
Jump into a Python Interactive Session mid-program?
925,832
<p>Hey I was wondering... I am using the pydev with eclipse and I'm really enjoying the powerful debugging features, but I was wondering:</p> <p><strong>Is it possible to set a breakpoint in eclipse and jump into the interactive python interpreter during execution?</strong></p> <p>I think that would be pretty handy ;)</p> <p><strong>edit</strong>: I want to emphasize that my goal is not to jump into a debugger. pydev/eclipse have a great debugger, and I can just look at the traceback and set break points.</p> <p>What I want is to execute a script and jump into an interactive python interpreter during execution so I can do things like... </p> <ul> <li>poke around</li> <li>check the values of things</li> <li>manipulate variables</li> <li>figure out some code before I add it to the app</li> </ul> <p>I know you can do this all with a debugger, but I can do it faster in the interactive interpreter because I can try something, see that it didn't work, and try something else without having get the app back to the point of executing that code again.</p>
11
2009-05-29T12:58:07Z
926,190
<p>If you are already running in debug mode you can set an additional breakpoint if the program execution is currently paused (e.g. because you are already at a breakpoint). I just tried it out now with the latest Pydev - it works just fine. </p> <p>If you are running normally (i.e. not in debug mode) all breakpoints will be ignored. No changes to breakpoints will alter the way a non-debug run works.</p>
-2
2009-05-29T14:14:00Z
[ "python", "eclipse", "debugging", "breakpoints", "pydev" ]
Jump into a Python Interactive Session mid-program?
925,832
<p>Hey I was wondering... I am using the pydev with eclipse and I'm really enjoying the powerful debugging features, but I was wondering:</p> <p><strong>Is it possible to set a breakpoint in eclipse and jump into the interactive python interpreter during execution?</strong></p> <p>I think that would be pretty handy ;)</p> <p><strong>edit</strong>: I want to emphasize that my goal is not to jump into a debugger. pydev/eclipse have a great debugger, and I can just look at the traceback and set break points.</p> <p>What I want is to execute a script and jump into an interactive python interpreter during execution so I can do things like... </p> <ul> <li>poke around</li> <li>check the values of things</li> <li>manipulate variables</li> <li>figure out some code before I add it to the app</li> </ul> <p>I know you can do this all with a debugger, but I can do it faster in the interactive interpreter because I can try something, see that it didn't work, and try something else without having get the app back to the point of executing that code again.</p>
11
2009-05-29T12:58:07Z
926,408
<p>I've long been using this code in my <code>sitecustomize.py</code> to start a debugger on an exception. This can also be triggered by Ctrl+C. It works beautifully in the shell, don't know about eclipse. </p> <pre><code>import sys def info(exception_type, value, tb): if hasattr(sys, 'ps1') or not sys.stderr.isatty() or not sys.stdin.isatty() or not sys.stdout.isatty() or type==SyntaxError: # we are in interactive mode or we don't have a tty-like # device, so we call the default hook sys.__excepthook__(exception_type, value, tb) else: import traceback import pdb if exception_type != KeyboardInterrupt: try: import growlnotify growlnotify.growlNotify("Script crashed", sticky = False) except ImportError: pass # we are NOT in interactive mode, print the exception... traceback.print_exception(exception_type, value, tb) print # ...then start the debugger in post-mortem mode. pdb.pm() sys.excepthook = info </code></pre> <p>Here's the <a href="http://code.activestate.com/recipes/65287/" rel="nofollow">source</a> and <a href="http://stackoverflow.com/questions/242485/starting-python-debugger-automatically-on-error">more discussion on StackOverflow</a>.</p>
2
2009-05-29T14:52:58Z
[ "python", "eclipse", "debugging", "breakpoints", "pydev" ]
Jump into a Python Interactive Session mid-program?
925,832
<p>Hey I was wondering... I am using the pydev with eclipse and I'm really enjoying the powerful debugging features, but I was wondering:</p> <p><strong>Is it possible to set a breakpoint in eclipse and jump into the interactive python interpreter during execution?</strong></p> <p>I think that would be pretty handy ;)</p> <p><strong>edit</strong>: I want to emphasize that my goal is not to jump into a debugger. pydev/eclipse have a great debugger, and I can just look at the traceback and set break points.</p> <p>What I want is to execute a script and jump into an interactive python interpreter during execution so I can do things like... </p> <ul> <li>poke around</li> <li>check the values of things</li> <li>manipulate variables</li> <li>figure out some code before I add it to the app</li> </ul> <p>I know you can do this all with a debugger, but I can do it faster in the interactive interpreter because I can try something, see that it didn't work, and try something else without having get the app back to the point of executing that code again.</p>
11
2009-05-29T12:58:07Z
956,448
<p>You can jump into an interactive session using <code>code.InteractiveConsole</code> as described <a href="http://code.activestate.com/recipes/355319/" rel="nofollow">here</a>; however I don't know how to trigger this from Eclipse.</p> <p>A solution might be to intercept Ctrl+C to jump into this interactive console (using the <a href="http://docs.python.org/library/signal.html" rel="nofollow">signal</a> module: <code>signal.signal(signal.SIGINT, my_handler)</code>), but it would probably change the execution context and you probably don't want this.</p>
2
2009-06-05T15:20:58Z
[ "python", "eclipse", "debugging", "breakpoints", "pydev" ]
Jump into a Python Interactive Session mid-program?
925,832
<p>Hey I was wondering... I am using the pydev with eclipse and I'm really enjoying the powerful debugging features, but I was wondering:</p> <p><strong>Is it possible to set a breakpoint in eclipse and jump into the interactive python interpreter during execution?</strong></p> <p>I think that would be pretty handy ;)</p> <p><strong>edit</strong>: I want to emphasize that my goal is not to jump into a debugger. pydev/eclipse have a great debugger, and I can just look at the traceback and set break points.</p> <p>What I want is to execute a script and jump into an interactive python interpreter during execution so I can do things like... </p> <ul> <li>poke around</li> <li>check the values of things</li> <li>manipulate variables</li> <li>figure out some code before I add it to the app</li> </ul> <p>I know you can do this all with a debugger, but I can do it faster in the interactive interpreter because I can try something, see that it didn't work, and try something else without having get the app back to the point of executing that code again.</p>
11
2009-05-29T12:58:07Z
960,237
<p>Not truely an answer to your question, but just a pointer to iPython. Just in case you aren't aware of it. I use it side-by-side with eclipse/pydev for just such things.</p> <p>Of relevence is this info on embedding <a href="http://ipython.scipy.org/doc/manual/html/interactive/reference.html#embedding" rel="nofollow">iPython</a> into your own app. This provides the ability to do what you are looking for if you are willing to do it outside of eclipse/pydev.</p>
1
2009-06-06T18:19:42Z
[ "python", "eclipse", "debugging", "breakpoints", "pydev" ]
Jump into a Python Interactive Session mid-program?
925,832
<p>Hey I was wondering... I am using the pydev with eclipse and I'm really enjoying the powerful debugging features, but I was wondering:</p> <p><strong>Is it possible to set a breakpoint in eclipse and jump into the interactive python interpreter during execution?</strong></p> <p>I think that would be pretty handy ;)</p> <p><strong>edit</strong>: I want to emphasize that my goal is not to jump into a debugger. pydev/eclipse have a great debugger, and I can just look at the traceback and set break points.</p> <p>What I want is to execute a script and jump into an interactive python interpreter during execution so I can do things like... </p> <ul> <li>poke around</li> <li>check the values of things</li> <li>manipulate variables</li> <li>figure out some code before I add it to the app</li> </ul> <p>I know you can do this all with a debugger, but I can do it faster in the interactive interpreter because I can try something, see that it didn't work, and try something else without having get the app back to the point of executing that code again.</p>
11
2009-05-29T12:58:07Z
962,124
<p>This is from an old project, and I didn't write it, but it does something similar to what you want using ipython.</p> <pre><code>'''Start an IPython shell (for debugging) with current environment. Runs Call db() to start a shell, e.g. def foo(bar): for x in bar: if baz(x): import ipydb; ipydb.db() # &lt;-- start IPython here, with current value of x (ipydb is the name of this module). . ''' import inspect,IPython def db(): '''Start IPython shell with callers environment.''' # find callers __up_frame = inspect.currentframe().f_back eval('IPython.Shell.IPShellEmbed([])()', # Empty list arg is # ipythons argv later args to dict take precedence, so # f_globals() shadows globals(). Need globals() for IPython # module. dict(globals().items() + __up_frame.f_globals.items()), __up_frame.f_locals) </code></pre> <p><strong>edit by Jim Robert (question owner)</strong>: If you place the above code into a file called <code>my_debug.py</code> for the sake of this example. Then place that file in your python path, and you can insert the following lines anywhere in your code to jump into a debugger (as long as you execute from a shell):</p> <pre><code>import my_debug my_debug.db() </code></pre>
6
2009-06-07T15:41:31Z
[ "python", "eclipse", "debugging", "breakpoints", "pydev" ]
Jump into a Python Interactive Session mid-program?
925,832
<p>Hey I was wondering... I am using the pydev with eclipse and I'm really enjoying the powerful debugging features, but I was wondering:</p> <p><strong>Is it possible to set a breakpoint in eclipse and jump into the interactive python interpreter during execution?</strong></p> <p>I think that would be pretty handy ;)</p> <p><strong>edit</strong>: I want to emphasize that my goal is not to jump into a debugger. pydev/eclipse have a great debugger, and I can just look at the traceback and set break points.</p> <p>What I want is to execute a script and jump into an interactive python interpreter during execution so I can do things like... </p> <ul> <li>poke around</li> <li>check the values of things</li> <li>manipulate variables</li> <li>figure out some code before I add it to the app</li> </ul> <p>I know you can do this all with a debugger, but I can do it faster in the interactive interpreter because I can try something, see that it didn't work, and try something else without having get the app back to the point of executing that code again.</p>
11
2009-05-29T12:58:07Z
3,650,728
<p>So roughly a year on from the OP's question, PyDev has this capability built in. I am not sure when this feature was introduced, but all I know is I've spent the last ~2hrs Googling... configuring iPython and whatever (which was looking like it would have done the job), but only to realise Eclipse/PyDev has what I want ootb.</p> <p>As soon as you hit a breakpoint in debug mode, the console is right there ready and waiting! I only didn't notice this as there is no prompt or blinking cursor; I had wrongly assumed it was a standard, output-only, console... but it's not. It even has code-completion.</p> <p>Great stuff, see <a href="http://pydev.org/manual_adv_debug_console.html">http://pydev.org/manual_adv_debug_console.html</a> for more details.</p>
8
2010-09-06T10:28:37Z
[ "python", "eclipse", "debugging", "breakpoints", "pydev" ]
parsing in python
925,839
<p>I have following string</p> <p>adId:4028cb901dd9720a011e1160afbc01a3;siteId:8a8ee4f720e6beb70120e6d8e08b0002;userId:5082a05c-015e-4266-9874-5dc6262da3e0</p> <p>I need only the value of adId,siteId and userId. means </p> <p>4028cb901dd9720a011e1160afbc01a3</p> <p>8a8ee4f720e6beb70120e6d8e08b0002</p> <p>5082a05c-015e-4266-9874-5dc6262da3e0</p> <p>all the 3 in different variable or in a array so that i can use all three</p>
3
2009-05-29T13:00:15Z
925,843
<p>You can split them to a dictionary if you don't need any fancy parsing:</p> <pre><code>In [2]: dict(kvpair.split(':') for kvpair in s.split(';')) Out[2]: {'adId': '4028cb901dd9720a011e1160afbc01a3', 'siteId': '8a8ee4f720e6beb70120e6d8e08b0002', 'userId': '5082a05c-015e-4266-9874-5dc6262da3e0'} </code></pre>
18
2009-05-29T13:02:42Z
[ "python" ]
parsing in python
925,839
<p>I have following string</p> <p>adId:4028cb901dd9720a011e1160afbc01a3;siteId:8a8ee4f720e6beb70120e6d8e08b0002;userId:5082a05c-015e-4266-9874-5dc6262da3e0</p> <p>I need only the value of adId,siteId and userId. means </p> <p>4028cb901dd9720a011e1160afbc01a3</p> <p>8a8ee4f720e6beb70120e6d8e08b0002</p> <p>5082a05c-015e-4266-9874-5dc6262da3e0</p> <p>all the 3 in different variable or in a array so that i can use all three</p>
3
2009-05-29T13:00:15Z
925,851
<p>There is an awesome method called <a href="http://docs.python.org/library/string.html#deprecated-string-functions" rel="nofollow">split()</a> for python that will work nicely for you. I would suggest using it twice, once for ';' then again for each one of those using ':'.</p>
0
2009-05-29T13:05:08Z
[ "python" ]
parsing in python
925,839
<p>I have following string</p> <p>adId:4028cb901dd9720a011e1160afbc01a3;siteId:8a8ee4f720e6beb70120e6d8e08b0002;userId:5082a05c-015e-4266-9874-5dc6262da3e0</p> <p>I need only the value of adId,siteId and userId. means </p> <p>4028cb901dd9720a011e1160afbc01a3</p> <p>8a8ee4f720e6beb70120e6d8e08b0002</p> <p>5082a05c-015e-4266-9874-5dc6262da3e0</p> <p>all the 3 in different variable or in a array so that i can use all three</p>
3
2009-05-29T13:00:15Z
925,853
<pre><code>matches = re.findall("([a-z0-9A-Z_]+):([a-zA-Z0-9\-]+);", buf) for m in matches: #m[1] is adid and things #m[2] is the long string. </code></pre> <p>You can also limit the lengths using {32} like</p> <pre><code>([a-zA-Z0-9]+){32}; </code></pre> <p>Regular expressions allow you to <strong>validate</strong> the string and split it into component parts.</p>
1
2009-05-29T13:05:21Z
[ "python" ]
parsing in python
925,839
<p>I have following string</p> <p>adId:4028cb901dd9720a011e1160afbc01a3;siteId:8a8ee4f720e6beb70120e6d8e08b0002;userId:5082a05c-015e-4266-9874-5dc6262da3e0</p> <p>I need only the value of adId,siteId and userId. means </p> <p>4028cb901dd9720a011e1160afbc01a3</p> <p>8a8ee4f720e6beb70120e6d8e08b0002</p> <p>5082a05c-015e-4266-9874-5dc6262da3e0</p> <p>all the 3 in different variable or in a array so that i can use all three</p>
3
2009-05-29T13:00:15Z
925,856
<p>You could do something like this:</p> <pre><code>input='adId:4028cb901dd9720a011e1160afbc01a3;siteId:8a8ee4f720e6beb70120e6d8e08b0002;userId:5082a05c-015e-4266-9874-5dc6262da3e0' result={} for pair in input.split(';'): (key,value) = pair.split(':') result[key] = value print result['adId'] print result['siteId'] print result['userId'] </code></pre>
1
2009-05-29T13:05:28Z
[ "python" ]
Fedora Python Upgrade broke easy_install
925,965
<p>Fedora Core 9 includes Python 2.5.1. I can use YUM to get latest and greatest releases.</p> <p>To get ready for 2.6 official testing, I wanted to start with 2.5.4. It appears that there's no Fedora 9 YUM package, because 2.5.4 isn't an official part of FC9.</p> <p>I downloaded 2.5.4, did <code>./configure; make; make install</code> and wound up with two Pythons. The official 2.5.1 (in <code>/usr/bin</code>) and the new 2.5.4. (in <code>/usr/local/bin</code>).</p> <p>None of my technology stack is installed in <code>/usr/local/lib/python2.5</code>. </p> <p>It appears that I have several choices for going forward. Anyone have any preferences?</p> <ul> <li><p>Copy /usr/lib/python2.5/* to /usr/local/lib/python2.5 to replicate my environment. This should work, unless some part of the Python libraries have /usr/bin/python wired in during installation. This is sure simple, but is there a down side?</p></li> <li><p>Reinstall everything by running <code>easy_install</code>. Except, <code>easy_install</code> is (currently) hard-wired to <code>/usr/bin/python</code>. So, I'd have to fix <code>easy_install</code> first, then reinstall everything. </p> <p>This takes some time, but it gives me a clean, new latest-and-greatest environment. But is there a down-side? [And why does easy_install hard-wire itself?]</p></li> <li><p>Relink <code>/usr/bin/python</code> to be <code>/usr/local/bin/python</code>. I'd still have to copy or reinstall the library, so I don't think this does me any good. [It would make <code>easy_install</code> work; but so would editing <code>/usr/bin/easy_install</code>.]</p></li> </ul> <p>Has anyone copied their library? Is it that simple? </p> <p>Or should I fix <code>easy_install</code> and simply step through the installation guide and build a new, clean, latest-and-greatest?</p> <p><hr /></p> <p><strong>Edit</strong></p> <p>Or, should I </p> <ul> <li>Skip trying to resolve the 2.5.1 and 2.5.4 issues and just jump straight to 2.6?</li> </ul>
0
2009-05-29T13:29:39Z
926,006
<p>I suggest you create a virtualenv (or several) for installing packages into.</p>
2
2009-05-29T13:37:07Z
[ "python", "fedora", "easy-install" ]
Fedora Python Upgrade broke easy_install
925,965
<p>Fedora Core 9 includes Python 2.5.1. I can use YUM to get latest and greatest releases.</p> <p>To get ready for 2.6 official testing, I wanted to start with 2.5.4. It appears that there's no Fedora 9 YUM package, because 2.5.4 isn't an official part of FC9.</p> <p>I downloaded 2.5.4, did <code>./configure; make; make install</code> and wound up with two Pythons. The official 2.5.1 (in <code>/usr/bin</code>) and the new 2.5.4. (in <code>/usr/local/bin</code>).</p> <p>None of my technology stack is installed in <code>/usr/local/lib/python2.5</code>. </p> <p>It appears that I have several choices for going forward. Anyone have any preferences?</p> <ul> <li><p>Copy /usr/lib/python2.5/* to /usr/local/lib/python2.5 to replicate my environment. This should work, unless some part of the Python libraries have /usr/bin/python wired in during installation. This is sure simple, but is there a down side?</p></li> <li><p>Reinstall everything by running <code>easy_install</code>. Except, <code>easy_install</code> is (currently) hard-wired to <code>/usr/bin/python</code>. So, I'd have to fix <code>easy_install</code> first, then reinstall everything. </p> <p>This takes some time, but it gives me a clean, new latest-and-greatest environment. But is there a down-side? [And why does easy_install hard-wire itself?]</p></li> <li><p>Relink <code>/usr/bin/python</code> to be <code>/usr/local/bin/python</code>. I'd still have to copy or reinstall the library, so I don't think this does me any good. [It would make <code>easy_install</code> work; but so would editing <code>/usr/bin/easy_install</code>.]</p></li> </ul> <p>Has anyone copied their library? Is it that simple? </p> <p>Or should I fix <code>easy_install</code> and simply step through the installation guide and build a new, clean, latest-and-greatest?</p> <p><hr /></p> <p><strong>Edit</strong></p> <p>Or, should I </p> <ul> <li>Skip trying to resolve the 2.5.1 and 2.5.4 issues and just jump straight to 2.6?</li> </ul>
0
2009-05-29T13:29:39Z
926,636
<p>I've had similar experiences and issues when installing Python 2.5 on an older release of ubuntu that supplied 2.4 out of the box.</p> <p>I first tried to patch <code>easy_install</code>, but this led to problems with anything that wanted to use the os-supplied version of python. I was often fiddling with the tool chain to fix different errors that might crop up with every install. Installing any python software via apt, or installing any software from apt that had a python <code>easy_install</code> script as part of the install, was often amusing. I'm sure I could probably have been more vigilant in patching <code>easy_install</code>, but I gave up.</p> <p>Instead, I copied the library, and everything worked. As you say, there may be issues depending on what you have installed, but I didn't run into issues. Double-checking Python's <code>site.py</code> module, I did see that it operates entirely on relative paths, building absolute paths dynamically; this gave me some confidence to try the "copy everything" approach. I double-checked any <code>.pth</code> files, then went for it.</p>
2
2009-05-29T15:35:51Z
[ "python", "fedora", "easy-install" ]
Fedora Python Upgrade broke easy_install
925,965
<p>Fedora Core 9 includes Python 2.5.1. I can use YUM to get latest and greatest releases.</p> <p>To get ready for 2.6 official testing, I wanted to start with 2.5.4. It appears that there's no Fedora 9 YUM package, because 2.5.4 isn't an official part of FC9.</p> <p>I downloaded 2.5.4, did <code>./configure; make; make install</code> and wound up with two Pythons. The official 2.5.1 (in <code>/usr/bin</code>) and the new 2.5.4. (in <code>/usr/local/bin</code>).</p> <p>None of my technology stack is installed in <code>/usr/local/lib/python2.5</code>. </p> <p>It appears that I have several choices for going forward. Anyone have any preferences?</p> <ul> <li><p>Copy /usr/lib/python2.5/* to /usr/local/lib/python2.5 to replicate my environment. This should work, unless some part of the Python libraries have /usr/bin/python wired in during installation. This is sure simple, but is there a down side?</p></li> <li><p>Reinstall everything by running <code>easy_install</code>. Except, <code>easy_install</code> is (currently) hard-wired to <code>/usr/bin/python</code>. So, I'd have to fix <code>easy_install</code> first, then reinstall everything. </p> <p>This takes some time, but it gives me a clean, new latest-and-greatest environment. But is there a down-side? [And why does easy_install hard-wire itself?]</p></li> <li><p>Relink <code>/usr/bin/python</code> to be <code>/usr/local/bin/python</code>. I'd still have to copy or reinstall the library, so I don't think this does me any good. [It would make <code>easy_install</code> work; but so would editing <code>/usr/bin/easy_install</code>.]</p></li> </ul> <p>Has anyone copied their library? Is it that simple? </p> <p>Or should I fix <code>easy_install</code> and simply step through the installation guide and build a new, clean, latest-and-greatest?</p> <p><hr /></p> <p><strong>Edit</strong></p> <p>Or, should I </p> <ul> <li>Skip trying to resolve the 2.5.1 and 2.5.4 issues and just jump straight to 2.6?</li> </ul>
0
2009-05-29T13:29:39Z
928,408
<p>Normally, you would only have one version of a python release installed. Since 2.5.1 and 2.5.4 are from the same release, copying your libraries should work fine. What you would need to watch out for, is that you now have /usr/bin/python, and /usr/local/bin/python in your path, and some utilities may get confused. </p> <p>If you need to have both micro-releases installed at once, I would keep 2.5.4 out of your path altogether, or allow it to completely clobber the other (do so at your own risk though ;) If you go with the former, you can also point 2.5.4 to your site-packages by using the PYTHONPATH environment variable.</p> <p>Ubuntu takes a different route, and this is how you can handle different major releases. The python binary is given with the version appended:</p> <pre><code>/usr/bin/python -&gt; python2.6 /usr/bin/python2.5 /usr/bin/python2.6 </code></pre> <p>Each has their own /usr/lib/python2.X directory with versions of all the modules.</p> <p>And lastly, you can further customize your setup by <a href="http://www.python.org/doc/2.5.4/inst/search-path.html" rel="nofollow">modifying your site.py</a></p>
4
2009-05-29T22:24:10Z
[ "python", "fedora", "easy-install" ]
Are inner-classes unpythonic?
926,327
<p>My colleague just pointed out that my use of inner-classes seemed to be "unpythonic". I guess it violates the "flat is better than nested" heuristic.</p> <p>What do people here think? Are inner-classes something which are more appropriate to Java etc than Python?</p> <p>NB : I don't think this is a "subjective" question. Surely style and aesthetics <em>are</em> objective within a programming community.</p> <p><hr /></p> <p><strong>Related Question:</strong> <a href="http://stackoverflow.com/questions/78799/is-there-a-benefit-to-defining-a-class-inside-another-class-in-python">Is there a benefit to defining a class inside another class in Python?</a></p>
2
2009-05-29T14:40:35Z
926,351
<p>Actually, I'm not sure if I agree with the whole premise that "Flat is better than nested". Sometimes, quite often actually, the best way to represent something is hierarchically... Even nature itself, often uses hierarchy.</p>
1
2009-05-29T14:44:23Z
[ "python" ]
Are inner-classes unpythonic?
926,327
<p>My colleague just pointed out that my use of inner-classes seemed to be "unpythonic". I guess it violates the "flat is better than nested" heuristic.</p> <p>What do people here think? Are inner-classes something which are more appropriate to Java etc than Python?</p> <p>NB : I don't think this is a "subjective" question. Surely style and aesthetics <em>are</em> objective within a programming community.</p> <p><hr /></p> <p><strong>Related Question:</strong> <a href="http://stackoverflow.com/questions/78799/is-there-a-benefit-to-defining-a-class-inside-another-class-in-python">Is there a benefit to defining a class inside another class in Python?</a></p>
2
2009-05-29T14:40:35Z
926,388
<p>"Flat is better than nested" is focused on avoiding <em>excessive</em> nesting -- i.e., seriously deep hierarchies. One level of nesting, per se, is no big deal: as long as your nesting still respects (a weakish form of) the <a href="http://en.wikipedia.org/wiki/Law%5Fof%5FDemeter" rel="nofollow">Law of Demeter</a>, as typically confirmed by the fact that you don't find yourself writing stuff like <code>onething.another.andyet.anotherone</code> (too many dots in an expression are a "code smell" suggesting you've gone too deep in nesting and need to refactor to flatten things out), I wouldn't worry too much.</p>
8
2009-05-29T14:49:32Z
[ "python" ]
Are inner-classes unpythonic?
926,327
<p>My colleague just pointed out that my use of inner-classes seemed to be "unpythonic". I guess it violates the "flat is better than nested" heuristic.</p> <p>What do people here think? Are inner-classes something which are more appropriate to Java etc than Python?</p> <p>NB : I don't think this is a "subjective" question. Surely style and aesthetics <em>are</em> objective within a programming community.</p> <p><hr /></p> <p><strong>Related Question:</strong> <a href="http://stackoverflow.com/questions/78799/is-there-a-benefit-to-defining-a-class-inside-another-class-in-python">Is there a benefit to defining a class inside another class in Python?</a></p>
2
2009-05-29T14:40:35Z
926,443
<p>This may not deserve a [subjective] tag on StackOverflow, but it's subjective on the larger stage: some language communities encourage nesting and others discourage it. So why would the Python community discourage nesting? Because Tim Peters put it in <a href="http://www.python.org/dev/peps/pep-0020/">The Zen of Python</a>? Does it apply to every scenario, always, without exception? Rules should be taken as guidelines, meaning you should not switch off your brain when applying them. You must understand what the rule <em>means</em> and why it's important enough that someone bothered to make a rule.</p> <p>The biggest reason I know to keep things flat is because of another philosophy: do one thing and do it well. Lots of little special purpose classes living inside other classes is a sign that you're not abstracting enough. I.e., you should be removing the <em>need and desire</em> to have inner classes, <em>not</em> just moving them outside for the sake of following rules.</p> <p>But sometimes you really do have some behavior that should be abstracted into a class, and it's a special case that only obtains within another single class. In that case you should use an inner class because it makes sense, and it tells anyone else reading the code that there's something special going on there.</p> <ul> <li><strong>Don't</strong> slavishly follow rules.</li> <li><strong>Do</strong> understand the reason for a rule and respect that.</li> </ul>
8
2009-05-29T14:58:56Z
[ "python" ]
Why does defining __getitem__ on a class make it iterable in python?
926,574
<p>Why does defining __getitem__ on a class make it iterable? </p> <p>For instance if I write:</p> <pre><code>class b: def __getitem__(self, k): return k cb = b() for k in cb: print k </code></pre> <p>I get the output:</p> <pre><code>0 1 2 3 4 5 6 7 8 ... </code></pre> <p>I would really expect to see an error returned from "for k in cb:"</p>
34
2009-05-29T15:22:53Z
926,590
<p>Because <code>cb[0]</code> is the same as <code>cb.__getitem__(0)</code>. See the <a href="http://docs.python.org/reference/datamodel.html" rel="nofollow">python documentation</a> on this.</p>
3
2009-05-29T15:26:14Z
[ "python", "iterator", "overloading" ]
Why does defining __getitem__ on a class make it iterable in python?
926,574
<p>Why does defining __getitem__ on a class make it iterable? </p> <p>For instance if I write:</p> <pre><code>class b: def __getitem__(self, k): return k cb = b() for k in cb: print k </code></pre> <p>I get the output:</p> <pre><code>0 1 2 3 4 5 6 7 8 ... </code></pre> <p>I would really expect to see an error returned from "for k in cb:"</p>
34
2009-05-29T15:22:53Z
926,598
<p>Special methods such as <code>__getitem__</code> add special behaviors to objects, including iteration. </p> <p><a href="http://docs.python.org/reference/datamodel.html#object.%5F%5Fgetitem%5F%5F">http://docs.python.org/reference/datamodel.html#object.<strong>getitem</strong></a></p> <p>"for loops expect that an IndexError will be raised for illegal indexes to allow proper detection of the end of the sequence."</p> <p>Raise IndexError to signal the end of the sequence.</p> <p>Your code is basically equivalent to:</p> <pre><code>i = 0 while True: try: yield object[i] i += 1 except IndexError: break </code></pre> <p>Where object is what you're iterating over in the for loop.</p>
5
2009-05-29T15:28:06Z
[ "python", "iterator", "overloading" ]
Why does defining __getitem__ on a class make it iterable in python?
926,574
<p>Why does defining __getitem__ on a class make it iterable? </p> <p>For instance if I write:</p> <pre><code>class b: def __getitem__(self, k): return k cb = b() for k in cb: print k </code></pre> <p>I get the output:</p> <pre><code>0 1 2 3 4 5 6 7 8 ... </code></pre> <p>I would really expect to see an error returned from "for k in cb:"</p>
34
2009-05-29T15:22:53Z
926,609
<p>If you take a look at <a href="http://www.python.org/dev/peps/pep-0234">PEP234</a> defining iterators, it says:</p> <pre><code>1. An object can be iterated over with "for" if it implements __iter__() or __getitem__(). 2. An object can function as an iterator if it implements next(). </code></pre>
33
2009-05-29T15:29:22Z
[ "python", "iterator", "overloading" ]
Why does defining __getitem__ on a class make it iterable in python?
926,574
<p>Why does defining __getitem__ on a class make it iterable? </p> <p>For instance if I write:</p> <pre><code>class b: def __getitem__(self, k): return k cb = b() for k in cb: print k </code></pre> <p>I get the output:</p> <pre><code>0 1 2 3 4 5 6 7 8 ... </code></pre> <p>I would really expect to see an error returned from "for k in cb:"</p>
34
2009-05-29T15:22:53Z
926,645
<p>Iteration's support for <code>__getitem__</code> can be seen as a "legacy feature" which allowed smoother transition when PEP234 introduced iterability as a primary concept. It only applies to classes without <code>__iter__</code> whose <code>__getitem__</code> accepts integers 0, 1, &amp;c, and raises <code>IndexError</code> once the index gets too high (if ever), typically "sequence" classes coded before <code>__iter__</code> appeared (though nothing stops you from coding new classes this way too).</p> <p>Personally, I would rather not rely on this in new code, though it's not deprecated nor is it going away (works fine in Python 3 too), so this is just a matter of style and taste ("explicit is better than implicit" so I'd rather explicitly support iterability rather than rely on <code>__getitem__</code> supporting it implicitly for me -- but, not a bigge).</p>
42
2009-05-29T15:37:35Z
[ "python", "iterator", "overloading" ]
Why does defining __getitem__ on a class make it iterable in python?
926,574
<p>Why does defining __getitem__ on a class make it iterable? </p> <p>For instance if I write:</p> <pre><code>class b: def __getitem__(self, k): return k cb = b() for k in cb: print k </code></pre> <p>I get the output:</p> <pre><code>0 1 2 3 4 5 6 7 8 ... </code></pre> <p>I would really expect to see an error returned from "for k in cb:"</p>
34
2009-05-29T15:22:53Z
926,649
<p><code>__getitem__</code> predates the iterator protocol, and was in the past the <em>only</em> way to make things iterable. As such, it's still supported as a method of iterating. Essentially, the protocol for iteration is:</p> <ol> <li><p>Check for an <code>__iter__</code> method. If it exists, use the new iteration protocol.</p></li> <li><p>Otherwise, try calling <code>__getitem__</code> with successively larger integer values until it raises IndexError.</p></li> </ol> <p>(2) used to be the only way of doing this, but had the disadvantage that it assumed more than was needed to support just iteration. To support iteration, you had to support random access, which was much more expensive for things like files or network streams where going forwards was easy, but going backwards would require storing everything. <code>__iter__</code> allowed iteration without random access, but since random access usually allows iteration anyway, and because breaking backward compatability would be bad, <code>__getitem__</code> is still supported.</p>
16
2009-05-29T15:38:10Z
[ "python", "iterator", "overloading" ]
Why does defining __getitem__ on a class make it iterable in python?
926,574
<p>Why does defining __getitem__ on a class make it iterable? </p> <p>For instance if I write:</p> <pre><code>class b: def __getitem__(self, k): return k cb = b() for k in cb: print k </code></pre> <p>I get the output:</p> <pre><code>0 1 2 3 4 5 6 7 8 ... </code></pre> <p>I would really expect to see an error returned from "for k in cb:"</p>
34
2009-05-29T15:22:53Z
926,652
<p>This is so for historical reasons. Prior to Python 2.2 __getitem__ was the only way to create a class that could be iterated over with the for loop. In 2.2 the __iter__ protocol was added but to retain backwards compatibility __getitem__ still works in for loops.</p>
4
2009-05-29T15:38:23Z
[ "python", "iterator", "overloading" ]
Configure Apache to recover from mod_python errors
926,579
<p>I am hosting a Django app on Apache using mod_python. Occasionally, I get some cryptic mod_python errors, usually of the <code>ImportError</code> variety, although not usually referring to the same module. The thing is, these seem to come up for a single forked subprocess, while the others operate fine, even when I force behavior that requires using the module that the problem process has errored on. Once the process encounters the error, it will always just serve the same traceback every time Apache chooses it to handle a request. (This is also a hassle, since my users don't necessarily report the error on the first occurrence, and once the process encounters the error.)</p> <p>I know more about configuring Django than configuring Apache, but that won't get me anywhere since the request never reaches Django for processing. Ideally, I should solve the root problem, and that might involve my code, project, or machine configuration, but until then, I need help diagnosing and mitigating the problem.</p> <ol> <li>Is there any way to configure the Apache logs to include a subprocess id?</li> <li>Is there any way to force a subprocess to respawn if it has hit an error?</li> <li>Are there any known issues relating to this that I should know about?</li> </ol>
0
2009-05-29T15:23:29Z
928,519
<p>As a workaround, and assuming you are free to install new Apache modules on the server, you might try one of</p> <ul> <li>mod_scgi</li> <li>mod_fastcgi</li> <li>mod_wsgi </li> </ul> <p>instead. I use SCGI to connect an nginx frontend webserver to my Django apps, which highlights a major benefit (decoupling from the webserver). All of these packages are available in Debian, probably on RHELx as well.</p>
1
2009-05-29T23:16:35Z
[ "python", "django", "apache", "mod-python" ]
Configure Apache to recover from mod_python errors
926,579
<p>I am hosting a Django app on Apache using mod_python. Occasionally, I get some cryptic mod_python errors, usually of the <code>ImportError</code> variety, although not usually referring to the same module. The thing is, these seem to come up for a single forked subprocess, while the others operate fine, even when I force behavior that requires using the module that the problem process has errored on. Once the process encounters the error, it will always just serve the same traceback every time Apache chooses it to handle a request. (This is also a hassle, since my users don't necessarily report the error on the first occurrence, and once the process encounters the error.)</p> <p>I know more about configuring Django than configuring Apache, but that won't get me anywhere since the request never reaches Django for processing. Ideally, I should solve the root problem, and that might involve my code, project, or machine configuration, but until then, I need help diagnosing and mitigating the problem.</p> <ol> <li>Is there any way to configure the Apache logs to include a subprocess id?</li> <li>Is there any way to force a subprocess to respawn if it has hit an error?</li> <li>Are there any known issues relating to this that I should know about?</li> </ol>
0
2009-05-29T15:23:29Z
981,610
<p>A more detailed version of this question with accepted answer is available at this reposting:</p> <p><a href="http://stackoverflow.com/questions/970953/testing-for-mysterious-load-errors-in-python-django">http://stackoverflow.com/questions/970953/testing-for-mysterious-load-errors-in-python-django</a></p>
0
2009-06-11T14:56:31Z
[ "python", "django", "apache", "mod-python" ]
How can I make a class in python support __getitem__, but not allow iteration?
926,688
<p>I want to define a class that supports <code>__getitem__</code>, but does not allow iteration. for example:</p> <pre><code>class B: def __getitem__(self, k): return k cb = B() for x in cb: print x </code></pre> <p>What could I add to the class <code>B</code> to force the <code>for x in cb:</code> to fail?</p>
1
2009-05-29T15:45:35Z
926,705
<p>From the answers to this <a href="http://stackoverflow.com/questions/926574/why-does-defining-getitem-on-a-class-make-it-iterable-in-python">question</a>, we can see that __iter__ will be called before __getitem__ if it exists, so simply define B as:</p> <pre><code>class B: def __getitem__(self, k): return k def __iter__(self): raise Exception("This class is not iterable") </code></pre> <p>Then:</p> <pre><code>cb = B() for x in cb: # this will throw an exception when __iter__ is called. print x </code></pre>
2
2009-05-29T15:48:07Z
[ "python", "operator-overloading", "iteration" ]
How can I make a class in python support __getitem__, but not allow iteration?
926,688
<p>I want to define a class that supports <code>__getitem__</code>, but does not allow iteration. for example:</p> <pre><code>class B: def __getitem__(self, k): return k cb = B() for x in cb: print x </code></pre> <p>What could I add to the class <code>B</code> to force the <code>for x in cb:</code> to fail?</p>
1
2009-05-29T15:45:35Z
926,832
<p>I think a slightly better solution would be to raise a TypeError rather than a plain exception (this is what normally happens with a non-iterable class:</p> <pre><code>class A(object): # show what happens with a non-iterable class with no __getitem__ pass class B(object): def __getitem__(self, k): return k def __iter__(self): raise TypeError('%r object is not iterable' % self.__class__.__name__) </code></pre> <p>Testing:</p> <pre><code>&gt;&gt;&gt; iter(A()) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: 'A' object is not iterable &gt;&gt;&gt; iter(B()) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "iter.py", line 9, in __iter__ % self.__class__.__name__) TypeError: 'B' object is not iterable </code></pre>
13
2009-05-29T16:11:20Z
[ "python", "operator-overloading", "iteration" ]
Does python-memcache use consistent hashing?
926,814
<p>I'm using the python-memcache library, and I'm wondering if anyone knows if consistent hashing is used by that client as of 1.44.</p>
1
2009-05-29T16:07:57Z
927,081
<p>From a quick view into the source code: No it does not. It uses <code>server = hash_key % len(servers)</code> and round-robin if offline/full servers are encountered.</p>
2
2009-05-29T17:03:10Z
[ "python", "memcached" ]
Does python-memcache use consistent hashing?
926,814
<p>I'm using the python-memcache library, and I'm wondering if anyone knows if consistent hashing is used by that client as of 1.44.</p>
1
2009-05-29T16:07:57Z
927,641
<p>If you need something like that you might be interested in <a href="http://amix.dk/blog/viewEntry/19367" rel="nofollow">hash_ring</a></p>
3
2009-05-29T19:10:33Z
[ "python", "memcached" ]
Checking to See if a List Exists Within Another Lists?
926,946
<p>Okay I'm trying to go for a more pythonic method of doing things.</p> <p>How can i do the following:</p> <pre><code>required_values = ['A','B','C'] some_map = {'A' : 1, 'B' : 2, 'C' : 3, 'D' : 4} for required_value in required_values: if not required_value in some_map: print 'It Doesnt Exists' return False return True </code></pre> <p>I looked at the builtin function <code>all</code>, but I cant really see how to apply that to the above scenario.</p> <p>Any suggestions for making this more pythonic?</p>
2
2009-05-29T16:35:44Z
926,977
<pre><code>all(value in some_map for value in required_values) </code></pre>
8
2009-05-29T16:42:12Z
[ "python", "list" ]
Checking to See if a List Exists Within Another Lists?
926,946
<p>Okay I'm trying to go for a more pythonic method of doing things.</p> <p>How can i do the following:</p> <pre><code>required_values = ['A','B','C'] some_map = {'A' : 1, 'B' : 2, 'C' : 3, 'D' : 4} for required_value in required_values: if not required_value in some_map: print 'It Doesnt Exists' return False return True </code></pre> <p>I looked at the builtin function <code>all</code>, but I cant really see how to apply that to the above scenario.</p> <p>Any suggestions for making this more pythonic?</p>
2
2009-05-29T16:35:44Z
926,980
<pre><code>return set(required_values).issubset(set(some_map.keys())) </code></pre>
3
2009-05-29T16:42:39Z
[ "python", "list" ]
Checking to See if a List Exists Within Another Lists?
926,946
<p>Okay I'm trying to go for a more pythonic method of doing things.</p> <p>How can i do the following:</p> <pre><code>required_values = ['A','B','C'] some_map = {'A' : 1, 'B' : 2, 'C' : 3, 'D' : 4} for required_value in required_values: if not required_value in some_map: print 'It Doesnt Exists' return False return True </code></pre> <p>I looked at the builtin function <code>all</code>, but I cant really see how to apply that to the above scenario.</p> <p>Any suggestions for making this more pythonic?</p>
2
2009-05-29T16:35:44Z
927,042
<p>try a list comprehension:</p> <p>return not bool([x for x in required_values if x not in some_map.keys()]) (bool conversion for clarity)</p> <p>or return not [x for x in required_values if x not in some_map.keys()] (i think the more pythonic way)</p> <p>The inside [] statement builds a list of all required values not in your map keys if the list is empty it evaluates to False, otherwise to True.</p> <p>so if the map has not all required values, at least one element will be in the list built by the list comprehension expression. This will evaluate to True, so we negate the result to fulfill your code requirements (which are all required values should be present in the map)</p>
0
2009-05-29T16:55:04Z
[ "python", "list" ]
Using mx:RemoteObject with web2py's @service.amfrpc decorator
927,028
<p>I am using web2py (v1.63) and Flex 3. web2py v1.61 introduced the @service decorators, which allow you to tag a controller function with @service.amfrpc. You can then call that function remotely using <code>http://..../app/default/call/amfrpc/[function]</code>. See <a href="http://www.web2py.com/examples/default/tools#services" rel="nofollow">http://www.web2py.com/examples/default/tools#services</a>. Does anybody have an example of how you would set up a Flex 3 to call a function like this? Here is what I have tried so far:</p> <pre><code>&lt;mx:RemoteObject id="myRemote" destination="amfrpc" source="amfrpc" endpoint="http://{mysite}/{myapp}/default/call/amfrpc/"&gt; &lt;mx:method name="getContacts" result="show_results(event)" fault="on_fault(event)" /&gt; &lt;/mx:RemoteObject&gt; </code></pre> <p>In my scenario, what should be the value of the destination and source attributes? I have read a couple of articles on non-web2py implementations, such as <a href="http://corlan.org/2008/10/10/flex-and-php-remoting-with-amfphp/" rel="nofollow">http://corlan.org/2008/10/10/flex-and-php-remoting-with-amfphp/</a>, but they use a .../gateway.php file instead of having a URI that maps directly to the function.</p> <p>Alternatively, I have been able to use flash.net.NetConnection to successfully call my remote function, but most of the documentation I have found considers this to be the old, pre-Flex 3 way of doing AMF. See <a href="http://pyamf.org/wiki/HelloWorld/Flex" rel="nofollow">http://pyamf.org/wiki/HelloWorld/Flex</a>. Here is the NetConnection code:</p> <pre><code>gateway = new NetConnection(); gateway.connect("http://{mysite}/{myapp}/default/call/amfrpc/"); resp = new Responder(show_results, on_fault); gateway.call("getContacts", resp); </code></pre> <p>-Rob</p>
2
2009-05-29T16:52:51Z
939,927
<p>I have not found a way to use a RemoteObject with the @service.amfrpc decorator. However, I can use the older ActionScript code using a NetConnection (similar to what I posted originally) and pair that with a @service.amfrpc function on the web2py side. This seems to work fine. The one thing that you would want to change in the NetConnection code I shared originally, is adding an event listener for connection status. You can add more listeners if you feel the need, but I found that NetStatusEvent was a must. This status will be fired if the server is not responding. You connection set up would look like:</p> <pre><code>gateway = new NetConnection(); gateway.addEventListener(NetStatusEvent.NET_STATUS, gateway_status); gateway.connect("http://127.0.0.1:8000/robs_amf/default/call/amfrpc/"); resp = new Responder(show_results, on_fault); gateway.call("getContacts", resp); </code></pre> <p>-Rob</p>
1
2009-06-02T14:37:12Z
[ "python", "flex", "flex3", "web2py", "pyamf" ]
Nokia N95 and PyS60 with the sensor and xprofile modules
927,150
<p>I've made a python script which should modify the profile of the phone based on the phone position. Runned under ScriptShell it works great.</p> <p>The problem is that it hangs, both with the "sis" script runned upon "boot up", as well as without it.</p> <p>So my question is what is wrong with the code, and also whether I need to pass special parameters to ensymble?</p> <pre><code>import appuifw, e32, sensor, xprofile from appuifw import * old_profil = xprofile.get_ap() def get_sensor_data(status): #decide profile def exit_key_handler(): # Disconnect from the sensor and exit acc_sensor.disconnect() app_lock.signal() app_lock = e32.Ao_lock() appuifw.app.exit_key_handler = exit_key_handler appuifw.app.title = u"Acc Silent" appuifw.app.menu = [(u'Close', app_lock.signal)] appuifw.app.body = Canvas() # Retrieve the acceleration sensor sensor_type= sensor.sensors()['AccSensor'] # Create an acceleration sensor object acc_sensor= sensor.Sensor(sensor_type['id'],sensor_type['category']) # Connect to the sensor acc_sensor.connect(get_sensor_data) # Wait for sensor data and the exit event app_lock.wait() </code></pre> <p>The script starts at boot, using ensymble and my developer certificate.</p> <p>Thanks in advance</p>
0
2009-05-29T17:18:52Z
955,705
<p>xprofile is not a standard library, make sure you add path to it. My guess is that when run as SIS, it doesn't find xprofile and hangs up. When releasing your SIS, either instruct that users install that separately or include inside your SIS.</p> <p>Where would you have it installed, use that path. Here's python default directory as sample:</p> <pre><code> # PyS60 1.9.x and above sys.path.append('c:\\Data\\Python') sys.path.append('e:\\Data\\Python') # Pys60 1.4.x or below sys.path.append('c:\\Python') sys.path.append('e:\\Python') </code></pre> <p>Btw make clean exit, do this:</p> <pre><code> appuifw.app.menu = [(u'Close', exit_key_handler)] </code></pre>
2
2009-06-05T13:00:15Z
[ "python", "symbian", "nokia", "s60", "pys60" ]
Nokia N95 and PyS60 with the sensor and xprofile modules
927,150
<p>I've made a python script which should modify the profile of the phone based on the phone position. Runned under ScriptShell it works great.</p> <p>The problem is that it hangs, both with the "sis" script runned upon "boot up", as well as without it.</p> <p>So my question is what is wrong with the code, and also whether I need to pass special parameters to ensymble?</p> <pre><code>import appuifw, e32, sensor, xprofile from appuifw import * old_profil = xprofile.get_ap() def get_sensor_data(status): #decide profile def exit_key_handler(): # Disconnect from the sensor and exit acc_sensor.disconnect() app_lock.signal() app_lock = e32.Ao_lock() appuifw.app.exit_key_handler = exit_key_handler appuifw.app.title = u"Acc Silent" appuifw.app.menu = [(u'Close', app_lock.signal)] appuifw.app.body = Canvas() # Retrieve the acceleration sensor sensor_type= sensor.sensors()['AccSensor'] # Create an acceleration sensor object acc_sensor= sensor.Sensor(sensor_type['id'],sensor_type['category']) # Connect to the sensor acc_sensor.connect(get_sensor_data) # Wait for sensor data and the exit event app_lock.wait() </code></pre> <p>The script starts at boot, using ensymble and my developer certificate.</p> <p>Thanks in advance</p>
0
2009-05-29T17:18:52Z
965,797
<p>I often use something like that at the top of my scripts:</p> <pre><code>import os.path, sys PY_PATH = None for p in ['c:\\Data\\Python', 'e:\\Data\\Python','c:\\Python','e:\\Python']: if os.path.exists(p): PY_PATH = p break if PY_PATH and PY_PATH not in sys.path: sys.path.append(PY_PATH) </code></pre>
3
2009-06-08T16:36:05Z
[ "python", "symbian", "nokia", "s60", "pys60" ]
FIFO (named pipe) messaging obstacles
927,233
<p>I plan to use Unix named pipes (mkfifo) for simple multi-process messaging. A message would be just a single line of text.</p> <p>Would you discourage me from that? What obstacles should I expect?</p> <p>I have noticed these limitations:</p> <ol> <li>A sender cannot continue until the message is received.</li> <li>A receiver is blocked until there are some data. Nonblocking IO would be needed when we need to stop the reading. For example, another thread could ask for that.</li> <li>The receiver could obtain many messages in a single read. These have to be processed before quiting.</li> <li>The max length of an atomic message is limited by 4096 bytes. That is the PIPE_BUF limit on Linux (see man 7 pipe).</li> </ol> <p>I will implement the messaging in Python. But the obstacles hold in general.</p>
1
2009-05-29T17:35:45Z
927,281
<ol> <li>Lack of portability - they are mainly a Unix thing. Sockets are more portable.</li> <li>Harder to scale out to multiple systems (another sockets+)</li> <li>On the other hand, I believe pipes are faster than sockets for processes on the same machine (less communication overhead).</li> </ol> <p>As to your limitations,</p> <ol> <li>You can "<a href="http://docs.python.org/library/select.html" rel="nofollow">select</a>" on pipes, to do a non-blocking read.</li> <li>I normally (in perl) print out my messages on pipes seperated by "\n", and read a line from them to get one message at a time.</li> <li>Do be careful with the atomic length.</li> </ol> <p>I find <a href="http://search.cpan.org/~nwclark/perl-5.8.9/pod/perlipc.pod" rel="nofollow">perlipc</a> to be a good discussion between the various options, though it has perl specific code.</p>
4
2009-05-29T17:53:36Z
[ "python", "linux", "unix", "pipe", "named-pipes" ]