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 |
|---|---|---|---|---|---|---|---|---|---|
a question on for loops in python
| 588,052
|
<p>I want to calaculate pythagorean triplets(code below) and I want to calculate infinitly how do I do it without using the three for loops? Could I use a for loop in some way? thanks.</p>
<pre><code>import math
def main():
for x in range (10000, 1000):
for y in range (10000, 1000):
for z in range(10000, 1000):
if x*x == y*y + z*z:
print y, z, x
print '-'*50
if __name__ == '__main__':
main()
</code></pre>
| 3
|
2009-02-25T21:47:41Z
| 588,915
|
<p>At least three loops are needed for infinity. To make something flexible takes a ton of loops. This example is a solution to <a href="http://projecteuler.net/index.php?section=problems&id=9" rel="nofollow">Project Euler Problem 9</a> and more.</p>
<pre><code>#!/usr/bin/env python
def fcount(start=1):
n = float(start)
while True:
yield n
n += 1
def find_triples():
for c in fcount():
for b in fcount():
if b > c:
break
for a in fcount():
if a > b:
break
if a ** 2 + b ** 2 == c ** 2:
yield (a, b, c)
def triples_by_sum(targetsum):
for a, b, c in find_triples():
if a + b + c == targetsum:
yield a, b, c
if c > targetsum:
break
if __name__ == '__main__':
# Finds multiple triples
for a, b, c in triples_by_sum(252):
print a, b, c
# Finds single triples
a, b, c = triples_by_sum(1000).next()
print a, b, c
# Goes forever
for a, b, c in find_triples():
print a, b, c
</code></pre>
| 0
|
2009-02-26T02:52:46Z
|
[
"python",
"for-loop"
] |
a question on for loops in python
| 588,052
|
<p>I want to calaculate pythagorean triplets(code below) and I want to calculate infinitly how do I do it without using the three for loops? Could I use a for loop in some way? thanks.</p>
<pre><code>import math
def main():
for x in range (10000, 1000):
for y in range (10000, 1000):
for z in range(10000, 1000):
if x*x == y*y + z*z:
print y, z, x
print '-'*50
if __name__ == '__main__':
main()
</code></pre>
| 3
|
2009-02-25T21:47:41Z
| 6,937,631
|
<p>How about use itertools.product instead?</p>
<pre><code># range is [10000, 1000)
for x, y, z in itertools.product(range(10000, 1000, -1), repeat=3):
if x * x == y * y + z * z:
print(y, z, x)
</code></pre>
<p>with a litter bit optimize:</p>
<pre><code>for x, y, z in itertools.product(range(10000, 1000, -1), repeat=3):
if y >= x or z >= x or x >= (y + z) or z < y:
continue
if x * x == y * y + z * z:
print(y, z, x)
</code></pre>
<p>EDIT:Here I just give a way to use <code>product</code> instead of multiple for loop. And you can find more efficient method in above posts.</p>
| 0
|
2011-08-04T07:22:53Z
|
[
"python",
"for-loop"
] |
Is there a Django apps pattern equivalent in Google App Engine?
| 588,342
|
<p>Django has a very handy pattern known as "apps". Essentially, a self-contained plug-in that requires a minimal amount of wiring, configuring, and glue code to integrate into an existing project. Examples are tagging, comments, contact-form, etc. They let you build up large projects by gathering together a collection of useful apps, rather than writing everything from scratch. The apps you <em>do</em> end up writing can be made portable so you can recycle them in other projects.</p>
<p>Does this pattern exist in Google App Engine? Is there any way to create self-contained apps that can be easily be dropped into an App Engine project? Right off the bat, the YAML url approach looks like it could require a significant re-imagining to the way its done in Django.</p>
<p>Note: I know I can run Django on App Engine, but that's not what I'm interested in doing this time around.</p>
| 3
|
2009-02-25T23:09:54Z
| 591,169
|
<p>The Django implementation of <em>apps</em> is closely tied to Django operation as a framework - I mean plugging application using Django url mapping features (for mapping urls to view functions) and Django application component discovery (for discovering models and admin configuration). There is no such mechanisms in WebApp (I guess you think of WebApp <em>framework</em> when you refer to AppEngine, which is rather <em>platform</em>) itself - you have to write them by yourself then persuade people to write such applications in a way that will work with your <em>url plugger</em> and <em>component discovery</em> after plugging app to the rest of site code.</p>
<p>There are generic <em>pluggable modules</em>, ready to use with AppEngine, like sharded counters or GAE utilities library, but they do not provide such level of functionality like Django apps (django-registration for example). I thing this comes from much greater freedom of design (basically, on GAE you can model your app after Django layout or after any other you might think of) and lack of widely used conventions.</p>
| 3
|
2009-02-26T15:59:04Z
|
[
"python",
"django",
"design-patterns",
"google-app-engine",
"django-apps"
] |
Is there a Django apps pattern equivalent in Google App Engine?
| 588,342
|
<p>Django has a very handy pattern known as "apps". Essentially, a self-contained plug-in that requires a minimal amount of wiring, configuring, and glue code to integrate into an existing project. Examples are tagging, comments, contact-form, etc. They let you build up large projects by gathering together a collection of useful apps, rather than writing everything from scratch. The apps you <em>do</em> end up writing can be made portable so you can recycle them in other projects.</p>
<p>Does this pattern exist in Google App Engine? Is there any way to create self-contained apps that can be easily be dropped into an App Engine project? Right off the bat, the YAML url approach looks like it could require a significant re-imagining to the way its done in Django.</p>
<p>Note: I know I can run Django on App Engine, but that's not what I'm interested in doing this time around.</p>
| 3
|
2009-02-25T23:09:54Z
| 622,150
|
<p>I'd like to add that you can run Django apps inside App Engine. I've been doing this successfully for the last few months. Basically, you can make use of the <a href="http://code.google.com/appengine/articles/appengine%5Fhelper%5Ffor%5Fdjango.html" rel="nofollow">App Engine Helper</a> project or <a href="http://code.google.com/appengine/articles/app-engine-patch.html" rel="nofollow">App Engine Patcher</a>. The App Engine Helper is maintained, in part, by google employees, so that's the one I use, thought the App Engine Patcher's maintainer is always feverishly promoting and updating his project (perhaps a little too much :)</p>
| 2
|
2009-03-07T17:08:56Z
|
[
"python",
"django",
"design-patterns",
"google-app-engine",
"django-apps"
] |
How to produce a colored GUI in a console application?
| 588,622
|
<p>For the following questions, answers may be for C/C++, C#, or Python. I would like the answers to be cross platform if possible but I realize I will probably need <code>conio</code> or <code>ncurses</code></p>
<ol>
<li>How do I output colored text?</li>
<li>How would I do a GUI like <code>top</code> or <code>nethack</code> where certain things are "drawn" to certain spaces in the terminal? </li>
</ol>
<p>If possible a small oneliner code example would be great.</p>
| 4
|
2009-02-26T00:47:02Z
| 588,637
|
<p>Most terminal windows understand the ANSI escape sequences, which allow coloring, cursor movement etc. You can find a list of them <a href="http://en.wikipedia.org/wiki/ANSI%5Fescape%5Fcode" rel="nofollow">here</a>.</p>
<p>Use of these sequences can seem a bit "old school", but you can use them in cases where curses isn't really applicable. For example, I use the folowing function in my bash scripts to display error messages in red:</p>
<pre><code>color_red()
{
echo -e "\033[01;31m$1\033[00m"
}
</code></pre>
<p>You can then say things like:</p>
<pre><code>color_red "something has gone horribly wrong!"
exit 1
</code></pre>
| 1
|
2009-02-26T00:53:24Z
|
[
"c#",
"c++",
"python",
"c",
"console-application"
] |
How to produce a colored GUI in a console application?
| 588,622
|
<p>For the following questions, answers may be for C/C++, C#, or Python. I would like the answers to be cross platform if possible but I realize I will probably need <code>conio</code> or <code>ncurses</code></p>
<ol>
<li>How do I output colored text?</li>
<li>How would I do a GUI like <code>top</code> or <code>nethack</code> where certain things are "drawn" to certain spaces in the terminal? </li>
</ol>
<p>If possible a small oneliner code example would be great.</p>
| 4
|
2009-02-26T00:47:02Z
| 588,642
|
<p>Yes, these are VT100 escape codes. The simplest thing is to use some flavor of Curses. Once, you choose a curses flavor it is pretty simple to do both 1 and 2.</p>
<p>Here's a HowTo on ncurses.</p>
<p><a href="http://web.cs.mun.ca/~rod/ncurses/ncurses.html" rel="nofollow">http://web.cs.mun.ca/~rod/ncurses/ncurses.html</a></p>
| 4
|
2009-02-26T00:54:26Z
|
[
"c#",
"c++",
"python",
"c",
"console-application"
] |
How to produce a colored GUI in a console application?
| 588,622
|
<p>For the following questions, answers may be for C/C++, C#, or Python. I would like the answers to be cross platform if possible but I realize I will probably need <code>conio</code> or <code>ncurses</code></p>
<ol>
<li>How do I output colored text?</li>
<li>How would I do a GUI like <code>top</code> or <code>nethack</code> where certain things are "drawn" to certain spaces in the terminal? </li>
</ol>
<p>If possible a small oneliner code example would be great.</p>
| 4
|
2009-02-26T00:47:02Z
| 588,645
|
<p>Not cross platform but for Windows / C# colour, see</p>
<p><a href="http://www.daniweb.com/code/snippet134.html" rel="nofollow">Color your Console text (C#)</a></p>
<p><a href="http://www.daniweb.com/code/snippet83.html" rel="nofollow">c++</a></p>
| 0
|
2009-02-26T00:55:32Z
|
[
"c#",
"c++",
"python",
"c",
"console-application"
] |
How to produce a colored GUI in a console application?
| 588,622
|
<p>For the following questions, answers may be for C/C++, C#, or Python. I would like the answers to be cross platform if possible but I realize I will probably need <code>conio</code> or <code>ncurses</code></p>
<ol>
<li>How do I output colored text?</li>
<li>How would I do a GUI like <code>top</code> or <code>nethack</code> where certain things are "drawn" to certain spaces in the terminal? </li>
</ol>
<p>If possible a small oneliner code example would be great.</p>
| 4
|
2009-02-26T00:47:02Z
| 588,648
|
<p>From this point of view, the console is in many ways just an emulation of a classic terminal device. Curses was created originally to support a way of doing common operations on different terminal types, where the actual terminal in use could be selected by the user as part of the login sequence. That heritage survives today in ncurses. </p>
<p>The ncurses library provides functions to call to directly position the cursor and emit text, and it is known to work for the Windows Console (where CMD.EXE runs), as well as on various *nix platform equivalents such as XTerms and the like. It probably even works with a true Dec VT100 over a serial line if you had such a thing...</p>
<p>The escape sequences understood by the VT100 and later models became the basis for the ANSI standard terminal. But you really don't want to have to know about that. Use ncurses and you won't have to.</p>
<p>Leaning on conio won't get you cross platform, as that is a DOS/Windows specific API.</p>
<p><strong>Edit:</strong> Apparently the <a href="http://www.gnu.org/software/ncurses/" rel="nofollow">ncurses</a> library itself is not easily built on mingw, at least as observed from a quick attempt to Google it up. However, all is not lost, as ncurses is only one of the descendants of the original <a href="http://en.wikipedia.org/wiki/Curses%5F%28programming%5Flibrary%29" rel="nofollow">curses</a> library. </p>
<p>Another is <a href="http://pdcurses.sourceforge.net/" rel="nofollow">PDCurses</a> which <em>is</em> known to compile and run for Windows Consoles, as well as for X11 and a variety of *nix platforms.</p>
<p>(I was just reminded from chasing references at Wikipedia that curses came out of writing the game rogue, which is the ancestor of nethack. Some of its code was "borrowed" from the cursor management module of the vi editor, as well. So spelunking in the <a href="http://www.nethack.org/v343/download-src.html" rel="nofollow">nethack source kit</a> for ideas may not be a crazy idea at all...)</p>
| 1
|
2009-02-26T00:56:19Z
|
[
"c#",
"c++",
"python",
"c",
"console-application"
] |
How to produce a colored GUI in a console application?
| 588,622
|
<p>For the following questions, answers may be for C/C++, C#, or Python. I would like the answers to be cross platform if possible but I realize I will probably need <code>conio</code> or <code>ncurses</code></p>
<ol>
<li>How do I output colored text?</li>
<li>How would I do a GUI like <code>top</code> or <code>nethack</code> where certain things are "drawn" to certain spaces in the terminal? </li>
</ol>
<p>If possible a small oneliner code example would be great.</p>
| 4
|
2009-02-26T00:47:02Z
| 588,652
|
<p>In C#, you can set the text color and the background color via the Console.ForegroundColor and Console.BackgroundColor properties, respectively. For a list of valid colors, see this <a href="http://msdn.microsoft.com/en-us/library/system.consolecolor.aspx" rel="nofollow">MSDN doc</a>.</p>
| 0
|
2009-02-26T00:57:00Z
|
[
"c#",
"c++",
"python",
"c",
"console-application"
] |
Python Daemon Packaging Best Practices
| 588,749
|
<p>I have a tool which I have written in python and generally should be run as a daemon. What are the best practices for packaging this tool for distribution, particularly how should settings files and the daemon executable/script be handled?</p>
<p>Relatedly are there any common tools for setting up the daemon for running on boot as appropriate for the given platform (i.e. <em>init</em> scripts on linux, services on windows, <em>launchd</em> on os x)?</p>
| 23
|
2009-02-26T01:32:39Z
| 588,780
|
<p>The best tool I found for helping with init.d scripts is "start-stop-daemon". It will run any application, monitor run/pid files, create them when necessary, provide ways to stop the daemon, set process user/group ids, and can even background your process.</p>
<p>For example, this is a script which can start/stop a wsgi server:</p>
<pre><code>#! /bin/bash
case "$1" in
start)
echo "Starting server"
# Activate the virtual environment
. /home/ali/wer-gcms/g-env/bin/activate
# Run start-stop-daemon, the $DAEMON variable contains the path to the
# application to run
start-stop-daemon --start --pidfile $WSGI_PIDFILE \
--user www-data --group www-data \
--chuid www-data \
--exec "$DAEMON"
;;
stop)
echo "Stopping WSGI Application"
# Start-stop daemon can also stop the application by sending sig 15
# (configurable) to the process id contained in the run/pid file
start-stop-daemon --stop --pidfile $WSGI_PIDFILE --verbose
;;
*)
# Refuse to do other stuff
echo "Usage: /etc/init.d/wsgi-application.sh {start|stop}"
exit 1
;;
esac
exit 0
</code></pre>
<p>You can also see there an example of how to use it with a virtualenv, which I would always recommend.</p>
| 14
|
2009-02-26T01:46:15Z
|
[
"python",
"packaging",
"setuptools",
"distutils"
] |
Python Daemon Packaging Best Practices
| 588,749
|
<p>I have a tool which I have written in python and generally should be run as a daemon. What are the best practices for packaging this tool for distribution, particularly how should settings files and the daemon executable/script be handled?</p>
<p>Relatedly are there any common tools for setting up the daemon for running on boot as appropriate for the given platform (i.e. <em>init</em> scripts on linux, services on windows, <em>launchd</em> on os x)?</p>
| 23
|
2009-02-26T01:32:39Z
| 588,800
|
<p>"generally should be run as a daemon?"</p>
<p>Doesn't -- on surface -- make a lot of sense. "Generally" isn't sensible. It's either a a daemon or not. You might want to update your question.</p>
<p>For examples of daemons, read up on daemons like Apache's httpd or any database server (they're daemons) or the SMTPD mail daemon.</p>
<p>Or, perhaps, read up on something simpler, like the FTP daemon, SSH daemon, Telnet daemon.</p>
<p>In Linux world, you'll have your application installation directory, some working directory, plus the configuration file directories.</p>
<p>We use <code>/opt/ourapp</code> for the application (it's Python, but we don't install in Python's <code>lib/site-packages</code>)</p>
<p>We use <code>/var/ourapp</code> for working files and our configuration files. </p>
<p>We could use <code>/etc/ourapp</code> for configuration files -- it would be consistent -- but we don't.</p>
<p>We don't -- yet -- use the <code>init.d</code> scripts for startup. But that's the final piece, automated startup. For now, we have sys admins start the daemons.</p>
<p>This is based, partly, on <a href="http://www.pathname.com/fhs/" rel="nofollow">http://www.pathname.com/fhs/</a> and <a href="http://tldp.org/LDP/Linux-Filesystem-Hierarchy/html/Linux-Filesystem-Hierarchy.html" rel="nofollow">http://tldp.org/LDP/Linux-Filesystem-Hierarchy/html/Linux-Filesystem-Hierarchy.html</a>.</p>
| -10
|
2009-02-26T01:52:47Z
|
[
"python",
"packaging",
"setuptools",
"distutils"
] |
Python Daemon Packaging Best Practices
| 588,749
|
<p>I have a tool which I have written in python and generally should be run as a daemon. What are the best practices for packaging this tool for distribution, particularly how should settings files and the daemon executable/script be handled?</p>
<p>Relatedly are there any common tools for setting up the daemon for running on boot as appropriate for the given platform (i.e. <em>init</em> scripts on linux, services on windows, <em>launchd</em> on os x)?</p>
| 23
|
2009-02-26T01:32:39Z
| 588,835
|
<p>On Linux systems, the system's package manager (Portage for Gentoo, Aptitude for Ubuntu/Debian, yum for Fedora, etc.) usually takes care of installing the program including placing init scripts in the right places. If you want to distribute your program for Linux, you might want to look into bundling it up into the proper format for various distributions' package managers.</p>
<p>This advice is obviously irrelevant on systems which don't have package managers (Windows, and Mac I think).</p>
| 0
|
2009-02-26T02:09:29Z
|
[
"python",
"packaging",
"setuptools",
"distutils"
] |
Python Daemon Packaging Best Practices
| 588,749
|
<p>I have a tool which I have written in python and generally should be run as a daemon. What are the best practices for packaging this tool for distribution, particularly how should settings files and the daemon executable/script be handled?</p>
<p>Relatedly are there any common tools for setting up the daemon for running on boot as appropriate for the given platform (i.e. <em>init</em> scripts on linux, services on windows, <em>launchd</em> on os x)?</p>
| 23
|
2009-02-26T01:32:39Z
| 588,891
|
<p>There are many snippets on the internet offering to write a daemon in pure python (no bash scripts)</p>
<p><a href="http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/">http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/</a>
looks clean...</p>
<p>If you want to write your own,<br />
the principle is the same as with the bash daemon function.</p>
<p>Basically:</p>
<p><strong>On start:</strong></p>
<ul>
<li>you fork to another process</li>
<li>open a logfile to redirect your
stdout and stderr </li>
<li>Save the pid somewhere.</li>
</ul>
<p><strong>On stop:</strong></p>
<ul>
<li>You send SIGTERM to the process with pid stored in your pidfile.</li>
<li>With signal.signal(signal.SIGTERM, sigtermhandler) you can bind a stopping
procedure to the SIGTERM signal.</li>
</ul>
<p>I don't know any widely used package doing this though.</p>
| 8
|
2009-02-26T02:44:33Z
|
[
"python",
"packaging",
"setuptools",
"distutils"
] |
Python Daemon Packaging Best Practices
| 588,749
|
<p>I have a tool which I have written in python and generally should be run as a daemon. What are the best practices for packaging this tool for distribution, particularly how should settings files and the daemon executable/script be handled?</p>
<p>Relatedly are there any common tools for setting up the daemon for running on boot as appropriate for the given platform (i.e. <em>init</em> scripts on linux, services on windows, <em>launchd</em> on os x)?</p>
| 23
|
2009-02-26T01:32:39Z
| 588,904
|
<p>To answer one part of your question, there are no tools I know of that will do daemon setup portably even across Linux systems let alone Windows or Mac OS X.</p>
<p>Most Linux distributions seem to be using <code>start-stop-daemon</code> within init scripts now, but you're still going to have minor difference in filesystem layout and big differences in packaging. Using autotools/configure, or distutils/easy_install if your project is all Python, will go a long way to making it easier to build packages for different Linux/BSD distributions.</p>
<p>Windows is a whole different game and will require <a href="http://starship.python.net/crew/mhammond/">Mark Hammond's win32</a> extensions and maybe <a href="http://timgolden.me.uk/python/wmi.html">Tim Golden's WMI</a> extensions.</p>
<p>I don't know Launchd except that "none of the above" are relevant.</p>
<p>For tips on daemonizing Python scripts, I would look to Python apps that are actually doing it in the real world, for example inside Twisted.</p>
| 11
|
2009-02-26T02:48:06Z
|
[
"python",
"packaging",
"setuptools",
"distutils"
] |
Python Daemon Packaging Best Practices
| 588,749
|
<p>I have a tool which I have written in python and generally should be run as a daemon. What are the best practices for packaging this tool for distribution, particularly how should settings files and the daemon executable/script be handled?</p>
<p>Relatedly are there any common tools for setting up the daemon for running on boot as appropriate for the given platform (i.e. <em>init</em> scripts on linux, services on windows, <em>launchd</em> on os x)?</p>
| 23
|
2009-02-26T01:32:39Z
| 591,832
|
<p>I can't remember where I downloaded it... but this is the best daemonizing script that I've found. It works beautifully (on Mac and Linux.) (save it as daemonize.py)</p>
<pre><code>import sys, os
def daemonize (stdin='/dev/null', stdout='/dev/null', stderr='/dev/null'):
# Perform first fork.
try:
pid = os.fork( )
if pid > 0:
sys.exit(0) # Exit first parent.
except OSError, e:
sys.stderr.write("fork #1 failed: (%d) %sn" % (e.errno, e.strerror))
sys.exit(1)
# Decouple from parent environment.
os.chdir("/")
os.umask(0)
os.setsid( )
# Perform second fork.
try:
pid = os.fork( )
if pid > 0:
sys.exit(0) # Exit second parent.
except OSError, e:
sys.stderr.write("fork #2 failed: (%d) %sn" % (e.errno, e.strerror))
sys.exit(1)
# The process is now daemonized, redirect standard file descriptors.
for f in sys.stdout, sys.stderr: f.flush( )
si = file(stdin, 'r')
so = file(stdout, 'a+')
se = file(stderr, 'a+', 0)
os.dup2(si.fileno( ), sys.stdin.fileno( ))
os.dup2(so.fileno( ), sys.stdout.fileno( ))
os.dup2(se.fileno( ), sys.stderr.fileno( ))
</code></pre>
<p>In your script, you would simply:</p>
<pre><code>from daemonize import daemonize
daemonize()
</code></pre>
<p>And you can also specify places to redirect the stdio, err, etc...</p>
| 2
|
2009-02-26T18:29:22Z
|
[
"python",
"packaging",
"setuptools",
"distutils"
] |
Python Daemon Packaging Best Practices
| 588,749
|
<p>I have a tool which I have written in python and generally should be run as a daemon. What are the best practices for packaging this tool for distribution, particularly how should settings files and the daemon executable/script be handled?</p>
<p>Relatedly are there any common tools for setting up the daemon for running on boot as appropriate for the given platform (i.e. <em>init</em> scripts on linux, services on windows, <em>launchd</em> on os x)?</p>
| 23
|
2009-02-26T01:32:39Z
| 1,962,593
|
<p>Not a silver bullet for what you're asking, but check out <a href="http://supervisord.org/" rel="nofollow" title="supervisord">supervisord</a>. It handles all the fun bits of managing processes. I use it heavily in a large production environment. Also, it's written in Python!</p>
| 3
|
2009-12-26T04:03:37Z
|
[
"python",
"packaging",
"setuptools",
"distutils"
] |
Python Daemon Packaging Best Practices
| 588,749
|
<p>I have a tool which I have written in python and generally should be run as a daemon. What are the best practices for packaging this tool for distribution, particularly how should settings files and the daemon executable/script be handled?</p>
<p>Relatedly are there any common tools for setting up the daemon for running on boot as appropriate for the given platform (i.e. <em>init</em> scripts on linux, services on windows, <em>launchd</em> on os x)?</p>
| 23
|
2009-02-26T01:32:39Z
| 2,847,591
|
<p>Check the Ben Finney's daemon module. He has started to write a PEP targeting python 3.X:</p>
<p><a href="http://www.python.org/dev/peps/pep-3143/">http://www.python.org/dev/peps/pep-3143/</a></p>
<p>But an implementation is already available here :</p>
<p><a href="http://pypi.python.org/pypi/python-daemon/">http://pypi.python.org/pypi/python-daemon/</a></p>
| 5
|
2010-05-17T08:31:26Z
|
[
"python",
"packaging",
"setuptools",
"distutils"
] |
Python Daemon Packaging Best Practices
| 588,749
|
<p>I have a tool which I have written in python and generally should be run as a daemon. What are the best practices for packaging this tool for distribution, particularly how should settings files and the daemon executable/script be handled?</p>
<p>Relatedly are there any common tools for setting up the daemon for running on boot as appropriate for the given platform (i.e. <em>init</em> scripts on linux, services on windows, <em>launchd</em> on os x)?</p>
| 23
|
2009-02-26T01:32:39Z
| 8,817,383
|
<p>This <a href="http://jimmyg.org/blog/2010/python-daemon-init-script.html" rel="nofollow">blog entry</a> made it clear for me that there are actually two common ways to have your Python program run as a deamon (I hadn't figured that out so clearly from the existing answers):</p>
<blockquote>
<p>There are two approaches to writing daemon applications like servers
in Python. </p>
<ul>
<li>The first is to <strong>handle all the tasks of sarting and
stopping daemons in Python code itself</strong>. The easiest way to do this is
with the <code>python-daemon</code> package which might eventually make its way
into the Python distribution. </li>
</ul>
</blockquote>
<p><a href="http://stackoverflow.com/a/588891/50899">Poeljapon's answer</a> is an example of this 1st approach, although it doesn't use the <code>python-daemon</code> package, but links to a custom but very clean python script.</p>
<blockquote>
<ul>
<li>The other approach is to <strong>use the tools
supplied by the operating system</strong>. In the case of Debain, this means
writing an init script which makes use of the <code>start-stop-daemon</code>
program.</li>
</ul>
</blockquote>
<p><a href="http://stackoverflow.com/a/588780/50899">Ali Afshar's answer</a> is a shell script example of the 2nd approach, using the <code>start-stop-daemon</code>.</p>
<p>The blog entry I quoted has a shell script example, and some additional details on things such as starting your daemon at system startup and restarting your daemon automatically when it stopped for any reason.</p>
| 0
|
2012-01-11T10:02:48Z
|
[
"python",
"packaging",
"setuptools",
"distutils"
] |
Python persistent Popen
| 589,093
|
<p>Is there a way to do multiple calls in the same "session" in Popen? For instance, can I make a call through it and then another one after it without having to concatenate the commands into one long string?</p>
| 3
|
2009-02-26T04:19:43Z
| 589,104
|
<blockquote>
<p>For instance, can I make a call through it and then another one after it without having to concatenate the commands into one long string?</p>
</blockquote>
<p>Sounds like you're using shell=True. Don't, unless you need to. Instead use shell=False (the default) and pass in a command/arg list.</p>
<blockquote>
<p>Is there a way to do multiple calls in the same "session" in Popen? For instance, can I make a call through it and then another one after it without having to concatenate the commands into one long string?</p>
</blockquote>
<p>Any reason you can't just create two Popen instances and wait/communicate on each as necessary? That's the normal way to do it, if I understand you correctly.</p>
| 0
|
2009-02-26T04:24:14Z
|
[
"python",
"subprocess",
"popen"
] |
Python persistent Popen
| 589,093
|
<p>Is there a way to do multiple calls in the same "session" in Popen? For instance, can I make a call through it and then another one after it without having to concatenate the commands into one long string?</p>
| 3
|
2009-02-26T04:19:43Z
| 589,282
|
<p>You're not "making a call" when you use popen, you're running an executable and talking to it over stdin, stdout, and stderr. If the executable has some way of doing a "session" of work (for instance, by reading lines from stdin) then, yes, you can do it. Otherwise, you'll need to exec multiple times.</p>
<p>subprocess.Popen is (mostly) just a wrapper around execvp(3)</p>
| 3
|
2009-02-26T05:59:09Z
|
[
"python",
"subprocess",
"popen"
] |
Python persistent Popen
| 589,093
|
<p>Is there a way to do multiple calls in the same "session" in Popen? For instance, can I make a call through it and then another one after it without having to concatenate the commands into one long string?</p>
| 3
|
2009-02-26T04:19:43Z
| 589,312
|
<p>Assuming you want to be able to run a shell and send it multiple commands (and read their output), it appears you can do something like this:</p>
<pre><code>from subprocess import *
p = Popen(['/bin/sh'], shell=False, stdin=PIPE, stdout=PIPE, stderr=PIPE)
</code></pre>
<p>After which, e.g.,:</p>
<pre><code>>>> p.stdin.write("cat /etc/motd\n")
>>> p.stdout.readline()
'Welcome to dev-linux.mongo.com.\n'
</code></pre>
<p>(Of course, you should check <code>stderr</code> too, or else ask <code>Popen</code> to merge it with <code>stdout</code>). One major <strong>problem</strong> with the above is that the <code>stdin</code> and <code>stdout</code> pipes are in blocking mode, so it's easy to get "stuck" waiting forever for output from the shell. Although I haven't tried it, there's a <a href="http://code.activestate.com/recipes/440554/" rel="nofollow">recipe</a> at the ActiveState site that shows how to address this.</p>
<p><strong>Update</strong>: after looking at the related questions/answers, it looks like it might be simpler to just use Python's built-in <code>select</code> module to see if there's data to read on <code>stdout</code> (you should also do the same for <code>stderr</code>, of course), e.g.:</p>
<pre><code>>>> select.select([p.stdout], [], [], 0)
([<open file '<fdopen>', mode 'rb' at 0x10341690>], [], [])
</code></pre>
| 0
|
2009-02-26T06:09:06Z
|
[
"python",
"subprocess",
"popen"
] |
Miminal Linux For a Pylons Web App?
| 589,115
|
<p>I am going to be building a Pylons-based web application. For this purpose, I'd like to build a minimal Linux platform, upon which I would then install the necessary packages such as Python and Pylons, and other necessary dependencies. The other reason to keep it minimal is because this machine will be virtual, probably over KVM, and will eventually be replicated in some cloud environment.</p>
<p>What would you use to do this? I am thinking of using Fedora 10's AOS iso, but would love to understand all my options.</p>
| 2
|
2009-02-26T04:33:49Z
| 589,127
|
<p>I really like <a href="http://www.ubuntu.com/products/whatisubuntu/serveredition/jeos" rel="nofollow">JeOS</a> "Just enough OS" which is a minimal distribution of the Ubuntu Server Edition.</p>
| 8
|
2009-02-26T04:37:24Z
|
[
"python",
"linux",
"pylons"
] |
Miminal Linux For a Pylons Web App?
| 589,115
|
<p>I am going to be building a Pylons-based web application. For this purpose, I'd like to build a minimal Linux platform, upon which I would then install the necessary packages such as Python and Pylons, and other necessary dependencies. The other reason to keep it minimal is because this machine will be virtual, probably over KVM, and will eventually be replicated in some cloud environment.</p>
<p>What would you use to do this? I am thinking of using Fedora 10's AOS iso, but would love to understand all my options.</p>
| 2
|
2009-02-26T04:33:49Z
| 589,638
|
<p>debootstrap is your friend.</p>
| 0
|
2009-02-26T08:25:41Z
|
[
"python",
"linux",
"pylons"
] |
Miminal Linux For a Pylons Web App?
| 589,115
|
<p>I am going to be building a Pylons-based web application. For this purpose, I'd like to build a minimal Linux platform, upon which I would then install the necessary packages such as Python and Pylons, and other necessary dependencies. The other reason to keep it minimal is because this machine will be virtual, probably over KVM, and will eventually be replicated in some cloud environment.</p>
<p>What would you use to do this? I am thinking of using Fedora 10's AOS iso, but would love to understand all my options.</p>
| 2
|
2009-02-26T04:33:49Z
| 589,645
|
<p>Damn Small Linux? Slax?</p>
| 0
|
2009-02-26T08:28:15Z
|
[
"python",
"linux",
"pylons"
] |
Miminal Linux For a Pylons Web App?
| 589,115
|
<p>I am going to be building a Pylons-based web application. For this purpose, I'd like to build a minimal Linux platform, upon which I would then install the necessary packages such as Python and Pylons, and other necessary dependencies. The other reason to keep it minimal is because this machine will be virtual, probably over KVM, and will eventually be replicated in some cloud environment.</p>
<p>What would you use to do this? I am thinking of using Fedora 10's AOS iso, but would love to understand all my options.</p>
| 2
|
2009-02-26T04:33:49Z
| 589,674
|
<p>If you want to go serious about the virtual appliance idea, take a look at the newly released <strong><a href="http://www.vmware.com/appliances/learn/vmware%5Fstudio.html" rel="nofollow">VMware Studio</a></strong>. It was built exactly for trimming down a system (only Linux for now afaik) so it provides only enough base to run your application. </p>
<p>VMware is going (a bit more) open by pushing an open virtual appliance format (<a href="http://www.vmware.com/appliances/learn/ovf.html" rel="nofollow">OVF</a>) so, at some point in the future, you might be able to run the result on other virtualization platforms too.</p>
| 0
|
2009-02-26T08:43:21Z
|
[
"python",
"linux",
"pylons"
] |
Miminal Linux For a Pylons Web App?
| 589,115
|
<p>I am going to be building a Pylons-based web application. For this purpose, I'd like to build a minimal Linux platform, upon which I would then install the necessary packages such as Python and Pylons, and other necessary dependencies. The other reason to keep it minimal is because this machine will be virtual, probably over KVM, and will eventually be replicated in some cloud environment.</p>
<p>What would you use to do this? I am thinking of using Fedora 10's AOS iso, but would love to understand all my options.</p>
| 2
|
2009-02-26T04:33:49Z
| 589,678
|
<p><a href="http://www.debian-administration.org/articles/426" rel="nofollow">Debootstrap</a>, or use <a href="http://www.redhat.com/docs/manuals/linux/RHL-7.3-Manual/custom-guide/ch-kickstart2.html" rel="nofollow">kickstart</a> to strap your FC domains. However, other methods of strapping an RPM based distro exist, such as Steve Kemp's <a href="http://rinse.repository.steve.org.uk/" rel="nofollow">rinse</a> utility that replaces rpmstrap.</p>
<p>Or, you could just grab something at <a href="http://jailtime.org" rel="nofollow">jailtime</a> to use as a base.</p>
<p>If that fails, download everything you need from source, build / install it with a /mydist prefix (including libc, etc) and test it via <a href="http://en.wikipedia.org/wiki/Chroot" rel="nofollow">chroot</a>.</p>
<p>I've been building templates for Xen for years .. its actually turned into a very fun hobby :)</p>
| 0
|
2009-02-26T08:44:15Z
|
[
"python",
"linux",
"pylons"
] |
Miminal Linux For a Pylons Web App?
| 589,115
|
<p>I am going to be building a Pylons-based web application. For this purpose, I'd like to build a minimal Linux platform, upon which I would then install the necessary packages such as Python and Pylons, and other necessary dependencies. The other reason to keep it minimal is because this machine will be virtual, probably over KVM, and will eventually be replicated in some cloud environment.</p>
<p>What would you use to do this? I am thinking of using Fedora 10's AOS iso, but would love to understand all my options.</p>
| 2
|
2009-02-26T04:33:49Z
| 590,001
|
<p>If you want to be able to remove all the cruft but still be using a âmainstreamâ distro rather than one cut down to aim at tiny devices, look at Slackware. You can happily remove stuff as low-level as sysvinit, cron and so on, without collapsing into dependency hell. And nothing in it relies on Perl or Python, so you can easily remove them (and install whichever version of Python your app prefers to use).</p>
| 1
|
2009-02-26T10:38:51Z
|
[
"python",
"linux",
"pylons"
] |
Miminal Linux For a Pylons Web App?
| 589,115
|
<p>I am going to be building a Pylons-based web application. For this purpose, I'd like to build a minimal Linux platform, upon which I would then install the necessary packages such as Python and Pylons, and other necessary dependencies. The other reason to keep it minimal is because this machine will be virtual, probably over KVM, and will eventually be replicated in some cloud environment.</p>
<p>What would you use to do this? I am thinking of using Fedora 10's AOS iso, but would love to understand all my options.</p>
| 2
|
2009-02-26T04:33:49Z
| 895,583
|
<blockquote>
<p>For this purpose, I'd like to build a minimal Linux platform...</p>
</blockquote>
<p>So Why not try to use ArchLinux www.archlinux.org?</p>
<p>Also you can use virtualenv with Pylons in it.</p>
| 1
|
2009-05-21T22:30:24Z
|
[
"python",
"linux",
"pylons"
] |
imploding a list for use in a python MySQLDB IN clause
| 589,284
|
<p>I know how to map a list to a string:</p>
<pre><code>foostring = ",".join( map(str, list_of_ids) )
</code></pre>
<p>And I know that I can use the following to get that string into an IN clause:</p>
<pre><code>cursor.execute("DELETE FROM foo.bar WHERE baz IN ('%s')" % (foostring))
</code></pre>
<p>What I need is to accomplish the same thing SAFELY (avoiding SQL injection) using MySQLDB. In the above example because foostring is not passed as an argument to execute, it is vulnerable. I also have to quote and escape outside of the mysql library. </p>
<p>(There is a <a href="http://stackoverflow.com/questions/315672/automagically-expanding-a-python-list-with-formatted-output">related SO question</a>, but the answers listed there either do not work for MySQLDB or are vulnerable to SQL injection.)</p>
| 35
|
2009-02-26T05:59:25Z
| 589,416
|
<p>Use the <code>list_of_ids</code> directly:</p>
<pre><code>format_strings = ','.join(['%s'] * len(list_of_ids))
cursor.execute("DELETE FROM foo.bar WHERE baz IN (%s)" % format_strings,
tuple(list_of_ids))
</code></pre>
<p>That way you avoid having to quote yourself, and avoid all kinds of sql injection.</p>
<p>Note that the data (<code>list_of_ids</code>) is going directly to mysql's driver, as a parameter (not in the query text) so there is no injection. You can leave any chars you want in the string, no need to remove or quote chars.</p>
| 68
|
2009-02-26T06:46:38Z
|
[
"python",
"mysql"
] |
imploding a list for use in a python MySQLDB IN clause
| 589,284
|
<p>I know how to map a list to a string:</p>
<pre><code>foostring = ",".join( map(str, list_of_ids) )
</code></pre>
<p>And I know that I can use the following to get that string into an IN clause:</p>
<pre><code>cursor.execute("DELETE FROM foo.bar WHERE baz IN ('%s')" % (foostring))
</code></pre>
<p>What I need is to accomplish the same thing SAFELY (avoiding SQL injection) using MySQLDB. In the above example because foostring is not passed as an argument to execute, it is vulnerable. I also have to quote and escape outside of the mysql library. </p>
<p>(There is a <a href="http://stackoverflow.com/questions/315672/automagically-expanding-a-python-list-with-formatted-output">related SO question</a>, but the answers listed there either do not work for MySQLDB or are vulnerable to SQL injection.)</p>
| 35
|
2009-02-26T05:59:25Z
| 13,542,147
|
<p>Pain-less MySQLdb <code>execute('...WHERE name1 = %s AND name2 IN (%s)', value1, values2)</code></p>
<pre><code>def execute(sql, *values):
assert sql.count('%s') == len(values), (sql, values)
placeholders = []
new_values = []
for value in values:
if isinstance(value, (list, tuple)):
placeholders.append(', '.join(['%s'] * len(value)))
new_values.extend(value)
else:
placeholders.append('%s')
new_values.append(value)
sql = sql % tuple(placeholders)
values = tuple(new_values)
# ... cursor.execute(sql, values)
</code></pre>
| 0
|
2012-11-24T14:28:18Z
|
[
"python",
"mysql"
] |
imploding a list for use in a python MySQLDB IN clause
| 589,284
|
<p>I know how to map a list to a string:</p>
<pre><code>foostring = ",".join( map(str, list_of_ids) )
</code></pre>
<p>And I know that I can use the following to get that string into an IN clause:</p>
<pre><code>cursor.execute("DELETE FROM foo.bar WHERE baz IN ('%s')" % (foostring))
</code></pre>
<p>What I need is to accomplish the same thing SAFELY (avoiding SQL injection) using MySQLDB. In the above example because foostring is not passed as an argument to execute, it is vulnerable. I also have to quote and escape outside of the mysql library. </p>
<p>(There is a <a href="http://stackoverflow.com/questions/315672/automagically-expanding-a-python-list-with-formatted-output">related SO question</a>, but the answers listed there either do not work for MySQLDB or are vulnerable to SQL injection.)</p>
| 35
|
2009-02-26T05:59:25Z
| 15,662,693
|
<p>As this person suggested (<a href="http://stackoverflow.com/questions/4574609/executing-select-where-in-using-mysqldb#comment18905458_4574647">Executing "SELECT ... WHERE ... IN ..." using MySQLdb</a>), it is faster to use itertools.repeat() to create the list of '%s's than to multiply a ['%s'] list (and much faster than using map()), especially for long lists.</p>
<pre><code>in_p = ', '.join(itertools.repeat('%s', len(args)))
</code></pre>
<p>These timeits were done using Python 2.7.3 with an Intel Core i5 CPU M 540 @ 2.53GHz à 4:</p>
<pre><code>>>> timeit.timeit("repeat('%s', len(short_list))", 'from itertools import repeat; short_list = range(3)')
0.20310497283935547
>>> timeit.timeit("['%s'] * len(short_list)", 'short_list = range(3)')
0.263930082321167
>>> timeit.timeit("list(map(lambda x:'%s', short_list))", 'short_list = range(3)')
0.7543060779571533
>>> timeit.timeit("repeat('%s', len(long_list))", 'from itertools import repeat; long_list = range(1000)')
0.20342397689819336
>>> timeit.timeit("['%s'] * len(long_list)", 'long_list = range(1000)')
4.700995922088623
>>> timeit.timeit("list(map(lambda x:'%s', long_list))", 'long_list = range(1000)')
100.05319118499756
</code></pre>
| -2
|
2013-03-27T15:26:58Z
|
[
"python",
"mysql"
] |
imploding a list for use in a python MySQLDB IN clause
| 589,284
|
<p>I know how to map a list to a string:</p>
<pre><code>foostring = ",".join( map(str, list_of_ids) )
</code></pre>
<p>And I know that I can use the following to get that string into an IN clause:</p>
<pre><code>cursor.execute("DELETE FROM foo.bar WHERE baz IN ('%s')" % (foostring))
</code></pre>
<p>What I need is to accomplish the same thing SAFELY (avoiding SQL injection) using MySQLDB. In the above example because foostring is not passed as an argument to execute, it is vulnerable. I also have to quote and escape outside of the mysql library. </p>
<p>(There is a <a href="http://stackoverflow.com/questions/315672/automagically-expanding-a-python-list-with-formatted-output">related SO question</a>, but the answers listed there either do not work for MySQLDB or are vulnerable to SQL injection.)</p>
| 35
|
2009-02-26T05:59:25Z
| 25,677,198
|
<pre><code>list_of_ids = [ 1, 2, 3]
query = "select * from table where x in %s" % str(tuple(list_of_ids))
print query
</code></pre>
<p>This could work for some use-cases if you don't wish to be concerned with the method in which you have to pass arguments to complete the query string and would like to invoke just <code>cursror.execute(query)</code>.</p>
<p>Another way could be: </p>
<pre><code>"select * from table where x in (%s)" % ', '.join(str(id) for id in list_of_ids)
</code></pre>
| 0
|
2014-09-05T01:01:05Z
|
[
"python",
"mysql"
] |
Python - How to check if a file is used by another application?
| 589,407
|
<p>I want to open a file which is periodically written to by another application. This application cannot be modified. I'd therefore like to only open the file when I know it is not been written to by an other application.</p>
<p>Is there a pythonic way to do this? Otherwise, how do I achieve this in Unix and Windows?</p>
<p><strong>edit</strong>: I'll try and clarify. <em>Is there a way to check if the current file has been opened by another application?</em></p>
<p>I'd like to start with this question. Whether those other application read/write is irrelevant for now.</p>
<p>I realize it is probably OS dependent, so this may not really be python related right now.</p>
| 8
|
2009-02-26T06:44:48Z
| 589,440
|
<p>Will your python script desire to open the file for writing or for reading? Is the legacy application opening and closing the file between writes, or does it keep it open?</p>
<p>It is extremely important that we understand what the legacy application is doing, and what your python script is attempting to achieve.</p>
<p>This area of functionality is highly OS-dependent, and the fact that you have no control over the legacy application only makes things harder unfortunately. Whether there is a pythonic or non-pythonic way of doing this will probably be the least of your concerns - the hard question will be whether what you are trying to achieve will be possible at all.</p>
<hr>
<p><strong>UPDATE</strong></p>
<p>OK, so knowing (from your comment) that:</p>
<blockquote>
<p>the legacy application is opening and
closing the file every X minutes, but
I do not want to assume that at t =
t_0 + n*X + eps it already closed
the file.</p>
</blockquote>
<p>then the problem's parameters are changed. It can actually be done in an OS-independent way given a few assumptions, or as a combination of OS-dependent and OS-independent techniques. :)</p>
<ol>
<li><strong>OS-independent way</strong>: if it is safe to assume that the legacy application keeps the file open for at most some known quantity of time, say <code>T</code> seconds (e.g. opens the file, performs one write, then closes the file), and re-opens it more or less every <code>X</code> seconds, where <code>X</code> is larger than 2*<code>T</code>.
<ul>
<li><code>stat</code> the file</li>
<li>subtract file's modification time from <code>now()</code>, yielding <code>D</code></li>
<li>if <code>T</code> <= <code>D</code> < <code>X</code> then open the file and do what you need with it</li>
<li><em>This may be safe enough for your application</em>. Safety increases as <code>T</code>/<code>X</code> decreases. On *nix you may have to double check <code>/etc/ntpd.conf</code> for proper time-stepping vs. slew configuration (see tinker). For Windows see <a href="http://support.microsoft.com/kb/223184" rel="nofollow">MSDN</a></li>
</ul></li>
<li><strong>Windows</strong>: in addition (or in-lieu) of the OS-independent method above, you may attempt to use either:
<ul>
<li>sharing (locking): this assumes that the legacy program also opens the file in shared mode (usually the default in Windows apps); moreover, if your application acquires the lock just as the legacy application is attempting the same (race condition), the legacy application will fail.
<ul>
<li>this is extremely intrusive and error prone. Unless both the new application and the legacy application need synchronized access for writing to the same file and you are willing to handle the possibility of the legacy application being denied opening of the file, do not use this method.</li>
</ul></li>
<li>attempting to find out what files are open in the legacy application, using the same techniques as <a href="http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx" rel="nofollow">ProcessExplorer</a> (the equivalent of *nix's <code>lsof</code>)
<ul>
<li>you are even more vulnerable to race conditions than the OS-independent technique</li>
</ul></li>
</ul></li>
<li><strong>Linux/etc.</strong>: in addition (or in-lieu) of the OS-independent method above, you may attempt to use the same technique as <code>lsof</code> or, on some systems, simply check which file the symbolic link <code>/proc/<pid>/fd/<fdes></code> points to
<ul>
<li>you are even more vulnerable to race conditions than the OS-independent technique</li>
<li>it is highly unlikely that the legacy application uses locking, but if it is, locking is not a real option unless the legacy application can handle a locked file gracefully (by blocking, not by failing - and if your own application can guarantee that the file will not remain locked, blocking the legacy application for extender periods of time.)</li>
</ul></li>
</ol>
<hr>
<p><strong>UPDATE 2</strong></p>
<p>If favouring the "check whether the legacy application has the file open" (intrusive approach prone to race conditions) then you can solve the said race condition by:</p>
<ol>
<li>checking whether the legacy application has the file open (a la <code>lsof</code> or <code>ProcessExplorer</code>)</li>
<li>suspending the legacy application process</li>
<li>repeating the check in step 1 to confirm that the legacy application did not open the file between steps 1 and 2; delay and restart at step 1 if so, otherwise proceed to step 4</li>
<li>doing your business on the file -- ideally simply renaming it for subsequent, independent processing in order to keep the legacy application suspended for a minimal amount of time</li>
<li>resuming the legacy application process</li>
</ol>
| 7
|
2009-02-26T06:55:28Z
|
[
"python",
"windows",
"unix",
"logging",
"file-io"
] |
Python - How to check if a file is used by another application?
| 589,407
|
<p>I want to open a file which is periodically written to by another application. This application cannot be modified. I'd therefore like to only open the file when I know it is not been written to by an other application.</p>
<p>Is there a pythonic way to do this? Otherwise, how do I achieve this in Unix and Windows?</p>
<p><strong>edit</strong>: I'll try and clarify. <em>Is there a way to check if the current file has been opened by another application?</em></p>
<p>I'd like to start with this question. Whether those other application read/write is irrelevant for now.</p>
<p>I realize it is probably OS dependent, so this may not really be python related right now.</p>
| 8
|
2009-02-26T06:44:48Z
| 589,445
|
<p>Unix does not have file locking as a default. The best suggestion I have for a Unix environment would be to look at the sources for the lsof command. It has deep knowledge about which process have which files open. You could use that as the basis of your solution. Here are the <a href="https://launchpad.net/ubuntu/%2Bsource/lsof" rel="nofollow">Ubuntu sources for lsof.</a></p>
| 0
|
2009-02-26T06:56:59Z
|
[
"python",
"windows",
"unix",
"logging",
"file-io"
] |
Python - How to check if a file is used by another application?
| 589,407
|
<p>I want to open a file which is periodically written to by another application. This application cannot be modified. I'd therefore like to only open the file when I know it is not been written to by an other application.</p>
<p>Is there a pythonic way to do this? Otherwise, how do I achieve this in Unix and Windows?</p>
<p><strong>edit</strong>: I'll try and clarify. <em>Is there a way to check if the current file has been opened by another application?</em></p>
<p>I'd like to start with this question. Whether those other application read/write is irrelevant for now.</p>
<p>I realize it is probably OS dependent, so this may not really be python related right now.</p>
| 8
|
2009-02-26T06:44:48Z
| 592,121
|
<p>One thing I've done is have python very temporarily rename the file. If we're able to rename it, then no other process is using it. I only tested this on Windows.</p>
| 0
|
2009-02-26T19:50:29Z
|
[
"python",
"windows",
"unix",
"logging",
"file-io"
] |
How to find a relative URL and translate it to an absolute URL in Python
| 589,833
|
<p>I extract some code from a web page (<a href="http://www.opensolaris.org/os/community/on/flag-days/all/" rel="nofollow">http://www.opensolaris.org/os/community/on/flag-days/all/</a>) like follows,</p>
<pre><code><tr class="build">
<th colspan="0">Build 110</th>
</tr>
<tr class="arccase project flagday">
<td>Feb-25</td>
<td></td>
<td></td>
<td></td>
<td>
<a href="../pages/2009022501/">Flag Day and Heads Up: Power Aware Dispatcher and Deep C-States</a><br />
cpupm keyword mode extensions - <a href="/os/community/arc/caselog/2008/777/">PSARC/2008/777</a><br />
CPU Deep Idle Keyword - <a href="/os/community/arc/caselog/2008/663/">PSARC/2008/663</a><br />
</td>
</tr>
</code></pre>
<p>and there are some relative url path in it, now I want to search it with regular expression and replace them with absolute url path. Since I know urljoin can do the replace work like that,</p>
<pre><code>>>> urljoin("http://www.opensolaris.org/os/community/on/flag-days/all/",
... "/os/community/arc/caselog/2008/777/")
'http://www.opensolaris.org/os/community/arc/caselog/2008/777/'
</code></pre>
<p>Now I want to know that how to search them using regular expressions, and finally tanslate the code to,</p>
<pre><code><tr class="build">
<th colspan="0">Build 110</th>
</tr>
<tr class="arccase project flagday">
<td>Feb-25</td>
<td></td>
<td></td>
<td></td>
<td>
<a href="http://www.opensolaris.org/os/community/on/flag-days/all//pages/2009022501/">Flag Day and Heads Up: Power Aware Dispatcher and Deep C-States</a><br />
cpupm keyword mode extensions - <a href="http://www.opensolaris.org/os/community/arc/caselog/2008/777/">PSARC/2008/777</a><br />
CPU Deep Idle Keyword - <a href="http://www.opensolaris.org/os/community/arc/caselog/2008/663/">PSARC/2008/663</a><br />
</td>
</tr>
</code></pre>
<p>My knowledge of regular expressions is so poor that I want to know how to do that. Thanks</p>
<p><strong>I have finished the work using Beautiful Soup, haha~ Thx for everybody!</strong></p>
| 2
|
2009-02-26T09:37:39Z
| 589,845
|
<p>I'm not sure about what you're trying to achieve but using the <a href="http://www.w3schools.com/TAGS/tag%5Fbase.asp">BASE tag in HTML</a> may do this trick for you without having to resort to regular expressions when doing the processing.</p>
| 6
|
2009-02-26T09:42:12Z
|
[
"python",
"regex"
] |
How to find a relative URL and translate it to an absolute URL in Python
| 589,833
|
<p>I extract some code from a web page (<a href="http://www.opensolaris.org/os/community/on/flag-days/all/" rel="nofollow">http://www.opensolaris.org/os/community/on/flag-days/all/</a>) like follows,</p>
<pre><code><tr class="build">
<th colspan="0">Build 110</th>
</tr>
<tr class="arccase project flagday">
<td>Feb-25</td>
<td></td>
<td></td>
<td></td>
<td>
<a href="../pages/2009022501/">Flag Day and Heads Up: Power Aware Dispatcher and Deep C-States</a><br />
cpupm keyword mode extensions - <a href="/os/community/arc/caselog/2008/777/">PSARC/2008/777</a><br />
CPU Deep Idle Keyword - <a href="/os/community/arc/caselog/2008/663/">PSARC/2008/663</a><br />
</td>
</tr>
</code></pre>
<p>and there are some relative url path in it, now I want to search it with regular expression and replace them with absolute url path. Since I know urljoin can do the replace work like that,</p>
<pre><code>>>> urljoin("http://www.opensolaris.org/os/community/on/flag-days/all/",
... "/os/community/arc/caselog/2008/777/")
'http://www.opensolaris.org/os/community/arc/caselog/2008/777/'
</code></pre>
<p>Now I want to know that how to search them using regular expressions, and finally tanslate the code to,</p>
<pre><code><tr class="build">
<th colspan="0">Build 110</th>
</tr>
<tr class="arccase project flagday">
<td>Feb-25</td>
<td></td>
<td></td>
<td></td>
<td>
<a href="http://www.opensolaris.org/os/community/on/flag-days/all//pages/2009022501/">Flag Day and Heads Up: Power Aware Dispatcher and Deep C-States</a><br />
cpupm keyword mode extensions - <a href="http://www.opensolaris.org/os/community/arc/caselog/2008/777/">PSARC/2008/777</a><br />
CPU Deep Idle Keyword - <a href="http://www.opensolaris.org/os/community/arc/caselog/2008/663/">PSARC/2008/663</a><br />
</td>
</tr>
</code></pre>
<p>My knowledge of regular expressions is so poor that I want to know how to do that. Thanks</p>
<p><strong>I have finished the work using Beautiful Soup, haha~ Thx for everybody!</strong></p>
| 2
|
2009-02-26T09:37:39Z
| 589,864
|
<p>Something like this should do it:</p>
<pre><code>"(?:[^/:"]+|/(?!/))(?:/[^/"]+)*"
</code></pre>
| 1
|
2009-02-26T09:48:14Z
|
[
"python",
"regex"
] |
How to find a relative URL and translate it to an absolute URL in Python
| 589,833
|
<p>I extract some code from a web page (<a href="http://www.opensolaris.org/os/community/on/flag-days/all/" rel="nofollow">http://www.opensolaris.org/os/community/on/flag-days/all/</a>) like follows,</p>
<pre><code><tr class="build">
<th colspan="0">Build 110</th>
</tr>
<tr class="arccase project flagday">
<td>Feb-25</td>
<td></td>
<td></td>
<td></td>
<td>
<a href="../pages/2009022501/">Flag Day and Heads Up: Power Aware Dispatcher and Deep C-States</a><br />
cpupm keyword mode extensions - <a href="/os/community/arc/caselog/2008/777/">PSARC/2008/777</a><br />
CPU Deep Idle Keyword - <a href="/os/community/arc/caselog/2008/663/">PSARC/2008/663</a><br />
</td>
</tr>
</code></pre>
<p>and there are some relative url path in it, now I want to search it with regular expression and replace them with absolute url path. Since I know urljoin can do the replace work like that,</p>
<pre><code>>>> urljoin("http://www.opensolaris.org/os/community/on/flag-days/all/",
... "/os/community/arc/caselog/2008/777/")
'http://www.opensolaris.org/os/community/arc/caselog/2008/777/'
</code></pre>
<p>Now I want to know that how to search them using regular expressions, and finally tanslate the code to,</p>
<pre><code><tr class="build">
<th colspan="0">Build 110</th>
</tr>
<tr class="arccase project flagday">
<td>Feb-25</td>
<td></td>
<td></td>
<td></td>
<td>
<a href="http://www.opensolaris.org/os/community/on/flag-days/all//pages/2009022501/">Flag Day and Heads Up: Power Aware Dispatcher and Deep C-States</a><br />
cpupm keyword mode extensions - <a href="http://www.opensolaris.org/os/community/arc/caselog/2008/777/">PSARC/2008/777</a><br />
CPU Deep Idle Keyword - <a href="http://www.opensolaris.org/os/community/arc/caselog/2008/663/">PSARC/2008/663</a><br />
</td>
</tr>
</code></pre>
<p>My knowledge of regular expressions is so poor that I want to know how to do that. Thanks</p>
<p><strong>I have finished the work using Beautiful Soup, haha~ Thx for everybody!</strong></p>
| 2
|
2009-02-26T09:37:39Z
| 589,890
|
<p>Don't use regular expressions to parse HTML. Use a real parser for that. For example <a href="http://www.crummy.com/software/BeautifulSoup/" rel="nofollow">BeautifulSoup</a>.</p>
| 2
|
2009-02-26T10:00:31Z
|
[
"python",
"regex"
] |
How to find a relative URL and translate it to an absolute URL in Python
| 589,833
|
<p>I extract some code from a web page (<a href="http://www.opensolaris.org/os/community/on/flag-days/all/" rel="nofollow">http://www.opensolaris.org/os/community/on/flag-days/all/</a>) like follows,</p>
<pre><code><tr class="build">
<th colspan="0">Build 110</th>
</tr>
<tr class="arccase project flagday">
<td>Feb-25</td>
<td></td>
<td></td>
<td></td>
<td>
<a href="../pages/2009022501/">Flag Day and Heads Up: Power Aware Dispatcher and Deep C-States</a><br />
cpupm keyword mode extensions - <a href="/os/community/arc/caselog/2008/777/">PSARC/2008/777</a><br />
CPU Deep Idle Keyword - <a href="/os/community/arc/caselog/2008/663/">PSARC/2008/663</a><br />
</td>
</tr>
</code></pre>
<p>and there are some relative url path in it, now I want to search it with regular expression and replace them with absolute url path. Since I know urljoin can do the replace work like that,</p>
<pre><code>>>> urljoin("http://www.opensolaris.org/os/community/on/flag-days/all/",
... "/os/community/arc/caselog/2008/777/")
'http://www.opensolaris.org/os/community/arc/caselog/2008/777/'
</code></pre>
<p>Now I want to know that how to search them using regular expressions, and finally tanslate the code to,</p>
<pre><code><tr class="build">
<th colspan="0">Build 110</th>
</tr>
<tr class="arccase project flagday">
<td>Feb-25</td>
<td></td>
<td></td>
<td></td>
<td>
<a href="http://www.opensolaris.org/os/community/on/flag-days/all//pages/2009022501/">Flag Day and Heads Up: Power Aware Dispatcher and Deep C-States</a><br />
cpupm keyword mode extensions - <a href="http://www.opensolaris.org/os/community/arc/caselog/2008/777/">PSARC/2008/777</a><br />
CPU Deep Idle Keyword - <a href="http://www.opensolaris.org/os/community/arc/caselog/2008/663/">PSARC/2008/663</a><br />
</td>
</tr>
</code></pre>
<p>My knowledge of regular expressions is so poor that I want to know how to do that. Thanks</p>
<p><strong>I have finished the work using Beautiful Soup, haha~ Thx for everybody!</strong></p>
| 2
|
2009-02-26T09:37:39Z
| 589,939
|
<p>First, I'd recommend using a HTML parser, such as <a href="http://www.crummy.com/software/BeautifulSoup/" rel="nofollow">BeautifulSoup</a>. HTML is not a regular language, and thus can't be parsed fully by regular expressions alone. Parts of HTML can be parsed though.</p>
<p>If you don't want to use a full HTML parser, you could use something like this to approximate the work:</p>
<pre><code>import re, urlparse
find_re = re.compile(r'\bhref\s*=\s*("[^"]*"|\'[^\']*\'|[^"\'<>=\s]+)')
def fix_urls(document, base_url):
ret = []
last_end = 0
for match in find_re.finditer(document):
url = match.group(1)
if url[0] in "\"'":
url = url.strip(url[0])
parsed = urlparse.urlparse(url)
if parsed.scheme == parsed.netloc == '': #relative to domain
url = urlparse.urljoin(base_url, url)
ret.append(document[last_end:match.start(1)])
ret.append('"%s"' % (url,))
last_end = match.end(1)
ret.append(document[last_end:])
return ''.join(ret)
</code></pre>
<p>Example:</p>
<pre><code>>>> document = '''<tr class="build"><th colspan="0">Build 110</th></tr> <tr class="arccase project flagday"><td>Feb-25</td><td></td><td></td><td></td><td><a href="../pages/2009022501/">Flag Day and Heads Up: Power Aware Dispatcher and Deep C-States</a><br />cpupm keyword mode extensions - <a href="/os/community/arc/caselog/2008/777/">PSARC/2008/777</a><br /> CPU Deep Idle Keyword - <a href="/os/community/arc/caselog/2008/663/">PSARC/2008/663</a><br /></td></tr>'''
>>> fix_urls(document,"http://www.opensolaris.org/os/community/on/flag-days/all/")
'<tr class="build"><th colspan="0">Build 110</th></tr> <tr class="arccase project flagday"><td>Feb-25</td><td></td><td></td><td></td><td><a href="http://www.opensolaris.org/os/community/on/flag-days/pages/2009022501/">Flag Day and Heads Up: Power Aware Dispatcher and Deep C-States</a><br />cpupm keyword mode extensions - <a href="http://www.opensolaris.org/os/community/arc/caselog/2008/777/">PSARC/2008/777</a><br /> CPU Deep Idle Keyword - <a href="http://www.opensolaris.org/os/community/arc/caselog/2008/663/">PSARC/2008/663</a><br /></td></tr>'
>>>
</code></pre>
| 3
|
2009-02-26T10:16:50Z
|
[
"python",
"regex"
] |
How to find a relative URL and translate it to an absolute URL in Python
| 589,833
|
<p>I extract some code from a web page (<a href="http://www.opensolaris.org/os/community/on/flag-days/all/" rel="nofollow">http://www.opensolaris.org/os/community/on/flag-days/all/</a>) like follows,</p>
<pre><code><tr class="build">
<th colspan="0">Build 110</th>
</tr>
<tr class="arccase project flagday">
<td>Feb-25</td>
<td></td>
<td></td>
<td></td>
<td>
<a href="../pages/2009022501/">Flag Day and Heads Up: Power Aware Dispatcher and Deep C-States</a><br />
cpupm keyword mode extensions - <a href="/os/community/arc/caselog/2008/777/">PSARC/2008/777</a><br />
CPU Deep Idle Keyword - <a href="/os/community/arc/caselog/2008/663/">PSARC/2008/663</a><br />
</td>
</tr>
</code></pre>
<p>and there are some relative url path in it, now I want to search it with regular expression and replace them with absolute url path. Since I know urljoin can do the replace work like that,</p>
<pre><code>>>> urljoin("http://www.opensolaris.org/os/community/on/flag-days/all/",
... "/os/community/arc/caselog/2008/777/")
'http://www.opensolaris.org/os/community/arc/caselog/2008/777/'
</code></pre>
<p>Now I want to know that how to search them using regular expressions, and finally tanslate the code to,</p>
<pre><code><tr class="build">
<th colspan="0">Build 110</th>
</tr>
<tr class="arccase project flagday">
<td>Feb-25</td>
<td></td>
<td></td>
<td></td>
<td>
<a href="http://www.opensolaris.org/os/community/on/flag-days/all//pages/2009022501/">Flag Day and Heads Up: Power Aware Dispatcher and Deep C-States</a><br />
cpupm keyword mode extensions - <a href="http://www.opensolaris.org/os/community/arc/caselog/2008/777/">PSARC/2008/777</a><br />
CPU Deep Idle Keyword - <a href="http://www.opensolaris.org/os/community/arc/caselog/2008/663/">PSARC/2008/663</a><br />
</td>
</tr>
</code></pre>
<p>My knowledge of regular expressions is so poor that I want to know how to do that. Thanks</p>
<p><strong>I have finished the work using Beautiful Soup, haha~ Thx for everybody!</strong></p>
| 2
|
2009-02-26T09:37:39Z
| 4,232,118
|
<p>this isn't elegant, but does the job:</p>
<pre><code>import re
from urlparse import urljoin
relative_urls_re = re.compile('(<\s*a[^>]+href\s*=\s*["\']?)(?!http)([^"\'>]+)', re.IGNORECASE)
relative_urls_re.sub(lambda m: m.group(1) + urljoin(base_url, m.group(2)), html)
</code></pre>
| 1
|
2010-11-20T09:50:00Z
|
[
"python",
"regex"
] |
Python or IronPython
| 590,007
|
<p>How does IronPython stack up to the default Windows implementation of Python from python.org? If I am learning Python, will I be learning a subtley different language with IronPython, and what libraries would I be doing without?</p>
<p>Are there, alternatively, any pros to IronPython (not including .NET IL compiled classes) that would make it more attractive an option?</p>
| 26
|
2009-02-26T10:41:16Z
| 590,024
|
<p>Well, it's generally faster.</p>
<p>Can't use modules, and only has a subset of the library.</p>
<p><a href="http://www.codeplex.com/IronPython/Wiki/View.aspx?title=Differences">Here's a list of differences.</a></p>
| 6
|
2009-02-26T10:47:34Z
|
[
"python",
"ironpython",
"cpython"
] |
Python or IronPython
| 590,007
|
<p>How does IronPython stack up to the default Windows implementation of Python from python.org? If I am learning Python, will I be learning a subtley different language with IronPython, and what libraries would I be doing without?</p>
<p>Are there, alternatively, any pros to IronPython (not including .NET IL compiled classes) that would make it more attractive an option?</p>
| 26
|
2009-02-26T10:41:16Z
| 590,026
|
<p>There are some subtle differences in how you write your code, but the biggest difference is in the libraries you have available.</p>
<p>With IronPython, you have all the .Net libraries available, but at the expense of some of the "normal" python libraries that haven't been ported to the .Net VM I think.</p>
<p>Basically, you should expect the syntax and the idioms to be the same, but a script written for IronPython wont run if you try giving it to the "regular" Python interpreter. The other way around is probably more likely, but there too you will find differences I think.</p>
| 13
|
2009-02-26T10:47:57Z
|
[
"python",
"ironpython",
"cpython"
] |
Python or IronPython
| 590,007
|
<p>How does IronPython stack up to the default Windows implementation of Python from python.org? If I am learning Python, will I be learning a subtley different language with IronPython, and what libraries would I be doing without?</p>
<p>Are there, alternatively, any pros to IronPython (not including .NET IL compiled classes) that would make it more attractive an option?</p>
| 26
|
2009-02-26T10:41:16Z
| 590,029
|
<p>It also depends on whether you want your code to work on Linux. Dunno if IronPython will work on anything beside windows platforms.</p>
| 0
|
2009-02-26T10:50:26Z
|
[
"python",
"ironpython",
"cpython"
] |
Python or IronPython
| 590,007
|
<p>How does IronPython stack up to the default Windows implementation of Python from python.org? If I am learning Python, will I be learning a subtley different language with IronPython, and what libraries would I be doing without?</p>
<p>Are there, alternatively, any pros to IronPython (not including .NET IL compiled classes) that would make it more attractive an option?</p>
| 26
|
2009-02-26T10:41:16Z
| 590,052
|
<p>Python is Python, the only difference is that IronPython was designed to run on the CLR (.NET Framework), and as such, can inter-operate and consume .NET assemblies written in other .NET languages. So if your platform is Windows and you also use .NET or your company does then should consider IronPython.</p>
| 1
|
2009-02-26T10:55:51Z
|
[
"python",
"ironpython",
"cpython"
] |
Python or IronPython
| 590,007
|
<p>How does IronPython stack up to the default Windows implementation of Python from python.org? If I am learning Python, will I be learning a subtley different language with IronPython, and what libraries would I be doing without?</p>
<p>Are there, alternatively, any pros to IronPython (not including .NET IL compiled classes) that would make it more attractive an option?</p>
| 26
|
2009-02-26T10:41:16Z
| 590,216
|
<p>One of the pros of IronPython is that, unlike CPython, IronPython doesn't use the Global Interpreter Lock, thus making threading more effective. </p>
<p>In the standard Python implementation, threads grab the GIL on each object access. This limits parallel execution, which matters especially if you expect to fully utilize multiple CPUs.</p>
| 2
|
2009-02-26T11:50:53Z
|
[
"python",
"ironpython",
"cpython"
] |
Python or IronPython
| 590,007
|
<p>How does IronPython stack up to the default Windows implementation of Python from python.org? If I am learning Python, will I be learning a subtley different language with IronPython, and what libraries would I be doing without?</p>
<p>Are there, alternatively, any pros to IronPython (not including .NET IL compiled classes) that would make it more attractive an option?</p>
| 26
|
2009-02-26T10:41:16Z
| 590,782
|
<p>There are a number of important differences:</p>
<ol>
<li>Interoperability with other .NET languages. You can use other .NET libraries from an IronPython application, or use IronPython from a C# application, for example. This interoperability is increasing, with a movement toward greater support for dynamic types in .NET 4.0. For a lot of detail on this, see <a href="http://channel9.msdn.com/pdc2008/TL10/">these</a> <a href="http://channel9.msdn.com/pdc2008/TL16/">two</a> presentations at PDC 2008.</li>
<li>Better concurrency/multi-core support, due to lack of a GIL. (Note that the GIL doesn't inhibit threading on a single-core machine---it only limits performance on multi-core machines.)</li>
<li>Limited ability to consume Python C extensions. The <a href="http://code.google.com/p/ironclad/">Ironclad</a> project is making significant strides toward improving this---they've nearly gotten <a href="http://numpy.scipy.org/">Numpy</a> working!</li>
<li>Less cross-platform support; basically, you've got the CLR and <a href="http://www.mono-project.com/Main%5FPage">Mono</a>. Mono is impressive, though, and runs on many platforms---and they've got an implementation of Silverlight, called <a href="http://www.mono-project.com/Moonlight">Moonlight</a>.</li>
<li>Reports of improved performance, although I have not looked into this carefully.</li>
<li>Feature lag: since CPython is the reference Python implementation, it has the "latest and greatest" Python features, whereas IronPython necessarily lags behind. Many people do not find this to be a problem.</li>
</ol>
| 27
|
2009-02-26T14:30:48Z
|
[
"python",
"ironpython",
"cpython"
] |
Python or IronPython
| 590,007
|
<p>How does IronPython stack up to the default Windows implementation of Python from python.org? If I am learning Python, will I be learning a subtley different language with IronPython, and what libraries would I be doing without?</p>
<p>Are there, alternatively, any pros to IronPython (not including .NET IL compiled classes) that would make it more attractive an option?</p>
| 26
|
2009-02-26T10:41:16Z
| 590,811
|
<p>See the blog post <a href="http://www.johndcook.com/blog/2009/02/26/ironpython-is-a-one-way-gate/" rel="nofollow">IronPython is a one-way gate</a>. It summarizes some things I've learned about IronPython from asking questions on StackOverflow.</p>
| 2
|
2009-02-26T14:36:37Z
|
[
"python",
"ironpython",
"cpython"
] |
Python or IronPython
| 590,007
|
<p>How does IronPython stack up to the default Windows implementation of Python from python.org? If I am learning Python, will I be learning a subtley different language with IronPython, and what libraries would I be doing without?</p>
<p>Are there, alternatively, any pros to IronPython (not including .NET IL compiled classes) that would make it more attractive an option?</p>
| 26
|
2009-02-26T10:41:16Z
| 590,824
|
<p>Pro: You can run <a href="http://www.codeplex.com/sdlsdk" rel="nofollow">IronPython in a browser</a> if SilverLight is installed.</p>
| 2
|
2009-02-26T14:39:43Z
|
[
"python",
"ironpython",
"cpython"
] |
Video and Voice chat operability in Python
| 590,053
|
<p>I'm trying to find resources on video and voice chat operability in Python... Does anybody know of some good resources or sample projects?</p>
<p>Any help would really be appreciated!</p>
| 3
|
2009-02-26T10:56:32Z
| 590,202
|
<p>If you want something higher level you can try <a href="http://live.gnome.org/Empathy" rel="nofollow">Empathy</a>. It has python bindings so you can use chat GUI elements on your application or create your own. If you want something lower level, you might want to try to use <a href="http://telepathy.freedesktop.org/wiki/Telepathy%20Python" rel="nofollow">Telepathy Python</a> directly. </p>
| 1
|
2009-02-26T11:46:50Z
|
[
"python",
"audio",
"chat",
"voice"
] |
Video and Voice chat operability in Python
| 590,053
|
<p>I'm trying to find resources on video and voice chat operability in Python... Does anybody know of some good resources or sample projects?</p>
<p>Any help would really be appreciated!</p>
| 3
|
2009-02-26T10:56:32Z
| 6,936,316
|
<p>Basically a farsight lib which has xmpp-jingle that can accomodate video and voice chat is commonly used,for python itz farsight.py: try it.....!</p>
| 0
|
2011-08-04T04:47:54Z
|
[
"python",
"audio",
"chat",
"voice"
] |
How to change a Python module name?
| 590,250
|
<p>Is it only possible if I rename the file? Or is there a <code>__module__</code> variable to the file to define what's its name?</p>
| 3
|
2009-02-26T12:01:22Z
| 590,262
|
<p>Yes, you should rename the file. Best would be after you have done that to remove the <code>oldname.pyc</code> and <code>oldname.pyo</code> compiled files (if present) from your system, otherwise the module will be importable under the old name too.</p>
| 8
|
2009-02-26T12:05:14Z
|
[
"python",
"module"
] |
How to change a Python module name?
| 590,250
|
<p>Is it only possible if I rename the file? Or is there a <code>__module__</code> variable to the file to define what's its name?</p>
| 3
|
2009-02-26T12:01:22Z
| 590,271
|
<p>Every class has an <code>__module__</code> property, although I believe changing this will not change the namespace of the Class.</p>
<p>If it is possible, it would probably involve using setattr to insert the methods or class into the desired module, although you run the risk of making your code very confusing to your future peers.</p>
<p>Your best bet is to rename the file.</p>
| 0
|
2009-02-26T12:06:27Z
|
[
"python",
"module"
] |
How to change a Python module name?
| 590,250
|
<p>Is it only possible if I rename the file? Or is there a <code>__module__</code> variable to the file to define what's its name?</p>
| 3
|
2009-02-26T12:01:22Z
| 590,279
|
<p>Where would you like to have this <code>__module__</code> variable, so your original script knows what to import? Modules are recognized by file names and looked in paths defined in <code>sys.path</code> variable. </p>
<p>So, you have to rename the file, then remove the <code>oldname.pyc</code>, just to make sure everything works right. </p>
| 0
|
2009-02-26T12:07:30Z
|
[
"python",
"module"
] |
How to change a Python module name?
| 590,250
|
<p>Is it only possible if I rename the file? Or is there a <code>__module__</code> variable to the file to define what's its name?</p>
| 3
|
2009-02-26T12:01:22Z
| 590,312
|
<p>If you really want to import the file 'oldname.py' with the statement 'import newname', there is a trick that makes it possible: Import the module <em>somewhere</em> with the old name, then inject it into <code>sys.modules</code> with the new name. Subsequent import statements will also find it under the new name. Code sample:</p>
<pre><code># this is in file 'oldname.py'
...module code...
</code></pre>
<p>Usage:</p>
<pre><code># inject the 'oldname' module with a new name
import oldname
import sys
sys.modules['newname'] = oldname
</code></pre>
<p>Now you can everywhere your module with <code>import newname</code>.</p>
| 15
|
2009-02-26T12:16:09Z
|
[
"python",
"module"
] |
How to change a Python module name?
| 590,250
|
<p>Is it only possible if I rename the file? Or is there a <code>__module__</code> variable to the file to define what's its name?</p>
| 3
|
2009-02-26T12:01:22Z
| 590,353
|
<p>You can change the name used for a module when importing by using as:</p>
<pre><code>import foo as bar
print bar.baz
</code></pre>
| 9
|
2009-02-26T12:26:13Z
|
[
"python",
"module"
] |
How to change a Python module name?
| 590,250
|
<p>Is it only possible if I rename the file? Or is there a <code>__module__</code> variable to the file to define what's its name?</p>
| 3
|
2009-02-26T12:01:22Z
| 590,358
|
<p>When you do <code>import module_name</code> the Python interpreter looks for a file <code>module_name</code><em><code>.extension</code></em> in PYTHONPATH. So there's no chaging that name without changing name of the file. But of course you can do:</p>
<pre><code>import module_name as new_module_name
</code></pre>
<p>or even</p>
<pre><code>import module_name.submodule.subsubmodule as short_name
</code></pre>
<p>Useful eg. for writing DB code.</p>
<pre><code>import sqlite3 as sql
sql.whatever..
</code></pre>
<p>And then to switch eg. <code>sqlite3</code> to <code>pysqlite</code> you just change the import line</p>
| 1
|
2009-02-26T12:27:07Z
|
[
"python",
"module"
] |
How to change a Python module name?
| 590,250
|
<p>Is it only possible if I rename the file? Or is there a <code>__module__</code> variable to the file to define what's its name?</p>
| 3
|
2009-02-26T12:01:22Z
| 20,102,459
|
<p>I had an issue like this with bsddb. I was forced to install the bsddb3 module but hundreds of scripts imported bsddb. Instead of changing the import in all of them, I extracted the bsddb3 egg, and created a soft link in the site-packages directory so that both "bsddb" and "bsddb3" were one in the same to python.</p>
| 0
|
2013-11-20T17:13:31Z
|
[
"python",
"module"
] |
How can I query a model by if there is a subclass instance?
| 590,653
|
<p>I have these two simple models, A and B:</p>
<pre><code>from django.db import models
class A(models.Model):
name = models.CharField(max_length=10)
class B(A):
age = models.IntegerField()
</code></pre>
<p>Now, how can I query for all instances of A which do not have an instance of B?</p>
<p>The only way I found requires an explicitly unique field on each subclass, which is NOT NULL, so that I can do A.objects.filter(b__this_is_a_b=None), for example, to get instances that are not also B instances. I'm looking for a way to do this without adding an explicit silly flag like that.</p>
<p>I also don't want to query for all of the objects and then filter them in Python. I want to get the DB to do it for me, which is basically something like <code>SELECT * FROM A WHERE A.id in (SELECT id from B)</code></p>
| 2
|
2009-02-26T13:57:53Z
| 590,785
|
<p>I don't work with django, but it looks like you want the isinstance(obj, type) built-in python method.</p>
<p><strong>Edit:</strong><br>
Would A.objects.exclude(id__exact=B__id) work?</p>
| 0
|
2009-02-26T14:31:35Z
|
[
"python",
"django",
"model-inheritance"
] |
How can I query a model by if there is a subclass instance?
| 590,653
|
<p>I have these two simple models, A and B:</p>
<pre><code>from django.db import models
class A(models.Model):
name = models.CharField(max_length=10)
class B(A):
age = models.IntegerField()
</code></pre>
<p>Now, how can I query for all instances of A which do not have an instance of B?</p>
<p>The only way I found requires an explicitly unique field on each subclass, which is NOT NULL, so that I can do A.objects.filter(b__this_is_a_b=None), for example, to get instances that are not also B instances. I'm looking for a way to do this without adding an explicit silly flag like that.</p>
<p>I also don't want to query for all of the objects and then filter them in Python. I want to get the DB to do it for me, which is basically something like <code>SELECT * FROM A WHERE A.id in (SELECT id from B)</code></p>
| 2
|
2009-02-26T13:57:53Z
| 591,157
|
<p>I'm not sure it's possible to do this purely in the DB with Django's
ORM, in a single query. Here's the best I've been able to do:</p>
<pre><code>A.objects.exclude(id__in=[r[0] for r in B.objects.values_list("a_ptr_id")])
</code></pre>
<p>This is 2 DB queries, and works best with a simplistic inheritance
graph - each subclass of A would require a new database query.</p>
<p><hr /></p>
<p>Okay, it took a lot of trial and error, but I have a solution. It's
ugly as all hell, and the SQL is probably worse than just going with
two queries, but you can do something like so:</p>
<pre><code>A.objects.exclude(b__age__isnull=True).exclude(b__age_isnull=False)
</code></pre>
<p>There's no way to get Django to do the join without referencing a
field on b. But with these successive <code>.exclude()</code>s, you make <em>any</em> A
with a B subclass match one or the other of the excludes. All you're left with are A's
without a B subclass.</p>
<p>Anyway, this is an interesting use case, you should bring it up on django-dev...</p>
| 1
|
2009-02-26T15:57:12Z
|
[
"python",
"django",
"model-inheritance"
] |
How can I query a model by if there is a subclass instance?
| 590,653
|
<p>I have these two simple models, A and B:</p>
<pre><code>from django.db import models
class A(models.Model):
name = models.CharField(max_length=10)
class B(A):
age = models.IntegerField()
</code></pre>
<p>Now, how can I query for all instances of A which do not have an instance of B?</p>
<p>The only way I found requires an explicitly unique field on each subclass, which is NOT NULL, so that I can do A.objects.filter(b__this_is_a_b=None), for example, to get instances that are not also B instances. I'm looking for a way to do this without adding an explicit silly flag like that.</p>
<p>I also don't want to query for all of the objects and then filter them in Python. I want to get the DB to do it for me, which is basically something like <code>SELECT * FROM A WHERE A.id in (SELECT id from B)</code></p>
| 2
|
2009-02-26T13:57:53Z
| 10,824,061
|
<p>Since some version of django or python this works as well:</p>
<pre><code>A.Objects.all().filter(b__isnull=True)
</code></pre>
<p>because if a is an A object a.b gives the subclass B of a when it exists</p>
<p>I Know this is an old question, but my answer might help new searchers on this subject.</p>
<p>see also:</p>
<p><a href="https://docs.djangoproject.com/en/dev/topics/db/models/#multi-table-inheritance" rel="nofollow">multi table inheritance</a></p>
<p>And one of my own questions about this: <a href="http://stackoverflow.com/questions/9821935/django-model-inheritance-create-a-subclass-using-existing-super-class">downcasting a super class to a sub class</a></p>
| 2
|
2012-05-30T20:50:32Z
|
[
"python",
"django",
"model-inheritance"
] |
Django - designing models with virtual fields?
| 590,921
|
<p>I'd like to ask about the most elegant approach when it comes to designing models with virtual fields such as below in Django... </p>
<p>Let's say we're building an online store and all the products in the system are defined by the model "<em>Product</em>".</p>
<pre><code>class Product(models.Model):
# common fields that all products share
name = ...
brand = ...
price = ...
</code></pre>
<p>But the store will have lots of product types completely unrelated with eachother, so I need some way to store those virtual fields of different product types (ie. capacity of a MP3 player, pagecount of a book,..).</p>
<p>The solutions I could come up with my raw Django skills are far from perfect so far:</p>
<ul>
<li><p>Having a "custom_fields" property
and intermediate tables that I
manage manually. (screaming ugly in
my face :)) </p></li>
<li><p>Or inheriting classes from
"<em>Product</em>" on the fly with Python's
dangerous exec-eval statements (that is too
much voodoo magic for maintenance
and also implementation would
require knowledge of Django internals).</p></li>
</ul>
<p>What's your take on this?</p>
<p>TIA.</p>
| 2
|
2009-02-26T15:08:17Z
| 590,928
|
<p>Ruby on Rails has a "serialized" field which allows you to pack a dictionary into a text field. Perhaps DJango offers something similar?</p>
<p><a href="http://www.davidcramer.net/code/181/custom-fields-in-django.html" rel="nofollow">This article</a> has an implementation of a SerializedDataField.</p>
| 3
|
2009-02-26T15:09:48Z
|
[
"python",
"django",
"django-models"
] |
Django - designing models with virtual fields?
| 590,921
|
<p>I'd like to ask about the most elegant approach when it comes to designing models with virtual fields such as below in Django... </p>
<p>Let's say we're building an online store and all the products in the system are defined by the model "<em>Product</em>".</p>
<pre><code>class Product(models.Model):
# common fields that all products share
name = ...
brand = ...
price = ...
</code></pre>
<p>But the store will have lots of product types completely unrelated with eachother, so I need some way to store those virtual fields of different product types (ie. capacity of a MP3 player, pagecount of a book,..).</p>
<p>The solutions I could come up with my raw Django skills are far from perfect so far:</p>
<ul>
<li><p>Having a "custom_fields" property
and intermediate tables that I
manage manually. (screaming ugly in
my face :)) </p></li>
<li><p>Or inheriting classes from
"<em>Product</em>" on the fly with Python's
dangerous exec-eval statements (that is too
much voodoo magic for maintenance
and also implementation would
require knowledge of Django internals).</p></li>
</ul>
<p>What's your take on this?</p>
<p>TIA.</p>
| 2
|
2009-02-26T15:08:17Z
| 590,968
|
<p>Products have Features.</p>
<pre><code>class Feature( models.Model ):
feature_name = models.CharField( max_length=128 )
feature_value = models.TextField()
part_of = models.ForeignKey( Product )
</code></pre>
<p>Like that.</p>
<p>Just a list of features. </p>
<pre><code>p= Product( "iPhone", "Apple", 350 )
p.save()
f= Feature( "mp3 capacity", "16Gb", p )
f.save()
</code></pre>
<p>If you want, you can have a master list of feature names in a separate table. Don't over-analyze features. You can't do any processing on them. All you do is present them. </p>
| 13
|
2009-02-26T15:17:49Z
|
[
"python",
"django",
"django-models"
] |
Django - designing models with virtual fields?
| 590,921
|
<p>I'd like to ask about the most elegant approach when it comes to designing models with virtual fields such as below in Django... </p>
<p>Let's say we're building an online store and all the products in the system are defined by the model "<em>Product</em>".</p>
<pre><code>class Product(models.Model):
# common fields that all products share
name = ...
brand = ...
price = ...
</code></pre>
<p>But the store will have lots of product types completely unrelated with eachother, so I need some way to store those virtual fields of different product types (ie. capacity of a MP3 player, pagecount of a book,..).</p>
<p>The solutions I could come up with my raw Django skills are far from perfect so far:</p>
<ul>
<li><p>Having a "custom_fields" property
and intermediate tables that I
manage manually. (screaming ugly in
my face :)) </p></li>
<li><p>Or inheriting classes from
"<em>Product</em>" on the fly with Python's
dangerous exec-eval statements (that is too
much voodoo magic for maintenance
and also implementation would
require knowledge of Django internals).</p></li>
</ul>
<p>What's your take on this?</p>
<p>TIA.</p>
| 2
|
2009-02-26T15:08:17Z
| 591,015
|
<p>Personally, I'd go with S. Lott's answer. However, you might want to create a custom JSON Field:</p>
<p><a href="http://svn.navi.cx/misc/trunk/djblets/djblets/util/fields.py" rel="nofollow">http://svn.navi.cx/misc/trunk/djblets/djblets/util/fields.py</a></p>
<p><a href="http://www.djangosnippets.org/snippets/377/" rel="nofollow">http://www.djangosnippets.org/snippets/377/</a></p>
| 2
|
2009-02-26T15:28:37Z
|
[
"python",
"django",
"django-models"
] |
Django - designing models with virtual fields?
| 590,921
|
<p>I'd like to ask about the most elegant approach when it comes to designing models with virtual fields such as below in Django... </p>
<p>Let's say we're building an online store and all the products in the system are defined by the model "<em>Product</em>".</p>
<pre><code>class Product(models.Model):
# common fields that all products share
name = ...
brand = ...
price = ...
</code></pre>
<p>But the store will have lots of product types completely unrelated with eachother, so I need some way to store those virtual fields of different product types (ie. capacity of a MP3 player, pagecount of a book,..).</p>
<p>The solutions I could come up with my raw Django skills are far from perfect so far:</p>
<ul>
<li><p>Having a "custom_fields" property
and intermediate tables that I
manage manually. (screaming ugly in
my face :)) </p></li>
<li><p>Or inheriting classes from
"<em>Product</em>" on the fly with Python's
dangerous exec-eval statements (that is too
much voodoo magic for maintenance
and also implementation would
require knowledge of Django internals).</p></li>
</ul>
<p>What's your take on this?</p>
<p>TIA.</p>
| 2
|
2009-02-26T15:08:17Z
| 596,609
|
<p>Go with the inheritance. Create Produce subclasses with their own, additional fields. </p>
| 0
|
2009-02-27T20:43:55Z
|
[
"python",
"django",
"django-models"
] |
Can I use a decorator to mutate the local scope of a function in Python?
| 591,200
|
<p>Is there any way of writing a decorator such that the following would work?</p>
<pre><code>assert 'z' not in globals()
@my_decorator
def func(x, y):
print z
</code></pre>
<p><hr /></p>
<p>EDIT: moved from anwser</p>
<p>In answer to hop's "why?": syntax sugar / DRY.</p>
<p>It's not about caching, it's about calculating z (and z1, z2, z3, ...) based upon the values of x & y.</p>
<p>I have lots of functions which do related things, and I don't want to do have to write</p>
<pre><code>z1, z2, z3=calculate_from(x, y)
</code></pre>
<p>at the beginning of every single function - I'll get it wrong somewhere. If this were c I'd do this with cpp (if this were lisp, I'd do this with macros ...), but I wanted to see if decorators could do the same thing.</p>
<p>If it helps, I'd almost certainly call the decorator "precalculate_z", and it certainly wouldn't be part of any public API.</p>
<p>I could probably get a similar effect from using the class infrastructure as well, but I wanted to see if it was doable with raw functions.</p>
| 8
|
2009-02-26T16:03:08Z
| 591,295
|
<p>I don't know about the local scope, but you could provide an alternative global name space temporarily. Something like:</p>
<pre>
<code>
import types
def my_decorator(fn):
def decorated(*args,**kw):
my_globals={}
my_globals.update(globals())
my_globals['z']='value of z'
call_fn=types.FunctionType(fn.func_code,my_globals)
return call_fn(*args,**kw)
return decorated
@my_decorator
def func(x, y):
print z
func(0,1)
</code>
</pre>
<p>Which should print "value of z"</p>
| 8
|
2009-02-26T16:23:43Z
|
[
"python",
"decorator"
] |
Can I use a decorator to mutate the local scope of a function in Python?
| 591,200
|
<p>Is there any way of writing a decorator such that the following would work?</p>
<pre><code>assert 'z' not in globals()
@my_decorator
def func(x, y):
print z
</code></pre>
<p><hr /></p>
<p>EDIT: moved from anwser</p>
<p>In answer to hop's "why?": syntax sugar / DRY.</p>
<p>It's not about caching, it's about calculating z (and z1, z2, z3, ...) based upon the values of x & y.</p>
<p>I have lots of functions which do related things, and I don't want to do have to write</p>
<pre><code>z1, z2, z3=calculate_from(x, y)
</code></pre>
<p>at the beginning of every single function - I'll get it wrong somewhere. If this were c I'd do this with cpp (if this were lisp, I'd do this with macros ...), but I wanted to see if decorators could do the same thing.</p>
<p>If it helps, I'd almost certainly call the decorator "precalculate_z", and it certainly wouldn't be part of any public API.</p>
<p>I could probably get a similar effect from using the class infrastructure as well, but I wanted to see if it was doable with raw functions.</p>
| 8
|
2009-02-26T16:03:08Z
| 591,309
|
<p>a) don't do it.</p>
<p>b) seriously, why would you do that?</p>
<p>c) you could declare z as global within your decorator, so z will not be in globals() until after the decorator has been called for the first time, so the assert won't bark.</p>
<p>d) why???</p>
| 6
|
2009-02-26T16:26:19Z
|
[
"python",
"decorator"
] |
Can I use a decorator to mutate the local scope of a function in Python?
| 591,200
|
<p>Is there any way of writing a decorator such that the following would work?</p>
<pre><code>assert 'z' not in globals()
@my_decorator
def func(x, y):
print z
</code></pre>
<p><hr /></p>
<p>EDIT: moved from anwser</p>
<p>In answer to hop's "why?": syntax sugar / DRY.</p>
<p>It's not about caching, it's about calculating z (and z1, z2, z3, ...) based upon the values of x & y.</p>
<p>I have lots of functions which do related things, and I don't want to do have to write</p>
<pre><code>z1, z2, z3=calculate_from(x, y)
</code></pre>
<p>at the beginning of every single function - I'll get it wrong somewhere. If this were c I'd do this with cpp (if this were lisp, I'd do this with macros ...), but I wanted to see if decorators could do the same thing.</p>
<p>If it helps, I'd almost certainly call the decorator "precalculate_z", and it certainly wouldn't be part of any public API.</p>
<p>I could probably get a similar effect from using the class infrastructure as well, but I wanted to see if it was doable with raw functions.</p>
| 8
|
2009-02-26T16:03:08Z
| 591,948
|
<p><em>I could probably get a similar effect from using the class infrastructure as well, but I wanted to see if it was doable with raw functions.</em></p>
<p>Well, Python is an object-oriented language. You should do this in a class, in my opinion. Making a nice class interface would surely simplify your problem. This <strong>isn't</strong> what decorators were made for.</p>
| 1
|
2009-02-26T19:02:39Z
|
[
"python",
"decorator"
] |
Can I use a decorator to mutate the local scope of a function in Python?
| 591,200
|
<p>Is there any way of writing a decorator such that the following would work?</p>
<pre><code>assert 'z' not in globals()
@my_decorator
def func(x, y):
print z
</code></pre>
<p><hr /></p>
<p>EDIT: moved from anwser</p>
<p>In answer to hop's "why?": syntax sugar / DRY.</p>
<p>It's not about caching, it's about calculating z (and z1, z2, z3, ...) based upon the values of x & y.</p>
<p>I have lots of functions which do related things, and I don't want to do have to write</p>
<pre><code>z1, z2, z3=calculate_from(x, y)
</code></pre>
<p>at the beginning of every single function - I'll get it wrong somewhere. If this were c I'd do this with cpp (if this were lisp, I'd do this with macros ...), but I wanted to see if decorators could do the same thing.</p>
<p>If it helps, I'd almost certainly call the decorator "precalculate_z", and it certainly wouldn't be part of any public API.</p>
<p>I could probably get a similar effect from using the class infrastructure as well, but I wanted to see if it was doable with raw functions.</p>
| 8
|
2009-02-26T16:03:08Z
| 591,982
|
<p>I'll first echo the "please don't", but that's your choice. Here's a solution for you:</p>
<pre><code>assert 'z' not in globals ()
class my_dec:
def __init__ (self, f):
self.f = f
def __call__ (self,x,y):
z = x+y
self.f(x,y,z)
@my_dec
def func (x,y,z):
print z
func (1,3)
</code></pre>
<p>It does require <code>z</code> in the formal parameters, but not the actual.</p>
| 2
|
2009-02-26T19:09:07Z
|
[
"python",
"decorator"
] |
Can I use a decorator to mutate the local scope of a function in Python?
| 591,200
|
<p>Is there any way of writing a decorator such that the following would work?</p>
<pre><code>assert 'z' not in globals()
@my_decorator
def func(x, y):
print z
</code></pre>
<p><hr /></p>
<p>EDIT: moved from anwser</p>
<p>In answer to hop's "why?": syntax sugar / DRY.</p>
<p>It's not about caching, it's about calculating z (and z1, z2, z3, ...) based upon the values of x & y.</p>
<p>I have lots of functions which do related things, and I don't want to do have to write</p>
<pre><code>z1, z2, z3=calculate_from(x, y)
</code></pre>
<p>at the beginning of every single function - I'll get it wrong somewhere. If this were c I'd do this with cpp (if this were lisp, I'd do this with macros ...), but I wanted to see if decorators could do the same thing.</p>
<p>If it helps, I'd almost certainly call the decorator "precalculate_z", and it certainly wouldn't be part of any public API.</p>
<p>I could probably get a similar effect from using the class infrastructure as well, but I wanted to see if it was doable with raw functions.</p>
| 8
|
2009-02-26T16:03:08Z
| 592,019
|
<p>Echoing Hop's answer</p>
<ol>
<li>Don't do it.</li>
<li>Seriously, don't do this. Lisp and Ruby are more appropriate languages for writing your own custom syntax. Use one of those. Or find a cleaner way to do this</li>
<li>If you must, you want dynamic scoped variables, not lexically scoped.</li>
</ol>
<p>Python doesn't have dynamically scoped variables, but you can simulate it. Here's an example that simulates it by creating a global binding, but restores the previous value on exit:</p>
<p><a href="http://codepad.org/6vAY8Leh">http://codepad.org/6vAY8Leh</a></p>
<pre><code>def adds_dynamic_z_decorator(f):
def replacement(*arg,**karg):
# create a new 'z' binding in globals, saving previous
if 'z' in globals():
oldZ = (globals()['z'],)
else:
oldZ = None
try:
globals()['z'] = None
#invoke the original function
res = f(*arg, **karg)
finally:
#restore any old bindings
if oldZ:
globals()['z'] = oldZ[0]
else:
del(globals()['z'])
return res
return replacement
@adds_dynamic_z_decorator
def func(x,y):
print z
def other_recurse(x):
global z
print 'x=%s, z=%s' %(x,z)
recurse(x+1)
print 'x=%s, z=%s' %(x,z)
@adds_dynamic_z_decorator
def recurse(x=0):
global z
z = x
if x < 3:
other_recurse(x)
print 'calling func(1,2)'
func(1,2)
print 'calling recurse()'
recurse()
</code></pre>
<p>I make no warranties on the utility or sanity of the above code. Actually, I warrant that it <em>is</em> insane, and you should avoid using it unless you want a flogging from your Python peers.</p>
<p>This code is similar to both eduffy's and John Montgomery's code, but ensures that 'z' is created and properly restored "like" a local variable would be -- for instance, note how 'other_recurse' is able to see the binding for 'z' specified in the body of 'recurse'. </p>
| 10
|
2009-02-26T19:20:17Z
|
[
"python",
"decorator"
] |
Can I use a decorator to mutate the local scope of a function in Python?
| 591,200
|
<p>Is there any way of writing a decorator such that the following would work?</p>
<pre><code>assert 'z' not in globals()
@my_decorator
def func(x, y):
print z
</code></pre>
<p><hr /></p>
<p>EDIT: moved from anwser</p>
<p>In answer to hop's "why?": syntax sugar / DRY.</p>
<p>It's not about caching, it's about calculating z (and z1, z2, z3, ...) based upon the values of x & y.</p>
<p>I have lots of functions which do related things, and I don't want to do have to write</p>
<pre><code>z1, z2, z3=calculate_from(x, y)
</code></pre>
<p>at the beginning of every single function - I'll get it wrong somewhere. If this were c I'd do this with cpp (if this were lisp, I'd do this with macros ...), but I wanted to see if decorators could do the same thing.</p>
<p>If it helps, I'd almost certainly call the decorator "precalculate_z", and it certainly wouldn't be part of any public API.</p>
<p>I could probably get a similar effect from using the class infrastructure as well, but I wanted to see if it was doable with raw functions.</p>
| 8
|
2009-02-26T16:03:08Z
| 593,077
|
<p>Explicit is better than implicit.</p>
<p>Is this good enough?</p>
<pre><code>def provide_value(f):
f.foo = "Bar"
return f
@provide_value
def g(x):
print g.foo
</code></pre>
<p>(If you really want evil, assigning to f.func_globals seems fun.)</p>
| 0
|
2009-02-27T00:19:45Z
|
[
"python",
"decorator"
] |
Can I use a decorator to mutate the local scope of a function in Python?
| 591,200
|
<p>Is there any way of writing a decorator such that the following would work?</p>
<pre><code>assert 'z' not in globals()
@my_decorator
def func(x, y):
print z
</code></pre>
<p><hr /></p>
<p>EDIT: moved from anwser</p>
<p>In answer to hop's "why?": syntax sugar / DRY.</p>
<p>It's not about caching, it's about calculating z (and z1, z2, z3, ...) based upon the values of x & y.</p>
<p>I have lots of functions which do related things, and I don't want to do have to write</p>
<pre><code>z1, z2, z3=calculate_from(x, y)
</code></pre>
<p>at the beginning of every single function - I'll get it wrong somewhere. If this were c I'd do this with cpp (if this were lisp, I'd do this with macros ...), but I wanted to see if decorators could do the same thing.</p>
<p>If it helps, I'd almost certainly call the decorator "precalculate_z", and it certainly wouldn't be part of any public API.</p>
<p>I could probably get a similar effect from using the class infrastructure as well, but I wanted to see if it was doable with raw functions.</p>
| 8
|
2009-02-26T16:03:08Z
| 593,144
|
<p>Others have given a few ways of making a working decorator, many have advised against doing so because it's so stylistically different from normal python behavior that it'll really confuse anyone trying to understand the code.</p>
<p>If you're needing to recalculate things a lot, would it make sense to group them together in an object? Compute z1...zN in the constructor, then the functions that use these values can access the pre-computed answers as part of the instance.</p>
| 0
|
2009-02-27T00:50:36Z
|
[
"python",
"decorator"
] |
When using random, which form returns an equal 50% chance?
| 591,253
|
<p>I'm guessing that most built in random generators return something like this:</p>
<pre><code>[0.0, 1.0)
</code></pre>
<p>so if I would like a 50% chance would I use something like this:</p>
<pre><code>if random() < .5
</code></pre>
<p>or something like:</p>
<pre><code>if random() <= .5
</code></pre>
<p>Thanks for the help.</p>
| 6
|
2009-02-26T16:15:37Z
| 591,272
|
<p>It doesn't matter. Both formulas yield the desired result.</p>
| -2
|
2009-02-26T16:19:19Z
|
[
"python",
"random"
] |
When using random, which form returns an equal 50% chance?
| 591,253
|
<p>I'm guessing that most built in random generators return something like this:</p>
<pre><code>[0.0, 1.0)
</code></pre>
<p>so if I would like a 50% chance would I use something like this:</p>
<pre><code>if random() < .5
</code></pre>
<p>or something like:</p>
<pre><code>if random() <= .5
</code></pre>
<p>Thanks for the help.</p>
| 6
|
2009-02-26T16:15:37Z
| 591,276
|
<p>To a first approximation, either works.</p>
<p>The best way is to choose a random generator that specifically emits booleans or integers with range. Then you can nail the range exactly.</p>
<p>Operations like "equality" with floating point is iffy anyway.</p>
| 4
|
2009-02-26T16:20:05Z
|
[
"python",
"random"
] |
When using random, which form returns an equal 50% chance?
| 591,253
|
<p>I'm guessing that most built in random generators return something like this:</p>
<pre><code>[0.0, 1.0)
</code></pre>
<p>so if I would like a 50% chance would I use something like this:</p>
<pre><code>if random() < .5
</code></pre>
<p>or something like:</p>
<pre><code>if random() <= .5
</code></pre>
<p>Thanks for the help.</p>
| 6
|
2009-02-26T16:15:37Z
| 591,282
|
<pre><code> if random() < .5
</code></pre>
<p>In binary, .5 is .10000000000....
So, basically, the question reduces to, "What is the first binary digit after the radix point... 0 (for <.5) or 1 (for .5 or more) ?"</p>
| 3
|
2009-02-26T16:21:16Z
|
[
"python",
"random"
] |
When using random, which form returns an equal 50% chance?
| 591,253
|
<p>I'm guessing that most built in random generators return something like this:</p>
<pre><code>[0.0, 1.0)
</code></pre>
<p>so if I would like a 50% chance would I use something like this:</p>
<pre><code>if random() < .5
</code></pre>
<p>or something like:</p>
<pre><code>if random() <= .5
</code></pre>
<p>Thanks for the help.</p>
| 6
|
2009-02-26T16:15:37Z
| 591,283
|
<pre><code>< .5
</code></pre>
<p>but that assumes that your floating point support is good enough to satisfy your precision demands (since it's never <em>exactly</em>).</p>
| 0
|
2009-02-26T16:21:19Z
|
[
"python",
"random"
] |
When using random, which form returns an equal 50% chance?
| 591,253
|
<p>I'm guessing that most built in random generators return something like this:</p>
<pre><code>[0.0, 1.0)
</code></pre>
<p>so if I would like a 50% chance would I use something like this:</p>
<pre><code>if random() < .5
</code></pre>
<p>or something like:</p>
<pre><code>if random() <= .5
</code></pre>
<p>Thanks for the help.</p>
| 6
|
2009-02-26T16:15:37Z
| 591,286
|
<p>If I want 50% chance, I'd just check for the LSB (Least Significant Bit).</p>
| 0
|
2009-02-26T16:21:40Z
|
[
"python",
"random"
] |
When using random, which form returns an equal 50% chance?
| 591,253
|
<p>I'm guessing that most built in random generators return something like this:</p>
<pre><code>[0.0, 1.0)
</code></pre>
<p>so if I would like a 50% chance would I use something like this:</p>
<pre><code>if random() < .5
</code></pre>
<p>or something like:</p>
<pre><code>if random() <= .5
</code></pre>
<p>Thanks for the help.</p>
| 6
|
2009-02-26T16:15:37Z
| 591,294
|
<p>Ah, the old ".5" problem. Here's the answer:</p>
<p>If you're going to divide 10 things into two <strong>equal</strong> parts, you need 5 things in each part. 0 thru 4 in the first part, 5-9 in the second part. So... <code>< .5</code> is correct.</p>
| 12
|
2009-02-26T16:23:32Z
|
[
"python",
"random"
] |
When using random, which form returns an equal 50% chance?
| 591,253
|
<p>I'm guessing that most built in random generators return something like this:</p>
<pre><code>[0.0, 1.0)
</code></pre>
<p>so if I would like a 50% chance would I use something like this:</p>
<pre><code>if random() < .5
</code></pre>
<p>or something like:</p>
<pre><code>if random() <= .5
</code></pre>
<p>Thanks for the help.</p>
| 6
|
2009-02-26T16:15:37Z
| 591,353
|
<p>For a particular system you should test it, if you really want to find out. Could take a while though :-)</p>
<p>I agree with the other posters that to the first order, it doesn't matter. If it does matter, you'll need a better RNG anyway.</p>
<p><strong>EDIT:</strong> I just tried the default RNG in C# with 1,000,000,000 attempts and the answers were identical...</p>
| 1
|
2009-02-26T16:39:14Z
|
[
"python",
"random"
] |
When using random, which form returns an equal 50% chance?
| 591,253
|
<p>I'm guessing that most built in random generators return something like this:</p>
<pre><code>[0.0, 1.0)
</code></pre>
<p>so if I would like a 50% chance would I use something like this:</p>
<pre><code>if random() < .5
</code></pre>
<p>or something like:</p>
<pre><code>if random() <= .5
</code></pre>
<p>Thanks for the help.</p>
| 6
|
2009-02-26T16:15:37Z
| 591,378
|
<p>If you need truly random numbers, you can try <a href="http://random.org/" rel="nofollow">random.org</a>. They offer a web service connected to a device that detects noise coming from the universe. Still not random technically speaking, but close enough I guess. </p>
<p>They have all sort of way to make the query such as black and white images.</p>
| 0
|
2009-02-26T16:44:19Z
|
[
"python",
"random"
] |
When using random, which form returns an equal 50% chance?
| 591,253
|
<p>I'm guessing that most built in random generators return something like this:</p>
<pre><code>[0.0, 1.0)
</code></pre>
<p>so if I would like a 50% chance would I use something like this:</p>
<pre><code>if random() < .5
</code></pre>
<p>or something like:</p>
<pre><code>if random() <= .5
</code></pre>
<p>Thanks for the help.</p>
| 6
|
2009-02-26T16:15:37Z
| 591,389
|
<p>If you're going to be that fussy about your random numbers, don't rely on anything that comes built-in. Get a well-documented RNG from a place you trust (I trust Boost, for what that's worth), and read the documentation. It used to be that standard RNGs were notoriously bad, and I still wouldn't trust them.</p>
<p>Alternately, use an integer RNG that gives you discrete values within a range, and divide the range in half. RNGs, in my experience, are integral, and the floating-point function simply divides by the top of the range.</p>
<p>Of course, if this is true, you've got your answer. If the integer RNG produces 0, 1, 2, and 3, the floating-point equivalent will be 0.0, 0.25, 0.5, and 0.75, so the answer is to test < 0.5.</p>
<p>If the RNG isn't based on integral calculations, then it's based on floating-point calculations, and hence is inexact. In that case, it doesn't matter whether you test <= or <, since there is no guarantee that a calculation that should be a precise 0.5 will be.</p>
<p>So, the answer is probably to test < 0.5, which will likely be the correct one if it makes a difference.</p>
| 0
|
2009-02-26T16:46:01Z
|
[
"python",
"random"
] |
When using random, which form returns an equal 50% chance?
| 591,253
|
<p>I'm guessing that most built in random generators return something like this:</p>
<pre><code>[0.0, 1.0)
</code></pre>
<p>so if I would like a 50% chance would I use something like this:</p>
<pre><code>if random() < .5
</code></pre>
<p>or something like:</p>
<pre><code>if random() <= .5
</code></pre>
<p>Thanks for the help.</p>
| 6
|
2009-02-26T16:15:37Z
| 993,264
|
<p>Why do it yourself? Python has random.choice :)</p>
<p>random.choice([0, 1]) will give you 0/1 with equal chances -- and it is a standard part of Python, coded up by the same people who wrote random.random (and thus know more about its semantics than anyone else)</p>
| 2
|
2009-06-14T17:28:14Z
|
[
"python",
"random"
] |
When using random, which form returns an equal 50% chance?
| 591,253
|
<p>I'm guessing that most built in random generators return something like this:</p>
<pre><code>[0.0, 1.0)
</code></pre>
<p>so if I would like a 50% chance would I use something like this:</p>
<pre><code>if random() < .5
</code></pre>
<p>or something like:</p>
<pre><code>if random() <= .5
</code></pre>
<p>Thanks for the help.</p>
| 6
|
2009-02-26T16:15:37Z
| 1,020,029
|
<pre><code>import random
def fifty_fifty():
"Return 0 or 1 with 50% chance for each"
return random.randrange(2)
</code></pre>
| 1
|
2009-06-19T21:08:18Z
|
[
"python",
"random"
] |
How can I modify password expiration in Windows using Python?
| 591,300
|
<p>How can I modify the password expiration to "never" on Windows XP for a local user with Python? I have the PyWIN and WMI modules on board but have no solution. I managed to query the current settings via WMI(based on Win32_UserAccount class), but how can modify it?</p>
| 4
|
2009-02-26T16:24:28Z
| 591,375
|
<p>That change would require administrator permissions, which may (or may not) cause issues inside of PyWin32. I don't see any straight-forward way of making this change from a Python script, but I'm sure this can be automated using a different method.</p>
<p>This MSFN thread seems to have info that will help you, or at least a start:</p>
<p><a href="http://www.msfn.org/board/Password-Expires-Chang-t115757.html" rel="nofollow">http://www.msfn.org/board/Password-Expires-Chang-t115757.html</a></p>
| 0
|
2009-02-26T16:43:51Z
|
[
"python",
"windows",
"passwords"
] |
How can I modify password expiration in Windows using Python?
| 591,300
|
<p>How can I modify the password expiration to "never" on Windows XP for a local user with Python? I have the PyWIN and WMI modules on board but have no solution. I managed to query the current settings via WMI(based on Win32_UserAccount class), but how can modify it?</p>
| 4
|
2009-02-26T16:24:28Z
| 600,635
|
<p>You might need admin priviliges to do that, so look into elevating the current process or launch a new process with more priviliges. (I.e. something like vista's UAC but on XP.)</p>
<p>Can't help with details though. :-/</p>
| 0
|
2009-03-01T22:05:10Z
|
[
"python",
"windows",
"passwords"
] |
How can I modify password expiration in Windows using Python?
| 591,300
|
<p>How can I modify the password expiration to "never" on Windows XP for a local user with Python? I have the PyWIN and WMI modules on board but have no solution. I managed to query the current settings via WMI(based on Win32_UserAccount class), but how can modify it?</p>
| 4
|
2009-02-26T16:24:28Z
| 603,428
|
<p>If you are running your python script with ActvePython against Active Directory, then you can use something like this:</p>
<pre><code>import win32com.client
ads = win32com.client.Dispatch('ADsNameSpaces')
user = ads.getObject("", "WinNT://DOMAIN/username,user")
user.Getinfo()
user.Put('userAccountControl', 65536 | user.Get('userAccountControl'))
user.Setinfo()
</code></pre>
<p>But if your python is running under unix, you need two things to talk to Active Directory: Kerberos and LDAP. Once you have a SASL(GSSAPI(KRB5)) authenticated LDAP connection to your Active Directory server, then you access the target user's "userAccountControl" attribute. </p>
<p>userAccountControl is an integer attribute, treated as a bit field, on which you must set the DONT EXPIRE PASSWORD bit. See <a href="http://support.microsoft.com/kb/305144" rel="nofollow">this KB article</a> for bit values.</p>
| 1
|
2009-03-02T18:29:00Z
|
[
"python",
"windows",
"passwords"
] |
python variables not accepting names
| 591,421
|
<p>I'm trying to declare a few simple variables as part of a function in a very basic collision detection programme. For some reason it's rejecting my variables (although only some of them even though they're near identical). Here's the code for the function;</p>
<pre><code>def TimeCheck():
timechecknumber = int(time.time())
timecheckdiv = backcolourcheck % 5
if timecheckdiv < 1:
timecheck = true
else:
timecheck = false
if timecheck == true:
backgroundr = (int(random.random()*255)+1
backgroundg = (int(random.random()*255)+1
backgroundb = (int(random.random()*255)+1
</code></pre>
<p>for some reason it accepts backgroundr but not backgroundg, anyone got any ideas why? thanks</p>
| 0
|
2009-02-26T16:53:16Z
| 591,431
|
<p>You have mismatched parentheses on the line beginning with <code>backgroundr</code>. I think maybe you want this:</p>
<pre><code>backgroundr = int(random.random() * 255) + 1
</code></pre>
<p>Note that each of the next two lines also have mismatched parentheses, so you'll have to fix those, too.</p>
| 8
|
2009-02-26T16:55:47Z
|
[
"python",
"variables",
"syntax-error"
] |
python variables not accepting names
| 591,421
|
<p>I'm trying to declare a few simple variables as part of a function in a very basic collision detection programme. For some reason it's rejecting my variables (although only some of them even though they're near identical). Here's the code for the function;</p>
<pre><code>def TimeCheck():
timechecknumber = int(time.time())
timecheckdiv = backcolourcheck % 5
if timecheckdiv < 1:
timecheck = true
else:
timecheck = false
if timecheck == true:
backgroundr = (int(random.random()*255)+1
backgroundg = (int(random.random()*255)+1
backgroundb = (int(random.random()*255)+1
</code></pre>
<p>for some reason it accepts backgroundr but not backgroundg, anyone got any ideas why? thanks</p>
| 0
|
2009-02-26T16:53:16Z
| 591,444
|
<p>mipadi's answer will always yield a 1. You need to multiply by 255 before you cast to int. Try this.</p>
<pre><code>backgroundr = int(random.random() * 255) + 1
</code></pre>
| 2
|
2009-02-26T17:00:12Z
|
[
"python",
"variables",
"syntax-error"
] |
Python Win32 - DriveInfo On Mapped Drive
| 591,443
|
<p>Does anyone know how I can determine the server and share name of a mapped network drive?</p>
<p>For example:</p>
<pre><code>import win32file, win32api
for logDrive in win32api.GetLogicalDriveStrings().split("\x00"):
if win32file.GetDriveType(logDrive) != win32file.DRIVE_REMOTE: continue
# get server and share name here
</code></pre>
<p>Is there a handy api call for this?</p>
<p>Thanks.</p>
| 2
|
2009-02-26T17:00:07Z
| 591,452
|
<p>You'll have to call the win32 API: <a href="http://msdn.microsoft.com/en-us/library/aa385474%28VS.85%29.aspx" rel="nofollow">WNetGetUniversalName</a></p>
| 2
|
2009-02-26T17:01:34Z
|
[
"python",
"winapi"
] |
How can you programmatically tell the CPython interpreter to enter interactive mode when done?
| 591,520
|
<p>If you invoke the cpython interpreter with the -i option, it will enter the interactive mode upon completing any commands or scripts it has been given to run. Is there a way, within a program to get the interpreter to do this even when it has not been given -i? The obvious use case is in debugging by interactively inspecting the state when an exceptional condition has occurred.</p>
| 8
|
2009-02-26T17:21:57Z
| 591,531
|
<p>You want the <a href="http://docs.python.org/library/code.html">code module</a>.</p>
<pre><code>#!/usr/bin/env python
import code
code.interact("Enter Here")
</code></pre>
| 13
|
2009-02-26T17:25:18Z
|
[
"cpython",
"python"
] |
How can you programmatically tell the CPython interpreter to enter interactive mode when done?
| 591,520
|
<p>If you invoke the cpython interpreter with the -i option, it will enter the interactive mode upon completing any commands or scripts it has been given to run. Is there a way, within a program to get the interpreter to do this even when it has not been given -i? The obvious use case is in debugging by interactively inspecting the state when an exceptional condition has occurred.</p>
| 8
|
2009-02-26T17:21:57Z
| 591,971
|
<p>Set the PYTHONINSPECT environment variable. This can also be done in the script itself:</p>
<pre><code>import os
os.environ["PYTHONINSPECT"] = "1"
</code></pre>
<p>For debugging unexpected exceptions, you could also use this nice recipe <a href="http://code.activestate.com/recipes/65287/">http://code.activestate.com/recipes/65287/</a></p>
| 5
|
2009-02-26T19:06:18Z
|
[
"cpython",
"python"
] |
How can you programmatically tell the CPython interpreter to enter interactive mode when done?
| 591,520
|
<p>If you invoke the cpython interpreter with the -i option, it will enter the interactive mode upon completing any commands or scripts it has been given to run. Is there a way, within a program to get the interpreter to do this even when it has not been given -i? The obvious use case is in debugging by interactively inspecting the state when an exceptional condition has occurred.</p>
| 8
|
2009-02-26T17:21:57Z
| 593,013
|
<p>The <a href="http://code.activestate.com/recipes/65287/" rel="nofollow">recipe</a> metioned in the other answer using <code>sys.excepthook</code>, sounds like what you want. Otherwise, you could run <code>code.interact</code> on program exit:</p>
<pre><code>import code
import sys
sys.exitfunc = code.interact
</code></pre>
| 3
|
2009-02-26T23:49:05Z
|
[
"cpython",
"python"
] |
How can you programmatically tell the CPython interpreter to enter interactive mode when done?
| 591,520
|
<p>If you invoke the cpython interpreter with the -i option, it will enter the interactive mode upon completing any commands or scripts it has been given to run. Is there a way, within a program to get the interpreter to do this even when it has not been given -i? The obvious use case is in debugging by interactively inspecting the state when an exceptional condition has occurred.</p>
| 8
|
2009-02-26T17:21:57Z
| 17,989,239
|
<p>The best way to do this that I know of is:</p>
<pre><code>from IPython import embed
embed()
</code></pre>
<p>which allows access to variables in the current scope and brings you the full power of IPython.</p>
| 1
|
2013-08-01T08:48:04Z
|
[
"cpython",
"python"
] |
pygame function appears to be being ignored
| 591,776
|
<p>I'm building a relatively simple programme to test collision detection, it's all working fine at the moment except one thing, I'm trying to make the background colour change randomly, the only issue is that it appears to be completely skipping the function to do this;</p>
<pre><code>import pygame
from pygame.locals import *
import random, math, time, sys
pygame.init()
Surface = pygame.display.set_mode((800,600))
backgroundr = int(random.random()*255)+1
backgroundg = int(random.random()*255)+1
backgroundb = int(random.random()*255)+1
Circles = []
class Circle:
def __init__(self):
self.radius = int(random.random()*50) + 1
self.x = random.randint(self.radius, 800-self.radius)
self.y = random.randint(self.radius, 600-self.radius)
self.speedx = 0.5*(random.random()+1.0)
self.speedy = 0.5*(random.random()+1.0)
self.r = int(random.random()*255)+1
self.g = int(random.random()*255)+1
self.b = int(random.random()*255)+1
## self.mass = math.sqrt(self.radius)
for x in range(int(random.random()*30) + 1):
Circles.append(Circle())
def CircleCollide(C1,C2):
C1Speed = math.sqrt((C1.speedx**2)+(C1.speedy**2))
XDiff = -(C1.x-C2.x)
YDiff = -(C1.y-C2.y)
if XDiff > 0:
if YDiff > 0:
Angle = math.degrees(math.atan(YDiff/XDiff))
XSpeed = -C1Speed*math.cos(math.radians(Angle))
YSpeed = -C1Speed*math.sin(math.radians(Angle))
elif YDiff < 0:
Angle = math.degrees(math.atan(YDiff/XDiff))
XSpeed = -C1Speed*math.cos(math.radians(Angle))
YSpeed = -C1Speed*math.sin(math.radians(Angle))
elif XDiff < 0:
if YDiff > 0:
Angle = 180 + math.degrees(math.atan(YDiff/XDiff))
XSpeed = -C1Speed*math.cos(math.radians(Angle))
YSpeed = -C1Speed*math.sin(math.radians(Angle))
elif YDiff < 0:
Angle = -180 + math.degrees(math.atan(YDiff/XDiff))
XSpeed = -C1Speed*math.cos(math.radians(Angle))
YSpeed = -C1Speed*math.sin(math.radians(Angle))
elif XDiff == 0:
if YDiff > 0:
Angle = -90
else:
Angle = 90
XSpeed = C1Speed*math.cos(math.radians(Angle))
YSpeed = C1Speed*math.sin(math.radians(Angle))
elif YDiff == 0:
if XDiff < 0:
Angle = 0
else:
Angle = 180
XSpeed = C1Speed*math.cos(math.radians(Angle))
YSpeed = C1Speed*math.sin(math.radians(Angle))
C1.speedx = XSpeed
C1.speedy = YSpeed
C1.r = int(random.random()*255)+1
C1.g = int(random.random()*255)+1
C1.b = int(random.random()*255)+1
C2.r = int(random.random()*255)+1
C2.g = int(random.random()*255)+1
C2.b = int(random.random()*255)+1
def ColourCheck():
checknumber = int(random.random()*50)+1
if checknumber == 50:
backgroundr = int(random.random()*255)+1
backgroundg = int(random.random()*255)+1
backgroundb = int(random.random()*255)+1
def Move():
for Circle in Circles:
Circle.x += Circle.speedx
Circle.y += Circle.speedy
def CollisionDetect():
for Circle in Circles:
if Circle.x < Circle.radius or Circle.x > 800-Circle.radius:
Circle.speedx *= -1
Circle.r = int(random.random()*255)+1
Circle.g = int(random.random()*255)+1
Circle.b = int(random.random()*255)+1
if Circle.y < Circle.radius or Circle.y > 600-Circle.radius:
Circle.speedy *= -1
Circle.r = int(random.random()*255)+1
Circle.g = int(random.random()*255)+1
Circle.b = int(random.random()*255)+1
for Circle in Circles:
for Circle2 in Circles:
if Circle != Circle2:
if math.sqrt( ((Circle.x-Circle2.x)**2) + ((Circle.y-Circle2.y)**2) ) <= (Circle.radius+Circle2.radius):
CircleCollide(Circle,Circle2)
def Draw():
Surface.fill((backgroundr,backgroundg,backgroundb))
for Circle in Circles:
pygame.draw.circle(Surface,(Circle.r,Circle.g,Circle.b),(int(Circle.x),int(600-Circle.y)),Circle.radius)
pygame.display.flip()
def GetInput():
keystate = pygame.key.get_pressed()
for event in pygame.event.get():
if event.type == QUIT or keystate[K_ESCAPE]:
pygame.quit(); sys.exit()
def main():
while True:
ColourCheck()
GetInput()
Move()
CollisionDetect()
Draw()
if __name__ == '__main__': main()
</code></pre>
<p>it's the <code>ColourCheck</code> function that's being ignored, any ideas why?</p>
| 2
|
2009-02-26T18:15:48Z
| 591,821
|
<p>I believe backgroundr, backgroundg, and backgroundb are local variables to your ColourCheck() function.</p>
<p>If you're determined to use global variables, try this at the top of your file:</p>
<pre><code>global backgroundr;
global backgroundg;
global backgroundb;
backgroundr = int(random.random()*255)+1
backgroundg = int(random.random()*255)+1
backgroundb = int(random.random()*255)+1
</code></pre>
<p>and this in your function:</p>
<pre><code>def ColourCheck():
global backgroundr;
global backgroundg;
global backgroundb;
checknumber = int(random.random()*50)+1
if checknumber == 50:
backgroundr = int(random.random()*255)+1
backgroundg = int(random.random()*255)+1
backgroundb = int(random.random()*255)+1
</code></pre>
| 6
|
2009-02-26T18:26:27Z
|
[
"python",
"function",
"pygame"
] |
pygame function appears to be being ignored
| 591,776
|
<p>I'm building a relatively simple programme to test collision detection, it's all working fine at the moment except one thing, I'm trying to make the background colour change randomly, the only issue is that it appears to be completely skipping the function to do this;</p>
<pre><code>import pygame
from pygame.locals import *
import random, math, time, sys
pygame.init()
Surface = pygame.display.set_mode((800,600))
backgroundr = int(random.random()*255)+1
backgroundg = int(random.random()*255)+1
backgroundb = int(random.random()*255)+1
Circles = []
class Circle:
def __init__(self):
self.radius = int(random.random()*50) + 1
self.x = random.randint(self.radius, 800-self.radius)
self.y = random.randint(self.radius, 600-self.radius)
self.speedx = 0.5*(random.random()+1.0)
self.speedy = 0.5*(random.random()+1.0)
self.r = int(random.random()*255)+1
self.g = int(random.random()*255)+1
self.b = int(random.random()*255)+1
## self.mass = math.sqrt(self.radius)
for x in range(int(random.random()*30) + 1):
Circles.append(Circle())
def CircleCollide(C1,C2):
C1Speed = math.sqrt((C1.speedx**2)+(C1.speedy**2))
XDiff = -(C1.x-C2.x)
YDiff = -(C1.y-C2.y)
if XDiff > 0:
if YDiff > 0:
Angle = math.degrees(math.atan(YDiff/XDiff))
XSpeed = -C1Speed*math.cos(math.radians(Angle))
YSpeed = -C1Speed*math.sin(math.radians(Angle))
elif YDiff < 0:
Angle = math.degrees(math.atan(YDiff/XDiff))
XSpeed = -C1Speed*math.cos(math.radians(Angle))
YSpeed = -C1Speed*math.sin(math.radians(Angle))
elif XDiff < 0:
if YDiff > 0:
Angle = 180 + math.degrees(math.atan(YDiff/XDiff))
XSpeed = -C1Speed*math.cos(math.radians(Angle))
YSpeed = -C1Speed*math.sin(math.radians(Angle))
elif YDiff < 0:
Angle = -180 + math.degrees(math.atan(YDiff/XDiff))
XSpeed = -C1Speed*math.cos(math.radians(Angle))
YSpeed = -C1Speed*math.sin(math.radians(Angle))
elif XDiff == 0:
if YDiff > 0:
Angle = -90
else:
Angle = 90
XSpeed = C1Speed*math.cos(math.radians(Angle))
YSpeed = C1Speed*math.sin(math.radians(Angle))
elif YDiff == 0:
if XDiff < 0:
Angle = 0
else:
Angle = 180
XSpeed = C1Speed*math.cos(math.radians(Angle))
YSpeed = C1Speed*math.sin(math.radians(Angle))
C1.speedx = XSpeed
C1.speedy = YSpeed
C1.r = int(random.random()*255)+1
C1.g = int(random.random()*255)+1
C1.b = int(random.random()*255)+1
C2.r = int(random.random()*255)+1
C2.g = int(random.random()*255)+1
C2.b = int(random.random()*255)+1
def ColourCheck():
checknumber = int(random.random()*50)+1
if checknumber == 50:
backgroundr = int(random.random()*255)+1
backgroundg = int(random.random()*255)+1
backgroundb = int(random.random()*255)+1
def Move():
for Circle in Circles:
Circle.x += Circle.speedx
Circle.y += Circle.speedy
def CollisionDetect():
for Circle in Circles:
if Circle.x < Circle.radius or Circle.x > 800-Circle.radius:
Circle.speedx *= -1
Circle.r = int(random.random()*255)+1
Circle.g = int(random.random()*255)+1
Circle.b = int(random.random()*255)+1
if Circle.y < Circle.radius or Circle.y > 600-Circle.radius:
Circle.speedy *= -1
Circle.r = int(random.random()*255)+1
Circle.g = int(random.random()*255)+1
Circle.b = int(random.random()*255)+1
for Circle in Circles:
for Circle2 in Circles:
if Circle != Circle2:
if math.sqrt( ((Circle.x-Circle2.x)**2) + ((Circle.y-Circle2.y)**2) ) <= (Circle.radius+Circle2.radius):
CircleCollide(Circle,Circle2)
def Draw():
Surface.fill((backgroundr,backgroundg,backgroundb))
for Circle in Circles:
pygame.draw.circle(Surface,(Circle.r,Circle.g,Circle.b),(int(Circle.x),int(600-Circle.y)),Circle.radius)
pygame.display.flip()
def GetInput():
keystate = pygame.key.get_pressed()
for event in pygame.event.get():
if event.type == QUIT or keystate[K_ESCAPE]:
pygame.quit(); sys.exit()
def main():
while True:
ColourCheck()
GetInput()
Move()
CollisionDetect()
Draw()
if __name__ == '__main__': main()
</code></pre>
<p>it's the <code>ColourCheck</code> function that's being ignored, any ideas why?</p>
| 2
|
2009-02-26T18:15:48Z
| 591,824
|
<p><code>Move()</code>, <code>CollisionDetect()</code>, and <code>Draw()</code> all refer to <code>Circles</code>, but don't declare it global. Try adding a <code>global Circles</code> line to the beginning of each function. Also, I'd recommend changing your variables to lower-case; not only does an initial cap typically indicate a class in Python, but you're actually generating (insignificant) collisions between the <code>Circle</code> variable and the <code>Circle</code> class.</p>
<p>For example:</p>
<pre><code>circles = []
# ...
for x in range(int(random.random()*30) + 1):
circles.append(Circle())
# ...
def Move():
global circles
for circle in circles:
circle.x += circle.speedx
circle.y += circle.speedy
# ...
</code></pre>
<p><strong>Edit:</strong></p>
<p>And as Nathan notes, your <code>backgroundX</code> variables also need to be declared global in <code>ColorCheck()</code> and <code>Draw()</code>.</p>
<p>You might consider wrapping all of these functions into a <code>Game</code> class (or some such), to avoid working with so many globals.</p>
| 0
|
2009-02-26T18:27:08Z
|
[
"python",
"function",
"pygame"
] |
Is there a python equivalent of the prefuse visualization toolkit?
| 591,839
|
<p>The <a href="http://prefuse.org/" rel="nofollow">prefuse visualization toolkit</a> is pretty nice, but for Java. I was wondering if there was something similar for python. My primary interest is being able to navigate dynamic graphs.</p>
| 10
|
2009-02-26T18:30:45Z
| 591,847
|
<p><a href="http://mayavi.sourceforge.net/" rel="nofollow">MayaVi</a></p>
| -1
|
2009-02-26T18:33:07Z
|
[
"python",
"visualization",
"prefuse"
] |
Is there a python equivalent of the prefuse visualization toolkit?
| 591,839
|
<p>The <a href="http://prefuse.org/" rel="nofollow">prefuse visualization toolkit</a> is pretty nice, but for Java. I was wondering if there was something similar for python. My primary interest is being able to navigate dynamic graphs.</p>
| 10
|
2009-02-26T18:30:45Z
| 591,851
|
<p>Note that prefuse now has the <a href="http://flare.prefuse.org/" rel="nofollow">flare</a> package which uses flash. </p>
<p>Connect that to a Python backend via <a href="http://mdp.cti.depaul.edu/" rel="nofollow">web2py</a> and you've got a great web app (just an idea).</p>
| 0
|
2009-02-26T18:35:03Z
|
[
"python",
"visualization",
"prefuse"
] |
Is there a python equivalent of the prefuse visualization toolkit?
| 591,839
|
<p>The <a href="http://prefuse.org/" rel="nofollow">prefuse visualization toolkit</a> is pretty nice, but for Java. I was wondering if there was something similar for python. My primary interest is being able to navigate dynamic graphs.</p>
| 10
|
2009-02-26T18:30:45Z
| 592,004
|
<p>You could try using prefuse with <a href="http://jpype.sourceforge.net/" rel="nofollow">JPype</a>, if you can't find a suitable replacement.</p>
| 0
|
2009-02-26T19:16:35Z
|
[
"python",
"visualization",
"prefuse"
] |
Is there a python equivalent of the prefuse visualization toolkit?
| 591,839
|
<p>The <a href="http://prefuse.org/" rel="nofollow">prefuse visualization toolkit</a> is pretty nice, but for Java. I was wondering if there was something similar for python. My primary interest is being able to navigate dynamic graphs.</p>
| 10
|
2009-02-26T18:30:45Z
| 592,336
|
<p>If you're using a Mac, check out <a href="http://nodebox.net/code/index.php/Home" rel="nofollow">NodeBox</a>. One extension it offers is a <a href="http://nodebox.net/code/index.php/Graphing" rel="nofollow">graph library</a> that looks pretty good. Poke around in the <a href="http://nodebox.net/code/index.php/Gallery" rel="nofollow">NodeBox gallery</a> some to find something similar to your problem and it should have some helpful links.</p>
| 2
|
2009-02-26T20:38:22Z
|
[
"python",
"visualization",
"prefuse"
] |
Is there a python equivalent of the prefuse visualization toolkit?
| 591,839
|
<p>The <a href="http://prefuse.org/" rel="nofollow">prefuse visualization toolkit</a> is pretty nice, but for Java. I was wondering if there was something similar for python. My primary interest is being able to navigate dynamic graphs.</p>
| 10
|
2009-02-26T18:30:45Z
| 849,870
|
<p>I know this is not exactly python, but you could use prefuse in python <em>through</em> <a href="http://jython.org" rel="nofollow">jython</a></p>
<p>Something along the lines of:</p>
<p>Add prefuse to your path:</p>
<p><code>export JYTHONPATH=$JYTHONPATH:prefuse.jar</code></p>
<p>and</p>
<p><code>>>> import prefuse</code></p>
<p>from your jython machinery</p>
<p>this <a href="http://github.com/fajran" rel="nofollow">guy</a> has an example of using prefuse from jython <a href="http://gist.github.com/32288" rel="nofollow">here</a></p>
| 6
|
2009-05-11T20:10:57Z
|
[
"python",
"visualization",
"prefuse"
] |
Is there a python equivalent of the prefuse visualization toolkit?
| 591,839
|
<p>The <a href="http://prefuse.org/" rel="nofollow">prefuse visualization toolkit</a> is pretty nice, but for Java. I was wondering if there was something similar for python. My primary interest is being able to navigate dynamic graphs.</p>
| 10
|
2009-02-26T18:30:45Z
| 988,053
|
<p>You might want to check out <a href="http://people.csail.mit.edu/rasmus/summon/index.shtml" rel="nofollow">SUMMON</a>, a visualization system that uses python but handles fairly large data sets. There's an impressive video of visualizing and navigating a massive tree. (Can't post the link because I'm a first time poster. It's on the SUMMON front page.)</p>
| 3
|
2009-06-12T17:48:49Z
|
[
"python",
"visualization",
"prefuse"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.