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
Event system in Python
1,092,531
<p>What event system for Python do you use? I'm already aware of <a href="http://pydispatcher.sourceforge.net/">pydispatcher</a>, but I was wondering what else can be found, or is commonly used?</p> <p>I'm not interested in event managers that are part of large frameworks, I'd rather use a small bare-bones solution that I can easily extend.</p>
111
2009-07-07T14:00:51Z
35,957,226
<p>I made a variation of Longpoke's minimalistic approach that also ensures the signatures for both callees and callers:</p> <pre><code>class EventHook(object): ''' A simple implementation of the Observer-Pattern. The user can specify an event signature upon inizializazion, defined by kwargs in the form of argumentname=class (e.g. id=int). The arguments' types are not checked in this implementation though. Callables with a fitting signature can be added with += or removed with -=. All listeners can be notified by calling the EventHook class with fitting arguments. &gt;&gt;&gt; event = EventHook(id=int, data=dict) &gt;&gt;&gt; event += lambda id, data: print("%d %s" % (id, data)) &gt;&gt;&gt; event(id=5, data={"foo": "bar"}) 5 {'foo': 'bar'} &gt;&gt;&gt; event = EventHook(id=int) &gt;&gt;&gt; event += lambda wrong_name: None Traceback (most recent call last): ... ValueError: Listener must have these arguments: (id=int) &gt;&gt;&gt; event = EventHook(id=int) &gt;&gt;&gt; event += lambda id: None &gt;&gt;&gt; event(wrong_name=0) Traceback (most recent call last): ... ValueError: This EventHook must be called with these arguments: (id=int) ''' def __init__(self, **signature): self._signature = signature self._argnames = set(signature.keys()) self._handlers = [] def _kwargs_str(self): return ", ".join(k+"="+v.__name__ for k, v in self._signature.items()) def __iadd__(self, handler): params = inspect.signature(handler).parameters valid = True argnames = set(n for n in params.keys()) if argnames != self._argnames: valid = False for p in params.values(): if p.kind == p.VAR_KEYWORD: valid = True break if p.kind not in (p.POSITIONAL_OR_KEYWORD, p.KEYWORD_ONLY): valid = False break if not valid: raise ValueError("Listener must have these arguments: (%s)" % self._kwargs_str()) self._handlers.append(handler) return self def __isub__(self, handler): self._handlers.remove(handler) return self def __call__(self, *args, **kwargs): if args or set(kwargs.keys()) != self._argnames: raise ValueError("This EventHook must be called with these " + "keyword arguments: (%s)" % self._kwargs_str()) for handler in self._handlers[:]: handler(**kwargs) def __repr__(self): return "EventHook(%s)" % self._kwargs_str() </code></pre>
1
2016-03-12T11:45:23Z
[ "python", "events", "event-handling", "dispatcher" ]
AppEngine server cannot import atom module
1,092,648
<p>I have gdata library install on my ArchLinux, and a simple application which imports atom library at the beginning, when I run gapp engine and access that web app,</p> <blockquote> <p>$ python2.5 ./dev_appserver.py ~/myapp</p> </blockquote> <p>It throws exception 'No module named atom'. But when I run 'import atom' in Python2.5 interactive mode, it works well. How can I import atom module in my GAppEngine applications?</p>
3
2009-07-07T14:26:49Z
1,092,753
<p>Add atom.py to the same directory you keep you GAE Python sources in, and make sure it's uploaded to the server when you upload your app. (The upload happens when you do <code>appcfg.py update myapp/</code> unless you go out of your way to stop it; use the <code>--verbose</code> flag on the command to see exactly what's being uploaded or updated).</p> <p>(Or, if it's a large file, make a zipfile with it and in your handler append that zipfile to sys.path; see <a href="http://code.google.com/appengine/articles/django10%5Fzipimport.html" rel="nofollow">zipimport</a> for example).</p> <p>This assumes that you have a single file <code>atom.py</code> which is what you're importing; if that file in turns imports others you'll have to make those others available too in similar ways, and so on (see <a href="http://www.python.org/doc/2.5.2/lib/module-modulefinder.html" rel="nofollow">modulefinder</a> in Python's standard library for ways to find all modules you need).</p> <p>If <code>atom</code> is not a module but a package, then what you get on <code>import</code> is the <code>__init__.py</code> file in the directory that's the package; so the same advice applies (and zipimport becomes much more attractive since you can easily package up any directory structure e.g. with a <code>zip -r</code> command from the Linux command line).</p> <p>If at any point (as modulefinder will help you discover) there is a dependency on a third party C-coded extension (a <code>.so</code> or <code>.pyd</code> file that Python can use but is not written in pure Python) that is not in the short list supplied with GAE (see <a href="http://code.google.com/appengine/docs/python/tools/libraries.html" rel="nofollow">here</a>), then that Python code is not usable on GAE, as GAE supports only pure-Python. If this is the case then you must look for alternatives that <em>are</em> supported on GAE, i.e. pure-Python ways to obtain the same functionality you require.</p>
11
2009-07-07T14:43:09Z
[ "python", "google-app-engine" ]
how can I not distribute my secret key (facebook api) while using python?
1,092,942
<p>I'm writing a facebook desktop application for the first time using the PyFacebook api. Up until now, since I've been experimenting, I just passed the secret key along with the api key to the Facebook constructor like so:</p> <pre><code>import facebook fb = facebook.Facebook("my_api_key", "my_secret_key") </code></pre> <p>and then logged in (<code>fb.login()</code> opens a browser) without any trouble. But now, I want to distribute the code and since it's python and opensource, I want to have some way of protecting my secret key. The wiki mentions I can use a server and ask for my secret key using the server each time my app runs (as I understand), but I have no clue as to how to start doing this, and how this should be done. I have never done web programming and don't know where I can get a server, and how to get the server to do what is needed in this case, and I don't know how can I use that server. I would really appreciate some help!</p> <p>Thank you.</p>
2
2009-07-07T15:15:29Z
1,093,178
<p>EDIT: cmb's session keys approach is better than the proxy described below. Config files and GAE are still applicable. /EDIT</p> <p>You could take a couple approaches. If your code is open-source and will be used by other developers, you could allow the secret key to be set in a configuration file. When you distribute the code, place a dummy key in the file and create some instructions on how to obtain and set the key in the config file.</p> <p>Alternately, if you want to do the server approach, you'll basically be creating a proxy* that will take requests, add the secret key and then forward them on to Facebook. A good, free (unless/until your app gets a lot of users) Python-based service is <a href="http://code.google.com/appengine/" rel="nofollow">Google App Engine</a>. They also have a bunch of tutorial videos to get you started. </p> <p>* E.g., when myservice.appspot.com/getUserInfo?uid=12345 is called, your service will execute something like the following.</p> <pre><code>userinfo = fb.users.getInfo(self.request.get('uid')...) </code></pre> <p>Ideally, you'd want to abstract it enough that you don't have to explicitly implement every FB API call you make.</p> <p>One last thing to keep in mind is that many FB API calls do not require the secret key to be passed.</p>
1
2009-07-07T15:53:07Z
[ "python", "facebook" ]
how can I not distribute my secret key (facebook api) while using python?
1,092,942
<p>I'm writing a facebook desktop application for the first time using the PyFacebook api. Up until now, since I've been experimenting, I just passed the secret key along with the api key to the Facebook constructor like so:</p> <pre><code>import facebook fb = facebook.Facebook("my_api_key", "my_secret_key") </code></pre> <p>and then logged in (<code>fb.login()</code> opens a browser) without any trouble. But now, I want to distribute the code and since it's python and opensource, I want to have some way of protecting my secret key. The wiki mentions I can use a server and ask for my secret key using the server each time my app runs (as I understand), but I have no clue as to how to start doing this, and how this should be done. I have never done web programming and don't know where I can get a server, and how to get the server to do what is needed in this case, and I don't know how can I use that server. I would really appreciate some help!</p> <p>Thank you.</p>
2
2009-07-07T15:15:29Z
1,093,421
<p>The <a href="http://wiki.developers.facebook.com/index.php/Desktop%5FApp%5FAuth%5FProcess" rel="nofollow">relevant page on the FB developer wiki</a> recommends a server component that just keeps your secret key and handles <code>auth.getSession()</code>, then gives your desktop app a session key. See that link for details.</p>
3
2009-07-07T16:38:49Z
[ "python", "facebook" ]
How do I check what version of Python is running my script?
1,093,322
<p>How can I check what version of the Python Interpreter is interpreting my script?</p>
524
2009-07-07T16:17:49Z
1,093,331
<p>This information is available in the <a href="http://docs.python.org/2/library/sys.html#sys.version">sys.version</a> string in the <a href="http://docs.python.org/2/library/sys.html">sys</a> module:</p> <pre><code>&gt;&gt;&gt; import sys </code></pre> <p>Human readable:</p> <pre><code>&gt;&gt;&gt; print (sys.version) #parentheses necessary in python 3. 2.5.2 (r252:60911, Jul 31 2008, 17:28:52) [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] </code></pre> <p>For further processing:</p> <pre><code>&gt;&gt;&gt; sys.version_info (2, 5, 2, 'final', 0) # or &gt;&gt;&gt; sys.hexversion 34014192 </code></pre> <p>To ensure a script runs with a minimal version requirement of the Python interpreter add this to your code:</p> <pre><code>assert sys.version_info &gt;= (2,5) </code></pre> <p>This compares major and minor version information. Add micro (=<code>0</code>, <code>1</code>, etc) and even releaselevel (=<code>'alpha'</code>,<code>'final'</code>, etc) to the tuple as you like. Note however, that it is almost always better to "duck" check if a certain feature is there, and if not, workaround (or bail out). Sometimes features go away in newer releases, being replaced by others.</p>
636
2009-07-07T16:20:12Z
[ "python", "version" ]
How do I check what version of Python is running my script?
1,093,322
<p>How can I check what version of the Python Interpreter is interpreting my script?</p>
524
2009-07-07T16:17:49Z
1,093,336
<pre><code>import sys sys.version.split(' ')[0] </code></pre> <p>sys.version gives you what you want, just pick the first number :)</p>
-1
2009-07-07T16:20:59Z
[ "python", "version" ]
How do I check what version of Python is running my script?
1,093,322
<p>How can I check what version of the Python Interpreter is interpreting my script?</p>
524
2009-07-07T16:17:49Z
3,016,171
<p>Your best bet is probably something like so: </p> <pre><code>&gt;&gt;&gt; import sys &gt;&gt;&gt; sys.version_info (2, 6, 4, 'final', 0) &gt;&gt;&gt; if not sys.version_info[:2] == (2, 6): ... print "Error, I need python 2.6" ... else: ... from my_module import twoPointSixCode &gt;&gt;&gt; </code></pre> <p>Additionally, you can always wrap your imports in a simple try, which should catch syntax errors. And, to @Heikki's point, this code will be compatible with much older versions of python: </p> <pre><code>&gt;&gt;&gt; try: ... from my_module import twoPointSixCode ... except Exception: ... print "can't import, probably because your python is too old!" &gt;&gt;&gt; </code></pre>
46
2010-06-10T16:06:05Z
[ "python", "version" ]
How do I check what version of Python is running my script?
1,093,322
<p>How can I check what version of the Python Interpreter is interpreting my script?</p>
524
2009-07-07T16:17:49Z
3,016,198
<p>Put something like:</p> <pre><code>#!/usr/bin/env/python import sys if sys.version_info&lt;(2,6,0): sys.stderr.write("You need python 2.6 or later to run this script\n") exit(1) </code></pre> <p>at the top of your script.</p> <p>Note that depending on what else is in your script, older versions of python than the target may not be able to even load the script, so won't get far enough to report this error. As a workaround, you can run the above in a script that imports the script with the more modern code.</p>
40
2010-06-10T16:08:54Z
[ "python", "version" ]
How do I check what version of Python is running my script?
1,093,322
<p>How can I check what version of the Python Interpreter is interpreting my script?</p>
524
2009-07-07T16:17:49Z
3,016,234
<p>Like Seth said, the main script could check <code>sys.version_info</code> (but note that that didn't appear until 2.0, so if you want to support older versions you would need to check another version property of the sys module).</p> <p>But you still need to take care of not using any Python language features in the file that are not available in older Python versions. For example, this is allowed in Python 2.5 and later:</p> <pre><code>try: pass except: pass finally: pass </code></pre> <p>but won't work in older Python versions, because you could only have except OR finally match the try. So for compatibility with older Python versions you need to write:</p> <pre><code>try: try: pass except: pass finally: pass </code></pre>
3
2010-06-10T16:12:50Z
[ "python", "version" ]
How do I check what version of Python is running my script?
1,093,322
<p>How can I check what version of the Python Interpreter is interpreting my script?</p>
524
2009-07-07T16:17:49Z
3,018,075
<p>I like <code>sys.hexversion</code> for stuff like this.</p> <p><a href="http://docs.python.org/library/sys.html#sys.hexversion">http://docs.python.org/library/sys.html#sys.hexversion</a></p> <pre><code>&gt;&gt;&gt; import sys &gt;&gt;&gt; sys.hexversion 33883376 &gt;&gt;&gt; '%x' % sys.hexversion '20504f0' &gt;&gt;&gt; sys.hexversion &lt; 0x02060000 True </code></pre>
74
2010-06-10T20:08:35Z
[ "python", "version" ]
How do I check what version of Python is running my script?
1,093,322
<p>How can I check what version of the Python Interpreter is interpreting my script?</p>
524
2009-07-07T16:17:49Z
7,730,858
<p>To see a MSDOS script to check the version before running the Python interpreter (to avoid Python version syntax exceptions) See solution:</p> <p><a href="http://stackoverflow.com/questions/446052/python-best-way-to-check-for-python-version-in-program-that-uses-new-language-fe/7642536#7642536">Python: Best way to check for Python version in program that uses new language features?</a></p> <p>and </p> <p>MS script; Python version check prelaunch of Python module <a href="http://pastebin.com/aAuJ91FQ" rel="nofollow">http://pastebin.com/aAuJ91FQ</a> (script likely easy to convert to other OS scripts.)</p>
0
2011-10-11T18:40:33Z
[ "python", "version" ]
How do I check what version of Python is running my script?
1,093,322
<p>How can I check what version of the Python Interpreter is interpreting my script?</p>
524
2009-07-07T16:17:49Z
17,672,432
<p>if you are working on linux just give command "python" output will be like this</p> <p>**Python 2.4.3 (#1, Jun 11 2009, 14:09:37)</p> <p>[GCC 4.1.2 20080704 (Red Hat 4.1.2-44)] on linux2</p> <p>Type "help", "copyright", "credits" or "license" for more information.**</p>
1
2013-07-16T09:10:48Z
[ "python", "version" ]
How do I check what version of Python is running my script?
1,093,322
<p>How can I check what version of the Python Interpreter is interpreting my script?</p>
524
2009-07-07T16:17:49Z
17,796,193
<p>From the command line (note the capital 'V'):</p> <pre><code>python -V </code></pre> <p>This is documented in 'man python'.</p>
125
2013-07-22T19:50:40Z
[ "python", "version" ]
How do I check what version of Python is running my script?
1,093,322
<p>How can I check what version of the Python Interpreter is interpreting my script?</p>
524
2009-07-07T16:17:49Z
25,477,839
<p>I found this method somewhere.</p> <pre><code>&gt;&gt;&gt; from platform import python_version &gt;&gt;&gt; print python_version() 2.7.8 </code></pre>
25
2014-08-25T01:11:33Z
[ "python", "version" ]
How do I check what version of Python is running my script?
1,093,322
<p>How can I check what version of the Python Interpreter is interpreting my script?</p>
524
2009-07-07T16:17:49Z
25,631,445
<p>Here's a short commandline version which exits straight away (handy for scripts and automated execution):</p> <pre><code>python -c 'print __import__("sys").version' </code></pre> <p>Or just the major, minor and micro:</p> <pre><code>python -c 'print __import__("sys").version_info[:1]' # (2,) python -c 'print __import__("sys").version_info[:2]' # (2, 7) python -c 'print __import__("sys").version_info[:3]' # (2, 7, 6) </code></pre>
9
2014-09-02T20:02:50Z
[ "python", "version" ]
How do I check what version of Python is running my script?
1,093,322
<p>How can I check what version of the Python Interpreter is interpreting my script?</p>
524
2009-07-07T16:17:49Z
35,294,211
<h1>The simplest way</h1> <p>Just type python in your terminal and you can see the the version as like following </p> <pre><code>desktop:~$ python Python 2.7.6 (default, Jun 22 2015, 18:00:18) [GCC 4.8.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; </code></pre>
4
2016-02-09T14:11:24Z
[ "python", "version" ]
Run web.py as daemon
1,093,485
<p>I have a simple web.py program to load data. In the server I don't want to install apache or any webserver.</p> <p>I try to put it as a background service with <a href="http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/" rel="nofollow">http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/</a> </p> <p>And subclassing: (from <a href="http://www.jejik.com/files/examples/daemon.py" rel="nofollow">http://www.jejik.com/files/examples/daemon.py</a>)</p> <pre><code>class Daemon: def start(self): """ Start the daemon """ ... PID CHECKS.... # Start the daemon self.daemonize() self.run() #My code class WebService(Daemon): def run(self): app.run() if __name__ == "__main__": if DEBUG: app.run() else: service = WebService(os.path.join(DIR_ACTUAL,'ElAdministrador.pid')) if len(sys.argv) == 2: if 'start' == sys.argv[1]: service.start() elif 'stop' == sys.argv[1]: service.stop() elif 'restart' == sys.argv[1]: service.restart() else: print "Unknown command" sys.exit(2) sys.exit(0) else: print "usage: %s start|stop|restart" % sys.argv[0] sys.exit(2) </code></pre> <p>However, the web.py software not load (ie: The service no listen)</p> <p>If I call it directly (ie: No using the daemon code) work fine.</p>
4
2009-07-07T16:51:24Z
1,093,519
<p>I don't think you're telling the daemon to run. You need to instantiate a MyDaemon object and call o.run(). It looks like WebService only starts and stops the service interface to your web app, not the actual web app itself.</p>
0
2009-07-07T16:57:17Z
[ "python", "backgroundworker" ]
Run web.py as daemon
1,093,485
<p>I have a simple web.py program to load data. In the server I don't want to install apache or any webserver.</p> <p>I try to put it as a background service with <a href="http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/" rel="nofollow">http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/</a> </p> <p>And subclassing: (from <a href="http://www.jejik.com/files/examples/daemon.py" rel="nofollow">http://www.jejik.com/files/examples/daemon.py</a>)</p> <pre><code>class Daemon: def start(self): """ Start the daemon """ ... PID CHECKS.... # Start the daemon self.daemonize() self.run() #My code class WebService(Daemon): def run(self): app.run() if __name__ == "__main__": if DEBUG: app.run() else: service = WebService(os.path.join(DIR_ACTUAL,'ElAdministrador.pid')) if len(sys.argv) == 2: if 'start' == sys.argv[1]: service.start() elif 'stop' == sys.argv[1]: service.stop() elif 'restart' == sys.argv[1]: service.restart() else: print "Unknown command" sys.exit(2) sys.exit(0) else: print "usage: %s start|stop|restart" % sys.argv[0] sys.exit(2) </code></pre> <p>However, the web.py software not load (ie: The service no listen)</p> <p>If I call it directly (ie: No using the daemon code) work fine.</p>
4
2009-07-07T16:51:24Z
1,094,810
<p>I finally find the problem.</p> <p>Web.py accept from command-line the optional port number:</p> <pre><code>python code.py 80 </code></pre> <p>And the script also take input from the command-line:</p> <pre><code>python WebServer start </code></pre> <p>then web.py try to use "start" as port number and fail. I don't see the error because was in the bacground. </p> <p>I fix this with a mini-hack:</p> <pre><code>if __name__ == "__main__": if DEBUG: app.run() else: service = WebService(os.path.join(DIR_ACTUAL,'ElAdministrador.pid')) if len(sys.argv) == 2: if 'start' == sys.argv[1]: sys.argv[1] = '8080' service.start() </code></pre>
4
2009-07-07T20:54:41Z
[ "python", "backgroundworker" ]
Run web.py as daemon
1,093,485
<p>I have a simple web.py program to load data. In the server I don't want to install apache or any webserver.</p> <p>I try to put it as a background service with <a href="http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/" rel="nofollow">http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/</a> </p> <p>And subclassing: (from <a href="http://www.jejik.com/files/examples/daemon.py" rel="nofollow">http://www.jejik.com/files/examples/daemon.py</a>)</p> <pre><code>class Daemon: def start(self): """ Start the daemon """ ... PID CHECKS.... # Start the daemon self.daemonize() self.run() #My code class WebService(Daemon): def run(self): app.run() if __name__ == "__main__": if DEBUG: app.run() else: service = WebService(os.path.join(DIR_ACTUAL,'ElAdministrador.pid')) if len(sys.argv) == 2: if 'start' == sys.argv[1]: service.start() elif 'stop' == sys.argv[1]: service.stop() elif 'restart' == sys.argv[1]: service.restart() else: print "Unknown command" sys.exit(2) sys.exit(0) else: print "usage: %s start|stop|restart" % sys.argv[0] sys.exit(2) </code></pre> <p>However, the web.py software not load (ie: The service no listen)</p> <p>If I call it directly (ie: No using the daemon code) work fine.</p>
4
2009-07-07T16:51:24Z
2,828,265
<p>you can start the web.py by using this command</p> <pre><code>/usr/bin/python index.py &gt; log.txt 2&gt;&amp;1 &amp; </code></pre>
2
2010-05-13T15:57:11Z
[ "python", "backgroundworker" ]
Run web.py as daemon
1,093,485
<p>I have a simple web.py program to load data. In the server I don't want to install apache or any webserver.</p> <p>I try to put it as a background service with <a href="http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/" rel="nofollow">http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/</a> </p> <p>And subclassing: (from <a href="http://www.jejik.com/files/examples/daemon.py" rel="nofollow">http://www.jejik.com/files/examples/daemon.py</a>)</p> <pre><code>class Daemon: def start(self): """ Start the daemon """ ... PID CHECKS.... # Start the daemon self.daemonize() self.run() #My code class WebService(Daemon): def run(self): app.run() if __name__ == "__main__": if DEBUG: app.run() else: service = WebService(os.path.join(DIR_ACTUAL,'ElAdministrador.pid')) if len(sys.argv) == 2: if 'start' == sys.argv[1]: service.start() elif 'stop' == sys.argv[1]: service.stop() elif 'restart' == sys.argv[1]: service.restart() else: print "Unknown command" sys.exit(2) sys.exit(0) else: print "usage: %s start|stop|restart" % sys.argv[0] sys.exit(2) </code></pre> <p>However, the web.py software not load (ie: The service no listen)</p> <p>If I call it directly (ie: No using the daemon code) work fine.</p>
4
2009-07-07T16:51:24Z
7,941,807
<p>Instead of overwrite the second argument like you wrote here:</p> <pre><code>if __name__ == "__main__": if DEBUG: app.run() else: service = WebService(os.path.join(DIR_ACTUAL,'ElAdministrador.pid')) if len(sys.argv) == 2: if 'start' == sys.argv[1]: sys.argv[1] = '8080' service.start() </code></pre> <p>you could just delete the second argument on 'start|restart', like this:</p> <pre><code>if __name__ == "__main__": if DEBUG: app.run() else: service = WebService(os.path.join(DIR_ACTUAL,'ElAdministrador.pid')) if len(sys.argv) == 2: if 'start' == sys.argv[1]: delete del sys.argv[1:2] service.start() </code></pre> <p>In this way, the webpy will receive all the arguments you passed from command line except the daemon controller. Then you can run simply:</p> <pre><code>python WebServer start 8080 </code></pre>
0
2011-10-29T21:23:00Z
[ "python", "backgroundworker" ]
Switching databases in TG2 during runtime
1,093,589
<p>I am doing an application which will use multiple sqlite3 databases, prepopuldated with data from an external application. Each database will have the exact same tables, but with different data.</p> <p>I want to be able to switch between these databases according to user input. What is the most elegant way to do that in TurboGears 2?</p>
1
2009-07-07T17:14:52Z
1,387,164
<p>If ALL databases have the same schema then you should be able to create several Sessions using the same model to the different DBs.</p>
1
2009-09-07T00:56:50Z
[ "python", "sqlite", "turbogears", "turbogears2" ]
Switching databases in TG2 during runtime
1,093,589
<p>I am doing an application which will use multiple sqlite3 databases, prepopuldated with data from an external application. Each database will have the exact same tables, but with different data.</p> <p>I want to be able to switch between these databases according to user input. What is the most elegant way to do that in TurboGears 2?</p>
1
2009-07-07T17:14:52Z
1,403,620
<p>Dzhelil,</p> <p>I wrote a blog post a while back about using multiple databases in TG2. You could combine this method with Jorge's suggestion of multiple DBSessions and I think you could do this easily.</p> <p><a href="http://blog.curiasolutions.com/?p=87" rel="nofollow">How to use multiple databases in TurboGears 2.0</a></p> <p>Hope this helps, Seth</p>
1
2009-09-10T06:13:53Z
[ "python", "sqlite", "turbogears", "turbogears2" ]
Switching databases in TG2 during runtime
1,093,589
<p>I am doing an application which will use multiple sqlite3 databases, prepopuldated with data from an external application. Each database will have the exact same tables, but with different data.</p> <p>I want to be able to switch between these databases according to user input. What is the most elegant way to do that in TurboGears 2?</p>
1
2009-07-07T17:14:52Z
1,422,838
<p>I am using two databases for a read-only application. The second database is a cache in case the primary database is down. I use two objects to hold the connection, metadata and compatible <code>Table</code> instances. The top of the view function assigns <code>db = primary</code> or <code>db = secondary</code> and the rest is just queries against <code>db.tableA.join(db.tableB)</code>. I am not using the ORM.</p> <p>The schemata are not strictly identical. The primary database needs a <code>schema.</code> prefix (<code>Table(...schema='schema')</code>) and the cache database does not. To get around this, I create my table objects in a function that takes the schema name as an argument. By calling the function once for each database, I wind up with compatible prefixed and non-prefixed <code>Table</code> objects.</p> <p>At least in Pylons, the SQLAlchemy <code>meta.Session</code> is a <code>ScopedSession</code>. The application's <code>BaseController</code> in <code>appname/lib/base.py</code> calls <code>Session.remove()</code> after each request. It's probably better to have a single <code>Session</code> that talks to both databases, but if you don't you may need to modify your <code>BaseController</code> to call <code>.remove()</code> on each <code>Session</code>.</p>
1
2009-09-14T17:13:56Z
[ "python", "sqlite", "turbogears", "turbogears2" ]
pyserial - How to read the last line sent from a serial device
1,093,598
<p>I have an Arduino connected to my computer running a loop, sending a value over the serial port back to the computer every 100&nbsp;ms. </p> <p>I want to make a Python script that will read from the serial port only every few seconds, so I want it to just see the last thing sent from the Arduino.</p> <p>How do you do this in Pyserial?</p> <p>Here's the code I tried which does't work. It reads the lines sequentially.</p> <pre><code>import serial import time ser = serial.Serial('com4',9600,timeout=1) while 1: time.sleep(10) print ser.readline() #How do I get the most recent line sent from the device? </code></pre>
14
2009-07-07T17:16:43Z
1,093,661
<pre><code>from serial import * from threading import Thread last_received = '' def receiving(ser): global last_received buffer = '' while True: # last_received = ser.readline() buffer += ser.read(ser.inWaiting()) if '\n' in buffer: last_received, buffer = buffer.split('\n')[-2:] if __name__ == '__main__': ser = Serial( port=None, baudrate=9600, bytesize=EIGHTBITS, parity=PARITY_NONE, stopbits=STOPBITS_ONE, timeout=0.1, xonxoff=0, rtscts=0, interCharTimeout=None ) Thread(target=receiving, args=(ser,)).start() </code></pre>
9
2009-07-07T17:27:56Z
[ "python", "serial-port", "arduino", "pyserial" ]
pyserial - How to read the last line sent from a serial device
1,093,598
<p>I have an Arduino connected to my computer running a loop, sending a value over the serial port back to the computer every 100&nbsp;ms. </p> <p>I want to make a Python script that will read from the serial port only every few seconds, so I want it to just see the last thing sent from the Arduino.</p> <p>How do you do this in Pyserial?</p> <p>Here's the code I tried which does't work. It reads the lines sequentially.</p> <pre><code>import serial import time ser = serial.Serial('com4',9600,timeout=1) while 1: time.sleep(10) print ser.readline() #How do I get the most recent line sent from the device? </code></pre>
14
2009-07-07T17:16:43Z
1,093,662
<p>Perhaps I'm misunderstanding your question, but as it's a serial line, you'll have to read everything sent from the Arduino sequentially - it'll be buffered up in the Arduino until you read it.</p> <p>If you want to have a status display which shows the latest thing sent - use a thread which incorporates the code in your question (minus the sleep), and keep the last complete line read as the latest line from the Arduino.</p> <p><strong>Update:</strong> <code>mtasic</code>'s example code is quite good, but if the Arduino has sent a partial line when <code>inWaiting()</code> is called, you'll get a truncated line. Instead, what you want to do is to put the last <em>complete</em> line into <code>last_received</code>, and keep the partial line in <code>buffer</code> so that it can be appended to the next time round the loop. Something like this:</p> <pre><code>def receiving(ser): global last_received buffer_string = '' while True: buffer_string = buffer_string + ser.read(ser.inWaiting()) if '\n' in buffer_string: lines = buffer_string.split('\n') # Guaranteed to have at least 2 entries last_received = lines[-2] #If the Arduino sends lots of empty lines, you'll lose the #last filled line, so you could make the above statement conditional #like so: if lines[-2]: last_received = lines[-2] buffer_string = lines[-1] </code></pre> <p>Regarding use of <code>readline()</code>: Here's what the Pyserial documentation has to say (slightly edited for clarity and with a mention to readlines()):</p> <blockquote> <p>Be careful when using "readline". Do specify a timeout when opening the serial port, otherwise it could block forever if no newline character is received. Also note that "readlines()" only works with a timeout. It depends on having a timeout and interprets that as EOF (end of file).</p> </blockquote> <p>which seems quite reasonable to me!</p>
25
2009-07-07T17:28:01Z
[ "python", "serial-port", "arduino", "pyserial" ]
pyserial - How to read the last line sent from a serial device
1,093,598
<p>I have an Arduino connected to my computer running a loop, sending a value over the serial port back to the computer every 100&nbsp;ms. </p> <p>I want to make a Python script that will read from the serial port only every few seconds, so I want it to just see the last thing sent from the Arduino.</p> <p>How do you do this in Pyserial?</p> <p>Here's the code I tried which does't work. It reads the lines sequentially.</p> <pre><code>import serial import time ser = serial.Serial('com4',9600,timeout=1) while 1: time.sleep(10) print ser.readline() #How do I get the most recent line sent from the device? </code></pre>
14
2009-07-07T17:16:43Z
1,093,742
<p>You will need a loop to read everything sent, with the last call to readline() blocking until the timeout. So:</p> <pre><code>def readLastLine(ser): last_data='' while True: data=ser.readline() if data!='': last_data=data else: return last_data </code></pre>
2
2009-07-07T17:44:05Z
[ "python", "serial-port", "arduino", "pyserial" ]
pyserial - How to read the last line sent from a serial device
1,093,598
<p>I have an Arduino connected to my computer running a loop, sending a value over the serial port back to the computer every 100&nbsp;ms. </p> <p>I want to make a Python script that will read from the serial port only every few seconds, so I want it to just see the last thing sent from the Arduino.</p> <p>How do you do this in Pyserial?</p> <p>Here's the code I tried which does't work. It reads the lines sequentially.</p> <pre><code>import serial import time ser = serial.Serial('com4',9600,timeout=1) while 1: time.sleep(10) print ser.readline() #How do I get the most recent line sent from the device? </code></pre>
14
2009-07-07T17:16:43Z
1,144,994
<p>Slight modification to mtasic &amp; Vinay Sajip's code:</p> <p>While I found this code quite helpful to me for a similar application, I needed <em>all</em> the lines coming back from a serial device that would send information periodically.</p> <p>I opted to pop the first element off the top, record it, and then rejoin the remaining elements as the new buffer and continue from there.</p> <p>I realize that this is <strong>not</strong> what Greg was asking for, but I thought it was worth sharing as a side note.</p> <pre><code>def receiving(ser): global last_received buffer = '' while True: buffer = buffer + ser.read(ser.inWaiting()) if '\n' in buffer: lines = buffer.split('\n') last_received = lines.pop(0) buffer = '\n'.join(lines) </code></pre>
2
2009-07-17T18:40:17Z
[ "python", "serial-port", "arduino", "pyserial" ]
pyserial - How to read the last line sent from a serial device
1,093,598
<p>I have an Arduino connected to my computer running a loop, sending a value over the serial port back to the computer every 100&nbsp;ms. </p> <p>I want to make a Python script that will read from the serial port only every few seconds, so I want it to just see the last thing sent from the Arduino.</p> <p>How do you do this in Pyserial?</p> <p>Here's the code I tried which does't work. It reads the lines sequentially.</p> <pre><code>import serial import time ser = serial.Serial('com4',9600,timeout=1) while 1: time.sleep(10) print ser.readline() #How do I get the most recent line sent from the device? </code></pre>
14
2009-07-07T17:16:43Z
3,999,994
<p>These solutions will hog the CPU while waiting for characters.</p> <p>You should do at least one blocking call to read(1)</p> <pre><code>while True: if '\n' in buffer: pass # skip if a line already in buffer else: buffer += ser.read(1) # this will block until one more char or timeout buffer += ser.read(ser.inWaiting()) # get remaining buffered chars </code></pre> <p>...and do the split thing as before.</p>
7
2010-10-22T18:53:23Z
[ "python", "serial-port", "arduino", "pyserial" ]
pyserial - How to read the last line sent from a serial device
1,093,598
<p>I have an Arduino connected to my computer running a loop, sending a value over the serial port back to the computer every 100&nbsp;ms. </p> <p>I want to make a Python script that will read from the serial port only every few seconds, so I want it to just see the last thing sent from the Arduino.</p> <p>How do you do this in Pyserial?</p> <p>Here's the code I tried which does't work. It reads the lines sequentially.</p> <pre><code>import serial import time ser = serial.Serial('com4',9600,timeout=1) while 1: time.sleep(10) print ser.readline() #How do I get the most recent line sent from the device? </code></pre>
14
2009-07-07T17:16:43Z
6,300,263
<p>Using <code>.inWaiting()</code> inside an infinite loop may be problematic. It may hog up the entire <a href="http://en.wikipedia.org/wiki/Central_processing_unit" rel="nofollow">CPU</a> depending on the implementation. Instead, I would recommend using a specific size of data to be read. So in this case the following should be done for example: </p> <pre><code>ser.read(1024) </code></pre>
2
2011-06-09T22:59:22Z
[ "python", "serial-port", "arduino", "pyserial" ]
pyserial - How to read the last line sent from a serial device
1,093,598
<p>I have an Arduino connected to my computer running a loop, sending a value over the serial port back to the computer every 100&nbsp;ms. </p> <p>I want to make a Python script that will read from the serial port only every few seconds, so I want it to just see the last thing sent from the Arduino.</p> <p>How do you do this in Pyserial?</p> <p>Here's the code I tried which does't work. It reads the lines sequentially.</p> <pre><code>import serial import time ser = serial.Serial('com4',9600,timeout=1) while 1: time.sleep(10) print ser.readline() #How do I get the most recent line sent from the device? </code></pre>
14
2009-07-07T17:16:43Z
15,572,128
<p>This method allows you to separately control the timeout for gathering all the data for each line, and a different timeout for waiting on additional lines.</p> <pre><code># get the last line from serial port lines = serial_com() lines[-1] def serial_com(): '''Serial communications: get a response''' # open serial port try: serial_port = serial.Serial(com_port, baudrate=115200, timeout=1) except serial.SerialException as e: print("could not open serial port '{}': {}".format(com_port, e)) # read response from serial port lines = [] while True: line = serial_port.readline() lines.append(line.decode('utf-8').rstrip()) # wait for new data after each line timeout = time.time() + 0.1 while not serial_port.inWaiting() and timeout &gt; time.time(): pass if not serial_port.inWaiting(): break #close the serial port serial_port.close() return lines </code></pre>
1
2013-03-22T13:56:34Z
[ "python", "serial-port", "arduino", "pyserial" ]
pyserial - How to read the last line sent from a serial device
1,093,598
<p>I have an Arduino connected to my computer running a loop, sending a value over the serial port back to the computer every 100&nbsp;ms. </p> <p>I want to make a Python script that will read from the serial port only every few seconds, so I want it to just see the last thing sent from the Arduino.</p> <p>How do you do this in Pyserial?</p> <p>Here's the code I tried which does't work. It reads the lines sequentially.</p> <pre><code>import serial import time ser = serial.Serial('com4',9600,timeout=1) while 1: time.sleep(10) print ser.readline() #How do I get the most recent line sent from the device? </code></pre>
14
2009-07-07T17:16:43Z
23,021,208
<p>You can use <code>ser.flushInput()</code> to flush out all serial data that is currently in the buffer.</p> <p>After clearing out the old data, you can user ser.readline() to get the most recent data from the serial device.</p> <p>I think its a bit simpler than the other proposed solutions on here. Worked for me, hope it's suitable for you.</p>
1
2014-04-11T19:35:53Z
[ "python", "serial-port", "arduino", "pyserial" ]
pyserial - How to read the last line sent from a serial device
1,093,598
<p>I have an Arduino connected to my computer running a loop, sending a value over the serial port back to the computer every 100&nbsp;ms. </p> <p>I want to make a Python script that will read from the serial port only every few seconds, so I want it to just see the last thing sent from the Arduino.</p> <p>How do you do this in Pyserial?</p> <p>Here's the code I tried which does't work. It reads the lines sequentially.</p> <pre><code>import serial import time ser = serial.Serial('com4',9600,timeout=1) while 1: time.sleep(10) print ser.readline() #How do I get the most recent line sent from the device? </code></pre>
14
2009-07-07T17:16:43Z
26,742,494
<p><strong>Too much complications</strong></p> <p>What is the reason to split the bytes object by newline or by other array manipulations? I write the simplest method, which will solve your problem:</p> <pre><code>import serial s = serial.Serial(31) s.write(bytes("ATI\r\n", "utf-8")); while True: last = '' for byte in s.read(s.inWaiting()): last += chr(byte) if len(last) &gt; 0: # Do whatever you want with last print (bytes(last, "utf-8")) last = '' </code></pre>
2
2014-11-04T18:35:33Z
[ "python", "serial-port", "arduino", "pyserial" ]
Objective-C string manipulation
1,093,805
<p>Currently I am working on a piece of software, which is currently written 100% in Objective-C using the iPhone 3.0 SDK.</p> <p>I have come to a cross roads where I need to do quite a bit or string concatenation, more specifically, NSString concatenation and so far I have been doing it like this:</p> <p><strong>Objective-C string concatenation:</strong></p> <pre><code>NSString *resultantString = (NSMutableString*)[@"Hello " stringByAppendingString: @"World"]; </code></pre> <p>Now as you can imagine this gets quite difficult to read when I try to concatenate 6 NSStrings together.</p> <p>At first I contemplated mixing in an Objective-C++ class to do my string concatenation and hand it back to my Objective-C class as then I could use C++'s easy string concatenation like:</p> <p><strong>C++ string concatenation:</strong></p> <pre><code>string cppString = "Hello" + "World" + "see" + "easy!"; </code></pre> <p>I could use <strong>C</strong> char arrays but that would be a little more difficult to read.</p> <p>It then struck me that I could use a Python or Ruby bridge in Cocoa (which provide the added bonus of Regular expressions and superior string handling than the C based languages do).</p> <p>This made sense to me even though I have coded only small amounts of Ruby and Python, because they are billed as string manipulation languages. Perl I decided to skip because it isn't directly supported in Xcode.</p> <p>I am also interested in performance, so I am looking for the fastest way to do my string concatenation.</p> <p>So what should I do? Is there some deviously easy way I am missing in Objective-C to concatenate many strings at once say 10 strings? or is my idea to use Python or Ruby class methods that return a concatenated or regex modified strings not as incredibly insane as it sounds? Perhaps I even missed some another way to do this?</p> <p><strong>Update:</strong> Yes. It seems I was rather crazy for thinking of pulling in another language runtime to do string manipulation, especially since I noted that I was concerned with speed. Adding a bridge would probably be much slower than simply using NSString/NSMutableString.</p>
1
2009-07-07T17:54:32Z
1,093,835
<p>Have you seen the appendString method from the NSMutableString class?</p> <p>appendFormat from the same class will let you do many concatenations with one statement if that is what you're really interested in.</p>
4
2009-07-07T17:59:54Z
[ "python", "objective-c", "ruby", "string", "objective-c++" ]
Objective-C string manipulation
1,093,805
<p>Currently I am working on a piece of software, which is currently written 100% in Objective-C using the iPhone 3.0 SDK.</p> <p>I have come to a cross roads where I need to do quite a bit or string concatenation, more specifically, NSString concatenation and so far I have been doing it like this:</p> <p><strong>Objective-C string concatenation:</strong></p> <pre><code>NSString *resultantString = (NSMutableString*)[@"Hello " stringByAppendingString: @"World"]; </code></pre> <p>Now as you can imagine this gets quite difficult to read when I try to concatenate 6 NSStrings together.</p> <p>At first I contemplated mixing in an Objective-C++ class to do my string concatenation and hand it back to my Objective-C class as then I could use C++'s easy string concatenation like:</p> <p><strong>C++ string concatenation:</strong></p> <pre><code>string cppString = "Hello" + "World" + "see" + "easy!"; </code></pre> <p>I could use <strong>C</strong> char arrays but that would be a little more difficult to read.</p> <p>It then struck me that I could use a Python or Ruby bridge in Cocoa (which provide the added bonus of Regular expressions and superior string handling than the C based languages do).</p> <p>This made sense to me even though I have coded only small amounts of Ruby and Python, because they are billed as string manipulation languages. Perl I decided to skip because it isn't directly supported in Xcode.</p> <p>I am also interested in performance, so I am looking for the fastest way to do my string concatenation.</p> <p>So what should I do? Is there some deviously easy way I am missing in Objective-C to concatenate many strings at once say 10 strings? or is my idea to use Python or Ruby class methods that return a concatenated or regex modified strings not as incredibly insane as it sounds? Perhaps I even missed some another way to do this?</p> <p><strong>Update:</strong> Yes. It seems I was rather crazy for thinking of pulling in another language runtime to do string manipulation, especially since I noted that I was concerned with speed. Adding a bridge would probably be much slower than simply using NSString/NSMutableString.</p>
1
2009-07-07T17:54:32Z
1,093,851
<p>For fixed size concatenation, you can use <code>[NSString stringWithFormat:]</code> like:</p> <pre><code>NSString *str = [NSString stringWithFormat:@"%@ %@ %@", @"Hello", @"World", @"Yay!"]; </code></pre>
9
2009-07-07T18:02:19Z
[ "python", "objective-c", "ruby", "string", "objective-c++" ]
Objective-C string manipulation
1,093,805
<p>Currently I am working on a piece of software, which is currently written 100% in Objective-C using the iPhone 3.0 SDK.</p> <p>I have come to a cross roads where I need to do quite a bit or string concatenation, more specifically, NSString concatenation and so far I have been doing it like this:</p> <p><strong>Objective-C string concatenation:</strong></p> <pre><code>NSString *resultantString = (NSMutableString*)[@"Hello " stringByAppendingString: @"World"]; </code></pre> <p>Now as you can imagine this gets quite difficult to read when I try to concatenate 6 NSStrings together.</p> <p>At first I contemplated mixing in an Objective-C++ class to do my string concatenation and hand it back to my Objective-C class as then I could use C++'s easy string concatenation like:</p> <p><strong>C++ string concatenation:</strong></p> <pre><code>string cppString = "Hello" + "World" + "see" + "easy!"; </code></pre> <p>I could use <strong>C</strong> char arrays but that would be a little more difficult to read.</p> <p>It then struck me that I could use a Python or Ruby bridge in Cocoa (which provide the added bonus of Regular expressions and superior string handling than the C based languages do).</p> <p>This made sense to me even though I have coded only small amounts of Ruby and Python, because they are billed as string manipulation languages. Perl I decided to skip because it isn't directly supported in Xcode.</p> <p>I am also interested in performance, so I am looking for the fastest way to do my string concatenation.</p> <p>So what should I do? Is there some deviously easy way I am missing in Objective-C to concatenate many strings at once say 10 strings? or is my idea to use Python or Ruby class methods that return a concatenated or regex modified strings not as incredibly insane as it sounds? Perhaps I even missed some another way to do this?</p> <p><strong>Update:</strong> Yes. It seems I was rather crazy for thinking of pulling in another language runtime to do string manipulation, especially since I noted that I was concerned with speed. Adding a bridge would probably be much slower than simply using NSString/NSMutableString.</p>
1
2009-07-07T17:54:32Z
1,093,863
<p>you can use join operation.</p> <pre><code>NSArray *chunks = ... get an array, say by splitting it; string = [chunks componentsJoinedByString: @" :-) "]; </code></pre> <p>would produce something like oop :-) ack :-) bork :-) greeble :-) ponies</p>
9
2009-07-07T18:04:24Z
[ "python", "objective-c", "ruby", "string", "objective-c++" ]
Objective-C string manipulation
1,093,805
<p>Currently I am working on a piece of software, which is currently written 100% in Objective-C using the iPhone 3.0 SDK.</p> <p>I have come to a cross roads where I need to do quite a bit or string concatenation, more specifically, NSString concatenation and so far I have been doing it like this:</p> <p><strong>Objective-C string concatenation:</strong></p> <pre><code>NSString *resultantString = (NSMutableString*)[@"Hello " stringByAppendingString: @"World"]; </code></pre> <p>Now as you can imagine this gets quite difficult to read when I try to concatenate 6 NSStrings together.</p> <p>At first I contemplated mixing in an Objective-C++ class to do my string concatenation and hand it back to my Objective-C class as then I could use C++'s easy string concatenation like:</p> <p><strong>C++ string concatenation:</strong></p> <pre><code>string cppString = "Hello" + "World" + "see" + "easy!"; </code></pre> <p>I could use <strong>C</strong> char arrays but that would be a little more difficult to read.</p> <p>It then struck me that I could use a Python or Ruby bridge in Cocoa (which provide the added bonus of Regular expressions and superior string handling than the C based languages do).</p> <p>This made sense to me even though I have coded only small amounts of Ruby and Python, because they are billed as string manipulation languages. Perl I decided to skip because it isn't directly supported in Xcode.</p> <p>I am also interested in performance, so I am looking for the fastest way to do my string concatenation.</p> <p>So what should I do? Is there some deviously easy way I am missing in Objective-C to concatenate many strings at once say 10 strings? or is my idea to use Python or Ruby class methods that return a concatenated or regex modified strings not as incredibly insane as it sounds? Perhaps I even missed some another way to do this?</p> <p><strong>Update:</strong> Yes. It seems I was rather crazy for thinking of pulling in another language runtime to do string manipulation, especially since I noted that I was concerned with speed. Adding a bridge would probably be much slower than simply using NSString/NSMutableString.</p>
1
2009-07-07T17:54:32Z
1,093,867
<p>I would avoid mixing languages, particularly if you don't know Python or Ruby well. What you gain in readable code in your Objective-C you will loose have having to read multiple languages to understand your own code base. Seems like a maintainability nightmare to me.</p> <p>I'd strongly suggest taking one of the suggestions of how to do this in Objective-C directly.</p>
3
2009-07-07T18:06:33Z
[ "python", "objective-c", "ruby", "string", "objective-c++" ]
Objective-C string manipulation
1,093,805
<p>Currently I am working on a piece of software, which is currently written 100% in Objective-C using the iPhone 3.0 SDK.</p> <p>I have come to a cross roads where I need to do quite a bit or string concatenation, more specifically, NSString concatenation and so far I have been doing it like this:</p> <p><strong>Objective-C string concatenation:</strong></p> <pre><code>NSString *resultantString = (NSMutableString*)[@"Hello " stringByAppendingString: @"World"]; </code></pre> <p>Now as you can imagine this gets quite difficult to read when I try to concatenate 6 NSStrings together.</p> <p>At first I contemplated mixing in an Objective-C++ class to do my string concatenation and hand it back to my Objective-C class as then I could use C++'s easy string concatenation like:</p> <p><strong>C++ string concatenation:</strong></p> <pre><code>string cppString = "Hello" + "World" + "see" + "easy!"; </code></pre> <p>I could use <strong>C</strong> char arrays but that would be a little more difficult to read.</p> <p>It then struck me that I could use a Python or Ruby bridge in Cocoa (which provide the added bonus of Regular expressions and superior string handling than the C based languages do).</p> <p>This made sense to me even though I have coded only small amounts of Ruby and Python, because they are billed as string manipulation languages. Perl I decided to skip because it isn't directly supported in Xcode.</p> <p>I am also interested in performance, so I am looking for the fastest way to do my string concatenation.</p> <p>So what should I do? Is there some deviously easy way I am missing in Objective-C to concatenate many strings at once say 10 strings? or is my idea to use Python or Ruby class methods that return a concatenated or regex modified strings not as incredibly insane as it sounds? Perhaps I even missed some another way to do this?</p> <p><strong>Update:</strong> Yes. It seems I was rather crazy for thinking of pulling in another language runtime to do string manipulation, especially since I noted that I was concerned with speed. Adding a bridge would probably be much slower than simply using NSString/NSMutableString.</p>
1
2009-07-07T17:54:32Z
1,093,891
<p>Dragging in C++ just for this seems quite heavy-handed. Using <code>stringWithFormat:</code> on NSString or <code>appendFormat:</code> with an NSMutableString, as others have suggested, is much more natural and not particularly hard to read. Also, in order to use the strings with Cocoa, you'll have to add extra code to convert back and forth from C++ strings.</p>
2
2009-07-07T18:11:26Z
[ "python", "objective-c", "ruby", "string", "objective-c++" ]
Python Error
1,093,884
<p>First python script and I'm getting an error I can't seem to get around using a config file. The first part of the script takes user input and puts that into a mysql database with no problem..Then I get to the filesystem work and things go a bit pear shaped..I can get it to work without using the config file options but I'd like to keep it consistent and pull from that file:</p> <pre><code> vshare = str(raw_input('Share the user needs access to: ')) vrights = str(raw_input('Should this user be Read Only? (y/n): ')) f = open("%s/%s" % (config['vsftp']['user_dir'], (vusername), 'wr')) #f = open("/etc/vsftpd_user_conf/%s" % (vusername) , 'wr' ) f.write("local_root=%s/%s" % (config['vsftp']['local_root_dir'], vshare)) if vrights.lower() in ['y', 'ye', 'yes']: buffer = [] for line in f.readlines(): if 'write_enable=' in line: buffer.append('write_enable=NO') else: buffer.append(line) f.writelines(buffer) f.close() </code></pre> <p>The error I'm getting is:</p> <pre><code>TypeError: not all arguments converted during string formatting </code></pre> <p>If I uncomment the commented line it works and makes it a bit further and errors out as well..But I'll deal with that once I get this hiccup sorted..Thanks for any input.</p>
0
2009-07-07T18:10:21Z
1,093,902
<p>The error is here:</p> <pre><code>open("%s/%s" % (config['vsftp']['user_dir'], (vusername), 'wr')) </code></pre> <p>You have three parameters, but only two %s in the string. You probably meant to say:</p> <pre><code>open("%s/%s" % (config['vsftp']['user_dir'], vusername), 'wr') </code></pre> <p>Although 'wr' is unclear, you probably mean w+ or r+.</p> <p><a href="http://docs.python.org/library/functions.html#open" rel="nofollow">http://docs.python.org/library/functions.html#open</a></p>
2
2009-07-07T18:14:10Z
[ "python", "typeerror" ]
Python Error
1,093,884
<p>First python script and I'm getting an error I can't seem to get around using a config file. The first part of the script takes user input and puts that into a mysql database with no problem..Then I get to the filesystem work and things go a bit pear shaped..I can get it to work without using the config file options but I'd like to keep it consistent and pull from that file:</p> <pre><code> vshare = str(raw_input('Share the user needs access to: ')) vrights = str(raw_input('Should this user be Read Only? (y/n): ')) f = open("%s/%s" % (config['vsftp']['user_dir'], (vusername), 'wr')) #f = open("/etc/vsftpd_user_conf/%s" % (vusername) , 'wr' ) f.write("local_root=%s/%s" % (config['vsftp']['local_root_dir'], vshare)) if vrights.lower() in ['y', 'ye', 'yes']: buffer = [] for line in f.readlines(): if 'write_enable=' in line: buffer.append('write_enable=NO') else: buffer.append(line) f.writelines(buffer) f.close() </code></pre> <p>The error I'm getting is:</p> <pre><code>TypeError: not all arguments converted during string formatting </code></pre> <p>If I uncomment the commented line it works and makes it a bit further and errors out as well..But I'll deal with that once I get this hiccup sorted..Thanks for any input.</p>
0
2009-07-07T18:10:21Z
1,093,905
<p>Your tuple is misshaped</p> <pre><code>f = open("%s/%s" % (config['vsftp']['user_dir'], (vusername), 'wr')) </code></pre> <p>Should be</p> <pre><code>f = open("%s/%s" % (config['vsftp']['user_dir'], (vusername)), 'wr') </code></pre>
3
2009-07-07T18:14:12Z
[ "python", "typeerror" ]
Python Error
1,093,884
<p>First python script and I'm getting an error I can't seem to get around using a config file. The first part of the script takes user input and puts that into a mysql database with no problem..Then I get to the filesystem work and things go a bit pear shaped..I can get it to work without using the config file options but I'd like to keep it consistent and pull from that file:</p> <pre><code> vshare = str(raw_input('Share the user needs access to: ')) vrights = str(raw_input('Should this user be Read Only? (y/n): ')) f = open("%s/%s" % (config['vsftp']['user_dir'], (vusername), 'wr')) #f = open("/etc/vsftpd_user_conf/%s" % (vusername) , 'wr' ) f.write("local_root=%s/%s" % (config['vsftp']['local_root_dir'], vshare)) if vrights.lower() in ['y', 'ye', 'yes']: buffer = [] for line in f.readlines(): if 'write_enable=' in line: buffer.append('write_enable=NO') else: buffer.append(line) f.writelines(buffer) f.close() </code></pre> <p>The error I'm getting is:</p> <pre><code>TypeError: not all arguments converted during string formatting </code></pre> <p>If I uncomment the commented line it works and makes it a bit further and errors out as well..But I'll deal with that once I get this hiccup sorted..Thanks for any input.</p>
0
2009-07-07T18:10:21Z
1,093,911
<pre><code>f = open("%s/%s" % (config['vsftp']['user_dir'], (vusername), 'wr')) </code></pre> <p>You are passing three arguments (config['vsftp']['user_dir'], (vusername), 'wr') to a format string expecting two: "%s/%s". So the error is telling you that there is an argument to the format string that is not being used.</p>
0
2009-07-07T18:15:32Z
[ "python", "typeerror" ]
Python Error
1,093,884
<p>First python script and I'm getting an error I can't seem to get around using a config file. The first part of the script takes user input and puts that into a mysql database with no problem..Then I get to the filesystem work and things go a bit pear shaped..I can get it to work without using the config file options but I'd like to keep it consistent and pull from that file:</p> <pre><code> vshare = str(raw_input('Share the user needs access to: ')) vrights = str(raw_input('Should this user be Read Only? (y/n): ')) f = open("%s/%s" % (config['vsftp']['user_dir'], (vusername), 'wr')) #f = open("/etc/vsftpd_user_conf/%s" % (vusername) , 'wr' ) f.write("local_root=%s/%s" % (config['vsftp']['local_root_dir'], vshare)) if vrights.lower() in ['y', 'ye', 'yes']: buffer = [] for line in f.readlines(): if 'write_enable=' in line: buffer.append('write_enable=NO') else: buffer.append(line) f.writelines(buffer) f.close() </code></pre> <p>The error I'm getting is:</p> <pre><code>TypeError: not all arguments converted during string formatting </code></pre> <p>If I uncomment the commented line it works and makes it a bit further and errors out as well..But I'll deal with that once I get this hiccup sorted..Thanks for any input.</p>
0
2009-07-07T18:10:21Z
1,093,917
<p>I think you have a wrong parenthesis, your line should be:</p> <pre><code>f = open("%s/%s" % (config['vsftp']['user_dir'], (vusername)), 'wr') </code></pre>
0
2009-07-07T18:16:12Z
[ "python", "typeerror" ]
Python Error
1,093,884
<p>First python script and I'm getting an error I can't seem to get around using a config file. The first part of the script takes user input and puts that into a mysql database with no problem..Then I get to the filesystem work and things go a bit pear shaped..I can get it to work without using the config file options but I'd like to keep it consistent and pull from that file:</p> <pre><code> vshare = str(raw_input('Share the user needs access to: ')) vrights = str(raw_input('Should this user be Read Only? (y/n): ')) f = open("%s/%s" % (config['vsftp']['user_dir'], (vusername), 'wr')) #f = open("/etc/vsftpd_user_conf/%s" % (vusername) , 'wr' ) f.write("local_root=%s/%s" % (config['vsftp']['local_root_dir'], vshare)) if vrights.lower() in ['y', 'ye', 'yes']: buffer = [] for line in f.readlines(): if 'write_enable=' in line: buffer.append('write_enable=NO') else: buffer.append(line) f.writelines(buffer) f.close() </code></pre> <p>The error I'm getting is:</p> <pre><code>TypeError: not all arguments converted during string formatting </code></pre> <p>If I uncomment the commented line it works and makes it a bit further and errors out as well..But I'll deal with that once I get this hiccup sorted..Thanks for any input.</p>
0
2009-07-07T18:10:21Z
1,093,931
<p>It looks like this line should be:</p> <pre><code>f = open("%s/%s" % (config['vsftp']['user_dir'], vusername), 'wr') </code></pre> <p>(I moved the closing parenthesis over.)</p>
0
2009-07-07T18:19:17Z
[ "python", "typeerror" ]
How to serve any file type with Python's BaseHTTPRequestHandler
1,094,185
<p>Consider the following example:</p> <pre><code>import string,cgi,time from os import curdir, sep from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer class MyHandler(BaseHTTPRequestHandler): def do_GET(self): try: if self.path.endswith(".html"): f = open(curdir + sep + self.path) #self.path has /test.html #note that this potentially makes every file on your computer readable by the internet self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() self.wfile.write(f.read()) f.close() return except IOError: self.send_error(404,'File Not Found: %s' % self.path) def main(): try: server = HTTPServer(('', 80), MyHandler) print 'started httpserver...' server.serve_forever() except KeyboardInterrupt: print '^C received, shutting down server' server.socket.close() if __name__ == '__main__': main() </code></pre> <p>What if I want to server a ZIP file also... how would I do that? I don't think this line would work right?</p> <pre><code>self.wfile.write(f.read()) </code></pre>
7
2009-07-07T19:06:36Z
1,094,211
<p>Your line would work just fine. The problem would be setting the <code>Content-type</code> appropriately. You'd want to set it to <code>application/zip</code> instead of <code>text/html</code>.</p>
4
2009-07-07T19:12:48Z
[ "python", "httpserver" ]
How to serve any file type with Python's BaseHTTPRequestHandler
1,094,185
<p>Consider the following example:</p> <pre><code>import string,cgi,time from os import curdir, sep from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer class MyHandler(BaseHTTPRequestHandler): def do_GET(self): try: if self.path.endswith(".html"): f = open(curdir + sep + self.path) #self.path has /test.html #note that this potentially makes every file on your computer readable by the internet self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() self.wfile.write(f.read()) f.close() return except IOError: self.send_error(404,'File Not Found: %s' % self.path) def main(): try: server = HTTPServer(('', 80), MyHandler) print 'started httpserver...' server.serve_forever() except KeyboardInterrupt: print '^C received, shutting down server' server.socket.close() if __name__ == '__main__': main() </code></pre> <p>What if I want to server a ZIP file also... how would I do that? I don't think this line would work right?</p> <pre><code>self.wfile.write(f.read()) </code></pre>
7
2009-07-07T19:06:36Z
1,094,237
<p>Pass binary as a parameter to open(). This:</p> <pre><code>f = open(curdir + sep + self.path, 'rb') </code></pre> <p>Instead of this:</p> <pre><code>f = open(curdir + sep + self.path) </code></pre> <p>UNIX doesn't distinguish between binary and text, but windows does. But if the script executes on UNIX, the "b" will just be ignored so you're safe.</p>
7
2009-07-07T19:18:14Z
[ "python", "httpserver" ]
How to serve any file type with Python's BaseHTTPRequestHandler
1,094,185
<p>Consider the following example:</p> <pre><code>import string,cgi,time from os import curdir, sep from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer class MyHandler(BaseHTTPRequestHandler): def do_GET(self): try: if self.path.endswith(".html"): f = open(curdir + sep + self.path) #self.path has /test.html #note that this potentially makes every file on your computer readable by the internet self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() self.wfile.write(f.read()) f.close() return except IOError: self.send_error(404,'File Not Found: %s' % self.path) def main(): try: server = HTTPServer(('', 80), MyHandler) print 'started httpserver...' server.serve_forever() except KeyboardInterrupt: print '^C received, shutting down server' server.socket.close() if __name__ == '__main__': main() </code></pre> <p>What if I want to server a ZIP file also... how would I do that? I don't think this line would work right?</p> <pre><code>self.wfile.write(f.read()) </code></pre>
7
2009-07-07T19:06:36Z
6,798,443
<p>If you want to share files in a folder of any type, then you can also try typing the command</p> <pre><code>python -m SimpleHTTPServer </code></pre> <p>This will start the server at port 8000 and you can browse the files (via directory listing)</p>
5
2011-07-23T05:30:22Z
[ "python", "httpserver" ]
Elegant way to abstract multiple function calls?
1,094,611
<p>Example:</p> <pre><code>&gt;&gt;&gt; def write_to_terminal(fmt, *args): ... print fmt % args &gt;&gt;&gt; LOG = logging.getLogger(__name__) &gt;&gt;&gt; info = multicall(write_to_terminal, LOG.info) &gt;&gt;&gt; debug = multicall(write_debug_to_terminal, LOG.debug) &gt;&gt;&gt; ... &gt;&gt;&gt; info('Hello %s', 'guido') # display in terminal *and* log the message </code></pre> <p>Is there an elegant way to write <code>multicall</code>? Perhaps with the help of the standard library .. without reinventing the wheel?</p>
1
2009-07-07T20:16:01Z
1,094,627
<p>Something like this?</p> <pre><code>def multicall(*functions): def call_functions(*args, **kwds): for function in functions: function(*args, **kwds) return call_functions </code></pre> <p>And if you want to aggregate the results:</p> <pre><code>def multicall(*functions): def call_functions(*args, **kwds): return [function(*args, **kwds) for function in functions] return call_functions </code></pre> <p>EDIT</p> <p>Decorators were suggested; in that case it would look like this:</p> <pre><code>def appendcalls(*functions): def decorator(decorated_function): all_functions = [decorated_function] + list(functions) def call_functions(*args, **kwds): for function in all_functions: function(*args, **kwds) return call_functions return decorator LOG = logging.getLogger(__name__) @appendcalls(LOG.info) def info(fmt, *args): print fmt % args info('Hello %s', 'guido') </code></pre> <p><code>appendcalls()</code> takes any number of functions to be called after the decorated function. You may want to implement the decorator differently, depending on what return value you want -- the original from the decorated function, a list of all function results or nothing at all.</p>
5
2009-07-07T20:19:58Z
[ "python", "function" ]
Elegant way to abstract multiple function calls?
1,094,611
<p>Example:</p> <pre><code>&gt;&gt;&gt; def write_to_terminal(fmt, *args): ... print fmt % args &gt;&gt;&gt; LOG = logging.getLogger(__name__) &gt;&gt;&gt; info = multicall(write_to_terminal, LOG.info) &gt;&gt;&gt; debug = multicall(write_debug_to_terminal, LOG.debug) &gt;&gt;&gt; ... &gt;&gt;&gt; info('Hello %s', 'guido') # display in terminal *and* log the message </code></pre> <p>Is there an elegant way to write <code>multicall</code>? Perhaps with the help of the standard library .. without reinventing the wheel?</p>
1
2009-07-07T20:16:01Z
1,094,644
<p>You could look into Python decorators.</p> <p>A clear description is here: <a href="http://www.artima.com/weblogs/viewpost.jsp?thread=240808" rel="nofollow">http://www.artima.com/weblogs/viewpost.jsp?thread=240808</a></p>
1
2009-07-07T20:22:18Z
[ "python", "function" ]
Wavelet plot with Python libraries
1,094,655
<p>I know that SciPy has some signal processing tools for wavelets in scipy.signal.wavelets and a chart can be drawn using Matplotlib, but it seems I can't get it right. I have tried plotting a Daubechies wavelet against a linear space, but it's not what I am looking for. I am highly unskilled about wavelets and math in general . :)</p>
6
2009-07-07T20:25:31Z
1,118,619
<p>With a recent trunk version of <a href="http://pybytes.com/pywavelets/">PyWavelets</a>, getting approximations of scaling function and wavelet function on x-grid is pretty straightforward:</p> <pre><code>[phi, psi, x] = pywt.Wavelet('db2').wavefun(level=4) </code></pre> <p>Note that x-grid output is not available in v0.1.6, so if you need that you will have to use the trunk version.</p> <p>Having that data, you can plot it using your favourite plotting package, for example:</p> <pre><code>import pylab pylab.plot(x, psi) pylab.show() </code></pre> <p>A very similar method is used on wavelets.pybytes.com demo page, but there the charts are done with Google Charts for online presentation.</p>
11
2009-07-13T10:03:00Z
[ "python", "matplotlib", "scipy", "wavelet", "pywt" ]
Convert a string to integer with decimal in Python
1,094,717
<p>I have a string in the format: 'nn.nnnnn' in Python, and I'd like to convert it to an integer.</p> <p>Direct conversion fails:</p> <pre><code>&gt;&gt;&gt; s = '23.45678' &gt;&gt;&gt; i = int(s) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ValueError: invalid literal for int() with base 10: '23.45678' </code></pre> <p>I can convert it to a decimal by using:</p> <pre><code>&gt;&gt;&gt; from decimal import * &gt;&gt;&gt; d = Decimal(s) &gt;&gt;&gt; print d 23.45678 </code></pre> <p>I could also split on '.', then subtract the decimal from zero, then add that to the whole number ... yuck.</p> <p>But I'd prefer to have it as an int, without unnecessary type conversions or maneuvering.</p>
33
2009-07-07T20:35:48Z
1,094,721
<p>How about this?</p> <pre><code>&gt;&gt;&gt; s = '23.45678' &gt;&gt;&gt; int(float(s)) 23 </code></pre> <p>Or...</p> <pre><code>&gt;&gt;&gt; int(Decimal(s)) 23 </code></pre> <p>Or...</p> <pre><code>&gt;&gt;&gt; int(s.split('.')[0]) 23 </code></pre> <p>I doubt it's going to get much simpler than that, I'm afraid. Just accept it and move on.</p>
66
2009-07-07T20:36:52Z
[ "python", "string", "integer", "decimal" ]
Convert a string to integer with decimal in Python
1,094,717
<p>I have a string in the format: 'nn.nnnnn' in Python, and I'd like to convert it to an integer.</p> <p>Direct conversion fails:</p> <pre><code>&gt;&gt;&gt; s = '23.45678' &gt;&gt;&gt; i = int(s) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ValueError: invalid literal for int() with base 10: '23.45678' </code></pre> <p>I can convert it to a decimal by using:</p> <pre><code>&gt;&gt;&gt; from decimal import * &gt;&gt;&gt; d = Decimal(s) &gt;&gt;&gt; print d 23.45678 </code></pre> <p>I could also split on '.', then subtract the decimal from zero, then add that to the whole number ... yuck.</p> <p>But I'd prefer to have it as an int, without unnecessary type conversions or maneuvering.</p>
33
2009-07-07T20:35:48Z
1,094,741
<p>You could use:</p> <pre><code>s = '23.245678' i = int(float(s)) </code></pre>
1
2009-07-07T20:40:58Z
[ "python", "string", "integer", "decimal" ]
Convert a string to integer with decimal in Python
1,094,717
<p>I have a string in the format: 'nn.nnnnn' in Python, and I'd like to convert it to an integer.</p> <p>Direct conversion fails:</p> <pre><code>&gt;&gt;&gt; s = '23.45678' &gt;&gt;&gt; i = int(s) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ValueError: invalid literal for int() with base 10: '23.45678' </code></pre> <p>I can convert it to a decimal by using:</p> <pre><code>&gt;&gt;&gt; from decimal import * &gt;&gt;&gt; d = Decimal(s) &gt;&gt;&gt; print d 23.45678 </code></pre> <p>I could also split on '.', then subtract the decimal from zero, then add that to the whole number ... yuck.</p> <p>But I'd prefer to have it as an int, without unnecessary type conversions or maneuvering.</p>
33
2009-07-07T20:35:48Z
1,094,745
<p>What sort of rounding behavior do you want? Do you 2.67 to turn into 3, or 2. If you want to use rounding, try this:</p> <pre><code>s = '234.67' i = int(round(float(s))) </code></pre> <p>Otherwise, just do:</p> <pre><code>s = '234.67' i = int(float(s)) </code></pre>
12
2009-07-07T20:41:44Z
[ "python", "string", "integer", "decimal" ]
Convert a string to integer with decimal in Python
1,094,717
<p>I have a string in the format: 'nn.nnnnn' in Python, and I'd like to convert it to an integer.</p> <p>Direct conversion fails:</p> <pre><code>&gt;&gt;&gt; s = '23.45678' &gt;&gt;&gt; i = int(s) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ValueError: invalid literal for int() with base 10: '23.45678' </code></pre> <p>I can convert it to a decimal by using:</p> <pre><code>&gt;&gt;&gt; from decimal import * &gt;&gt;&gt; d = Decimal(s) &gt;&gt;&gt; print d 23.45678 </code></pre> <p>I could also split on '.', then subtract the decimal from zero, then add that to the whole number ... yuck.</p> <p>But I'd prefer to have it as an int, without unnecessary type conversions or maneuvering.</p>
33
2009-07-07T20:35:48Z
1,094,765
<p>"Convert" only makes sense when you change from one data type to another without loss of fidelity. The number represented by the string is a float and will lose precision upon being forced into an int.</p> <p>You want to round instead, probably (I hope that the numbers don't represent currency because then rounding gets a whole lot more complicated).</p> <pre><code>round(float('23.45678')) </code></pre>
1
2009-07-07T20:45:05Z
[ "python", "string", "integer", "decimal" ]
Convert a string to integer with decimal in Python
1,094,717
<p>I have a string in the format: 'nn.nnnnn' in Python, and I'd like to convert it to an integer.</p> <p>Direct conversion fails:</p> <pre><code>&gt;&gt;&gt; s = '23.45678' &gt;&gt;&gt; i = int(s) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ValueError: invalid literal for int() with base 10: '23.45678' </code></pre> <p>I can convert it to a decimal by using:</p> <pre><code>&gt;&gt;&gt; from decimal import * &gt;&gt;&gt; d = Decimal(s) &gt;&gt;&gt; print d 23.45678 </code></pre> <p>I could also split on '.', then subtract the decimal from zero, then add that to the whole number ... yuck.</p> <p>But I'd prefer to have it as an int, without unnecessary type conversions or maneuvering.</p>
33
2009-07-07T20:35:48Z
1,094,775
<pre><code>&gt;&gt;&gt; s = '23.45678' &gt;&gt;&gt; int(float(s)) 23 &gt;&gt;&gt; int(round(float(s))) 23 &gt;&gt;&gt; s = '23.54678' &gt;&gt;&gt; int(float(s)) 23 &gt;&gt;&gt; int(round(float(s))) 24 </code></pre> <p>You don't specify if you want rounding or not...</p>
2
2009-07-07T20:47:25Z
[ "python", "string", "integer", "decimal" ]
Convert a string to integer with decimal in Python
1,094,717
<p>I have a string in the format: 'nn.nnnnn' in Python, and I'd like to convert it to an integer.</p> <p>Direct conversion fails:</p> <pre><code>&gt;&gt;&gt; s = '23.45678' &gt;&gt;&gt; i = int(s) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ValueError: invalid literal for int() with base 10: '23.45678' </code></pre> <p>I can convert it to a decimal by using:</p> <pre><code>&gt;&gt;&gt; from decimal import * &gt;&gt;&gt; d = Decimal(s) &gt;&gt;&gt; print d 23.45678 </code></pre> <p>I could also split on '.', then subtract the decimal from zero, then add that to the whole number ... yuck.</p> <p>But I'd prefer to have it as an int, without unnecessary type conversions or maneuvering.</p>
33
2009-07-07T20:35:48Z
1,094,776
<pre><code>round(float("123.789")) </code></pre> <p>will give you an integer value, but a float type. With Python's duck typing, however, the actual type is usually not very relevant. This will also round the value, which you might not want. Replace 'round' with 'int' and you'll have it just truncated and an actual int. Like this:</p> <pre><code>int(float("123.789")) </code></pre> <p>But, again, actual 'type' is usually not that important.</p>
0
2009-07-07T20:47:26Z
[ "python", "string", "integer", "decimal" ]
Convert a string to integer with decimal in Python
1,094,717
<p>I have a string in the format: 'nn.nnnnn' in Python, and I'd like to convert it to an integer.</p> <p>Direct conversion fails:</p> <pre><code>&gt;&gt;&gt; s = '23.45678' &gt;&gt;&gt; i = int(s) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ValueError: invalid literal for int() with base 10: '23.45678' </code></pre> <p>I can convert it to a decimal by using:</p> <pre><code>&gt;&gt;&gt; from decimal import * &gt;&gt;&gt; d = Decimal(s) &gt;&gt;&gt; print d 23.45678 </code></pre> <p>I could also split on '.', then subtract the decimal from zero, then add that to the whole number ... yuck.</p> <p>But I'd prefer to have it as an int, without unnecessary type conversions or maneuvering.</p>
33
2009-07-07T20:35:48Z
1,094,781
<p>The expression <code>int(float(s))</code> mentioned by others is the best if you want to truncate the value. If you want rounding, using <code>int(round(float(s))</code> if the round algorithm matches what you want (see the <a href="http://docs.python.org/library/functions.html?highlight=round#round" rel="nofollow">round documentation</a>), otherwise you should use <code>Decimal</code> and one if its rounding algorithms.</p>
1
2009-07-07T20:48:21Z
[ "python", "string", "integer", "decimal" ]
Reusable library to get human readable version of file size?
1,094,841
<p>There are various snippets on the web that would give you a function to return human readable size from bytes size:</p> <pre><code>&gt;&gt;&gt; human_readable(2048) '2 kilobytes' &gt;&gt;&gt; </code></pre> <p>But is there a Python library that provides this?</p>
129
2009-07-07T20:59:32Z
1,094,845
<p>One such library is <a href="http://pypi.python.org/pypi/hurry.filesize">hurry.filesize</a>.</p> <pre><code>&gt;&gt;&gt; from hurry.filesize import alternative &gt;&gt;&gt; size(1, system=alternative) '1 byte' &gt;&gt;&gt; size(10, system=alternative) '10 bytes' &gt;&gt;&gt; size(1024, system=alternative) '1 KB' </code></pre>
7
2009-07-07T21:00:25Z
[ "python", "code-snippets", "filesize" ]
Reusable library to get human readable version of file size?
1,094,841
<p>There are various snippets on the web that would give you a function to return human readable size from bytes size:</p> <pre><code>&gt;&gt;&gt; human_readable(2048) '2 kilobytes' &gt;&gt;&gt; </code></pre> <p>But is there a Python library that provides this?</p>
129
2009-07-07T20:59:32Z
1,094,933
<p>Addressing the above "too small a task to require a library" issue by a straightforward implementation:</p> <pre><code>def sizeof_fmt(num, suffix='B'): for unit in ['','Ki','Mi','Gi','Ti','Pi','Ei','Zi']: if abs(num) &lt; 1024.0: return "%3.1f%s%s" % (num, unit, suffix) num /= 1024.0 return "%.1f%s%s" % (num, 'Yi', suffix) </code></pre> <p>Supports:</p> <ul> <li>all currently known <a href="https://en.wikipedia.org/wiki/Binary_prefix#Specific_units_of_IEC_60027-2_A.2_and_ISO.2FIEC_80000">binary prefixes</a></li> <li>negative and positive numbers</li> <li>numbers larger than 1000 Yobibytes</li> <li>arbitrary units (maybe you like to count in Gibibits!)</li> </ul> <p>Example:</p> <pre><code>&gt;&gt;&gt; sizeof_fmt(168963795964) '157.4GiB' </code></pre> <p>by <a href="https://web.archive.org/web/20111010015624/http://blogmag.net/blog/read/38/Print_human_readable_file_size">Fred Cirera</a></p>
290
2009-07-07T21:15:41Z
[ "python", "code-snippets", "filesize" ]
Reusable library to get human readable version of file size?
1,094,841
<p>There are various snippets on the web that would give you a function to return human readable size from bytes size:</p> <pre><code>&gt;&gt;&gt; human_readable(2048) '2 kilobytes' &gt;&gt;&gt; </code></pre> <p>But is there a Python library that provides this?</p>
129
2009-07-07T20:59:32Z
1,095,051
<p>DiveIntoPython3 also <a href="http://getpython3.com/diveintopython3/your-first-python-program.html#divingin" rel="nofollow">talks</a> about this function.</p>
2
2009-07-07T21:44:26Z
[ "python", "code-snippets", "filesize" ]
Reusable library to get human readable version of file size?
1,094,841
<p>There are various snippets on the web that would give you a function to return human readable size from bytes size:</p> <pre><code>&gt;&gt;&gt; human_readable(2048) '2 kilobytes' &gt;&gt;&gt; </code></pre> <p>But is there a Python library that provides this?</p>
129
2009-07-07T20:59:32Z
2,181,538
<pre><code>def human_readable_data_quantity(quantity, multiple=1024): if quantity == 0: quantity = +0 SUFFIXES = ["B"] + [i + {1000: "B", 1024: "iB"}[multiple] for i in "KMGTPEZY"] for suffix in SUFFIXES: if quantity &lt; multiple or suffix == SUFFIXES[-1]: if suffix == SUFFIXES[0]: return "%d%s" % (quantity, suffix) else: return "%.1f%s" % (quantity, suffix) else: quantity /= multiple </code></pre>
1
2010-02-02T02:29:43Z
[ "python", "code-snippets", "filesize" ]
Reusable library to get human readable version of file size?
1,094,841
<p>There are various snippets on the web that would give you a function to return human readable size from bytes size:</p> <pre><code>&gt;&gt;&gt; human_readable(2048) '2 kilobytes' &gt;&gt;&gt; </code></pre> <p>But is there a Python library that provides this?</p>
129
2009-07-07T20:59:32Z
6,547,474
<p>Riffing on the snippet provided as an alternative to hurry.filesize(), here is a snippet that gives varying precision numbers based on the prefix used. It isn't as terse as some snippets, but I like the results.</p> <pre><code>def human_size(size_bytes): """ format a size in bytes into a 'human' file size, e.g. bytes, KB, MB, GB, TB, PB Note that bytes/KB will be reported in whole numbers but MB and above will have greater precision e.g. 1 byte, 43 bytes, 443 KB, 4.3 MB, 4.43 GB, etc """ if size_bytes == 1: # because I really hate unnecessary plurals return "1 byte" suffixes_table = [('bytes',0),('KB',0),('MB',1),('GB',2),('TB',2), ('PB',2)] num = float(size_bytes) for suffix, precision in suffixes_table: if num &lt; 1024.0: break num /= 1024.0 if precision == 0: formatted_size = "%d" % num else: formatted_size = str(round(num, ndigits=precision)) return "%s %s" % (formatted_size, suffix) </code></pre>
6
2011-07-01T11:40:16Z
[ "python", "code-snippets", "filesize" ]
Reusable library to get human readable version of file size?
1,094,841
<p>There are various snippets on the web that would give you a function to return human readable size from bytes size:</p> <pre><code>&gt;&gt;&gt; human_readable(2048) '2 kilobytes' &gt;&gt;&gt; </code></pre> <p>But is there a Python library that provides this?</p>
129
2009-07-07T20:59:32Z
10,171,475
<p>Here's my version. It does not use a for-loop. It has constant complexity, O(<em>1</em>), and is in theory more efficient than the answers here that use a for-loop.</p> <pre class="lang-python prettyprint-override"><code>from math import log unit_list = zip(['bytes', 'kB', 'MB', 'GB', 'TB', 'PB'], [0, 0, 1, 2, 2, 2]) def sizeof_fmt(num): """Human friendly file size""" if num &gt; 1: exponent = min(int(log(num, 1024)), len(unit_list) - 1) quotient = float(num) / 1024**exponent unit, num_decimals = unit_list[exponent] format_string = '{:.%sf} {}' % (num_decimals) return format_string.format(quotient, unit) if num == 0: return '0 bytes' if num == 1: return '1 byte' </code></pre> <p>To make it more clear what is going on, we can omit the code for the string formatting. Here are the lines that actually do the work:</p> <pre><code>exponent = int(log(num, 1024)) quotient = num / 1024**exponent unit_list[exponent] </code></pre>
24
2012-04-16T09:16:44Z
[ "python", "code-snippets", "filesize" ]
Reusable library to get human readable version of file size?
1,094,841
<p>There are various snippets on the web that would give you a function to return human readable size from bytes size:</p> <pre><code>&gt;&gt;&gt; human_readable(2048) '2 kilobytes' &gt;&gt;&gt; </code></pre> <p>But is there a Python library that provides this?</p>
129
2009-07-07T20:59:32Z
10,194,541
<p>Drawing from all the previous answers, here is my take on it. It's an object which will store the file size in bytes as an integer. But when you try to print the object, you automatically get a human readable version.</p> <pre><code>class Filesize(object): """ Container for a size in bytes with a human readable representation Use it like this:: &gt;&gt;&gt; size = Filesize(123123123) &gt;&gt;&gt; print size '117.4 MB' """ chunk = 1024 units = ['bytes', 'KB', 'MB', 'GB', 'TB', 'PB'] precisions = [0, 0, 1, 2, 2, 2] def __init__(self, size): self.size = size def __int__(self): return self.size def __str__(self): if self.size == 0: return '0 bytes' from math import log unit = self.units[min(int(log(self.size, self.chunk)), len(self.units) - 1)] return self.format(unit) def format(self, unit): if unit not in self.units: raise Exception("Not a valid file size unit: %s" % unit) if self.size == 1 and unit == 'bytes': return '1 byte' exponent = self.units.index(unit) quotient = float(self.size) / self.chunk**exponent precision = self.precisions[exponent] format_string = '{:.%sf} {}' % (precision) return format_string.format(quotient, unit) </code></pre>
3
2012-04-17T15:47:54Z
[ "python", "code-snippets", "filesize" ]
Reusable library to get human readable version of file size?
1,094,841
<p>There are various snippets on the web that would give you a function to return human readable size from bytes size:</p> <pre><code>&gt;&gt;&gt; human_readable(2048) '2 kilobytes' &gt;&gt;&gt; </code></pre> <p>But is there a Python library that provides this?</p>
129
2009-07-07T20:59:32Z
15,485,265
<p>A library that has all the functionality that it seems you're looking for is <a href="https://pypi.python.org/pypi/humanize"><code>humanize</code></a>. <code>humanize.naturalsize()</code> seems to do everything you're looking for.</p>
37
2013-03-18T19:29:28Z
[ "python", "code-snippets", "filesize" ]
Reusable library to get human readable version of file size?
1,094,841
<p>There are various snippets on the web that would give you a function to return human readable size from bytes size:</p> <pre><code>&gt;&gt;&gt; human_readable(2048) '2 kilobytes' &gt;&gt;&gt; </code></pre> <p>But is there a Python library that provides this?</p>
129
2009-07-07T20:59:32Z
17,754,143
<p>I like the fixed precision of <a href="http://stackoverflow.com/a/5414105/2595465">senderle's decimal version</a>, so here's a sort of hybrid of that with joctee's answer above (did you know you could take logs with non-integer bases?):</p> <pre><code>from math import log def human_readable_bytes(x): # hybrid of http://stackoverflow.com/a/10171475/2595465 # with http://stackoverflow.com/a/5414105/2595465 if x == 0: return '0' magnitude = int(log(abs(x),10.24)) if magnitude &gt; 16: format_str = '%iP' denominator_mag = 15 else: float_fmt = '%2.1f' if magnitude % 3 == 1 else '%1.2f' illion = (magnitude + 1) // 3 format_str = float_fmt + ['', 'K', 'M', 'G', 'T', 'P'][illion] return (format_str % (x * 1.0 / (1024 ** illion))).lstrip('0') </code></pre>
3
2013-07-19T19:36:16Z
[ "python", "code-snippets", "filesize" ]
Reusable library to get human readable version of file size?
1,094,841
<p>There are various snippets on the web that would give you a function to return human readable size from bytes size:</p> <pre><code>&gt;&gt;&gt; human_readable(2048) '2 kilobytes' &gt;&gt;&gt; </code></pre> <p>But is there a Python library that provides this?</p>
129
2009-07-07T20:59:32Z
23,773,174
<p>Using either powers of 1000 or <a href="http://en.wikipedia.org/wiki/Kibibyte" rel="nofollow">kibibytes</a> would be more standard-friendly:</p> <pre><code>def sizeof_fmt(num, use_kibibyte=True): base, suffix = [(1000.,'B'),(1024.,'iB')][use_kibibyte] for x in ['B'] + map(lambda x: x+suffix, list('kMGTP')): if -base &lt; num &lt; base: return "%3.1f %s" % (num, x) num /= base return "%3.1f %s" % (num, x) </code></pre> <p>P.S. Never trust a library that prints thousands with the K (uppercase) suffix :)</p>
5
2014-05-21T02:49:09Z
[ "python", "code-snippets", "filesize" ]
Reusable library to get human readable version of file size?
1,094,841
<p>There are various snippets on the web that would give you a function to return human readable size from bytes size:</p> <pre><code>&gt;&gt;&gt; human_readable(2048) '2 kilobytes' &gt;&gt;&gt; </code></pre> <p>But is there a Python library that provides this?</p>
129
2009-07-07T20:59:32Z
25,527,639
<p>If you're using Django installed you can also try <a href="https://docs.djangoproject.com/en/dev/ref/templates/builtins/#filesizeformat">filesizeformat</a>:</p> <pre><code>from django.template.defaultfilters import filesizeformat filesizeformat(1073741824) =&gt; "1.0 GB" </code></pre>
5
2014-08-27T12:47:28Z
[ "python", "code-snippets", "filesize" ]
Reusable library to get human readable version of file size?
1,094,841
<p>There are various snippets on the web that would give you a function to return human readable size from bytes size:</p> <pre><code>&gt;&gt;&gt; human_readable(2048) '2 kilobytes' &gt;&gt;&gt; </code></pre> <p>But is there a Python library that provides this?</p>
129
2009-07-07T20:59:32Z
25,613,067
<p>While I know this question is ancient, I recently came up with a version that avoids loops, using <code>log2</code> to determine the size order which doubles as a shift and an index into the suffix list:</p> <pre><code>from math import log2 _suffixes = ['bytes', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB'] def file_size(size): # determine binary order in steps of size 10 # (coerce to int, // still returns a float) order = int(log2(size) / 10) if size else 0 # format file size # (.4g results in rounded numbers for exact matches and max 3 decimals, # should never resort to exponent values) return '{:.4g} {}'.format(size / (1 &lt;&lt; (order * 10)), _suffixes[order]) </code></pre> <p>Could well be considered unpythonic for its readability, though :)</p>
15
2014-09-01T21:23:48Z
[ "python", "code-snippets", "filesize" ]
Reusable library to get human readable version of file size?
1,094,841
<p>There are various snippets on the web that would give you a function to return human readable size from bytes size:</p> <pre><code>&gt;&gt;&gt; human_readable(2048) '2 kilobytes' &gt;&gt;&gt; </code></pre> <p>But is there a Python library that provides this?</p>
129
2009-07-07T20:59:32Z
27,094,657
<p>How about the very simple:</p> <pre><code>import math def humanizeFileSize(size): size = abs(size) if (size==0): return "0B" units = ['B','KiB','MiB','GiB','TiB','PiB','EiB','ZiB','YiB'] p = math.floor(math.log(size, 2)/10) return "%.3f%s" % (size/math.pow(1024,p),units[int(p)]) if __name__ == "__main__": print humanizeFileSize(0) print humanizeFileSize(1023) print humanizeFileSize(1024) print humanizeFileSize(1024*1024*1024-1) print humanizeFileSize(1024*1024*1024) </code></pre> <hr> <p><strong>Output</strong></p> <pre><code>0B 1023.000B 1.000KiB 1024.000MiB 1.000GiB </code></pre> <p><strong>Note</strong>: The only limitation is, any size even 1 byte smaller than the next higher Unit, will be labeled as preceding Unit. So 1024*1024*1024-1 bytes will appear as 1024.000MiB (not 1 GiB)</p>
1
2014-11-23T21:39:33Z
[ "python", "code-snippets", "filesize" ]
Reusable library to get human readable version of file size?
1,094,841
<p>There are various snippets on the web that would give you a function to return human readable size from bytes size:</p> <pre><code>&gt;&gt;&gt; human_readable(2048) '2 kilobytes' &gt;&gt;&gt; </code></pre> <p>But is there a Python library that provides this?</p>
129
2009-07-07T20:59:32Z
31,178,618
<p>This will do what you need in almost any situation, is customizable with optional arguments, and as you can see, is <em>pretty</em> much self-documenting:</p> <pre><code>from math import log def pretty_size(n,pow=0,b=1024,u='B',pre=['']+[p+'i'for p in'KMGTPEZY']): pow,n=min(int(log(max(n*b**pow,1),b)),len(pre)-1),n*b**pow return "%%.%if %%s%%s"%abs(pow%(-pow-1))%(n/b**float(pow),pre[pow],u) </code></pre> <p>Example output:</p> <pre><code>&gt;&gt;&gt; pretty_size(42) '42 B' &gt;&gt;&gt; pretty_size(2015) '2.0 KiB' &gt;&gt;&gt; pretty_size(987654321) '941.9 MiB' &gt;&gt;&gt; pretty_size(9876543210) '9.2 GiB' &gt;&gt;&gt; pretty_size(0.5,pow=1) '512 B' &gt;&gt;&gt; pretty_size(0) '0 B' </code></pre> <p>Advanced customizations:</p> <pre><code>&gt;&gt;&gt; pretty_size(987654321,b=1000,u='bytes',pre=['','kilo','mega','giga']) '987.7 megabytes' &gt;&gt;&gt; pretty_size(9876543210,b=1000,u='bytes',pre=['','kilo','mega','giga']) '9.9 gigabytes' </code></pre> <p>This code is both Python 2 and Python 3 compatible. PEP8 compliance is an exercise for the reader. Remember, it's the <em>output</em> that's pretty.</p> <p><strong>Update:</strong> </p> <p>If you need thousands commas, just apply the obvious extension:</p> <pre><code>def prettier_size(n,pow=0,b=1024,u='B',pre=['']+[p+'i'for p in'KMGTPEZY']): r,f=min(int(log(max(n*b**pow,1),b)),len(pre)-1),'{:,.%if} %s%s' return (f%(abs(r%(-r-1)),pre[r],u)).format(n*b**pow/b**float(r)) </code></pre> <p>For example:</p> <pre><code>&gt;&gt;&gt; pretty_units(987654321098765432109876543210) '816,968.5 YiB' </code></pre>
3
2015-07-02T07:53:30Z
[ "python", "code-snippets", "filesize" ]
Is there a Python language specification?
1,094,961
<p>Is there anything in Python akin to Java's JLS or C#'s spec? </p>
24
2009-07-07T21:23:25Z
1,094,966
<p>No, python is defined by its implementation.</p>
-1
2009-07-07T21:25:31Z
[ "python", "specifications" ]
Is there a Python language specification?
1,094,961
<p>Is there anything in Python akin to Java's JLS or C#'s spec? </p>
24
2009-07-07T21:23:25Z
1,094,977
<p>You can check out the <a href="http://docs.python.org/dev/reference/index.html" rel="nofollow">Python Reference</a></p>
2
2009-07-07T21:26:22Z
[ "python", "specifications" ]
Is there a Python language specification?
1,094,961
<p>Is there anything in Python akin to Java's JLS or C#'s spec? </p>
24
2009-07-07T21:23:25Z
1,094,987
<p>There's no specification per se. The closest thing is the <a href="http://docs.python.org/reference/">Python Language Reference</a>, which details the syntax and semantics of the language.</p>
21
2009-07-07T21:27:30Z
[ "python", "specifications" ]
Python strings / match case
1,095,026
<p>I have a CSV file which has the following format:</p> <pre><code>id,case1,case2,case3 </code></pre> <p>Here is a sample:</p> <pre><code>123,null,X,Y 342,X,X,Y 456,null,null,null 789,null,null,X </code></pre> <p>For each line I need to know which of the cases is not null. Is there an easy way to find out which case(s) are not null without splitting the string and going through each element?</p> <p>This is what the result should look like:</p> <pre><code>123,case2:case3 342,case1:case2:case3 456:None 789:case3 </code></pre>
0
2009-07-07T21:39:56Z
1,095,058
<p>You probably want to take a look at the <a href="http://docs.python.org/library/csv.html#module-csv" rel="nofollow">CSV module</a>, which has readers and writers that will enable you to create transforms.</p> <pre><code>&gt;&gt;&gt; from StringIO import StringIO &gt;&gt;&gt; from csv import DictReader &gt;&gt;&gt; fh = StringIO(""" ... id,case1,case2,case3 ... ... 123,null,X,Y ... ... 342,X,X,Y ... ... 456,null,null,null ... ... 789,null,null,X ... """.strip()) &gt;&gt;&gt; dr = DictReader(fh) &gt;&gt;&gt; dr.next() {'case1': 'null', 'case3': 'Y', 'case2': 'X', 'id': '123'} </code></pre> <p>At which point you can do something like:</p> <pre><code>&gt;&gt;&gt; from csv import DictWriter &gt;&gt;&gt; out_fh = StringIO() &gt;&gt;&gt; writer = DictWriter(fh, fieldnames=dr.fieldnames) &gt;&gt;&gt; for mapping in dr: ... writer.write(dict((k, v) for k, v in mapping.items() if v != 'null')) ... </code></pre> <p>The last bit is just pseudocode -- not sure <code>dr.fieldnames</code> is actually a property. Replace <code>out_fh</code> with the filehandle that you'd like to output to.</p>
2
2009-07-07T21:45:33Z
[ "python", "csv" ]
Python strings / match case
1,095,026
<p>I have a CSV file which has the following format:</p> <pre><code>id,case1,case2,case3 </code></pre> <p>Here is a sample:</p> <pre><code>123,null,X,Y 342,X,X,Y 456,null,null,null 789,null,null,X </code></pre> <p>For each line I need to know which of the cases is not null. Is there an easy way to find out which case(s) are not null without splitting the string and going through each element?</p> <p>This is what the result should look like:</p> <pre><code>123,case2:case3 342,case1:case2:case3 456:None 789:case3 </code></pre>
0
2009-07-07T21:39:56Z
1,095,059
<p>Why do you treat spliting as a problem? For performance reasons?</p> <p>Literally you could avoid splitting with smart regexps (like:</p> <pre><code>\d+,null,\w+,\w+ \d+,\w+,null,\w+ ... </code></pre> <p>but I find it a worse solution than reparsing the data into lists.</p>
0
2009-07-07T21:46:31Z
[ "python", "csv" ]
Python strings / match case
1,095,026
<p>I have a CSV file which has the following format:</p> <pre><code>id,case1,case2,case3 </code></pre> <p>Here is a sample:</p> <pre><code>123,null,X,Y 342,X,X,Y 456,null,null,null 789,null,null,X </code></pre> <p>For each line I need to know which of the cases is not null. Is there an easy way to find out which case(s) are not null without splitting the string and going through each element?</p> <p>This is what the result should look like:</p> <pre><code>123,case2:case3 342,case1:case2:case3 456:None 789:case3 </code></pre>
0
2009-07-07T21:39:56Z
1,095,064
<p>Anyway you slice it, you are still going to have to go through the list. There are more and less elegant ways to do it. Depending on the python version you are using, you can use list comprehensions.</p> <pre><code>ids=line.split(",") print "%s:%s" % (ids[0], ":".join(["case%d" % x for x in range(1, len(ids)) if ids[x] != "null"]) </code></pre>
1
2009-07-07T21:47:14Z
[ "python", "csv" ]
Python strings / match case
1,095,026
<p>I have a CSV file which has the following format:</p> <pre><code>id,case1,case2,case3 </code></pre> <p>Here is a sample:</p> <pre><code>123,null,X,Y 342,X,X,Y 456,null,null,null 789,null,null,X </code></pre> <p>For each line I need to know which of the cases is not null. Is there an easy way to find out which case(s) are not null without splitting the string and going through each element?</p> <p>This is what the result should look like:</p> <pre><code>123,case2:case3 342,case1:case2:case3 456:None 789:case3 </code></pre>
0
2009-07-07T21:39:56Z
1,095,075
<p>You could use the Python <a href="http://docs.python.org/library/csv.html" rel="nofollow">csv module</a>, comes in with the standard installation of python... It will not be <code>much</code> easier, though...</p>
0
2009-07-07T21:49:58Z
[ "python", "csv" ]
Django file upload input validation and security
1,095,250
<p>I'm creating a <strong>very</strong> simple django upload application but I want to make it as secure as possible. This is app is going to be completely one way, IE. anybody who uploads a file will never have to retrieve it. So far I've done the following:</p> <ol> <li>Disallow certain file extensions (.php, .html, .py, .rb, .pl, .cgi, .htaccess, etc)</li> <li>Set a maximum file size limit and file name character length limit.</li> <li>Password protected the directory that the files are uploaded to (with .htaccess owned by root so the web server cannot possibly overwrite it)</li> </ol> <p>Assuming that apache and mod_python are on the front end of this and that apache itself has been secured, are there any other "best practice" things I should do or consider to protect my application?</p> <p>Thanks in advance.</p>
1
2009-07-07T22:50:23Z
1,095,662
<p>Disallowing a file extension is -- potentially -- a waste of time. A unix server doesn't use the extension -- it uses ownership and permissions. </p> <p>When accepting an upload, you will often rename the file to prevent it being misused. Uploaded files should be simply named "upload_xxx" with the "xxx" being a key to some database record that provides the claimed name and data type.</p> <p>You have to actually read the file and confirm that the content of the file is what someone claims it is. </p> <p>For example, if they claim to upload a .JPG, you have to actually read the file to be sure it's a JPEG, not an .EXE.</p>
4
2009-07-08T01:17:23Z
[ "python", "django", "security", "file-upload" ]
Django file upload input validation and security
1,095,250
<p>I'm creating a <strong>very</strong> simple django upload application but I want to make it as secure as possible. This is app is going to be completely one way, IE. anybody who uploads a file will never have to retrieve it. So far I've done the following:</p> <ol> <li>Disallow certain file extensions (.php, .html, .py, .rb, .pl, .cgi, .htaccess, etc)</li> <li>Set a maximum file size limit and file name character length limit.</li> <li>Password protected the directory that the files are uploaded to (with .htaccess owned by root so the web server cannot possibly overwrite it)</li> </ol> <p>Assuming that apache and mod_python are on the front end of this and that apache itself has been secured, are there any other "best practice" things I should do or consider to protect my application?</p> <p>Thanks in advance.</p>
1
2009-07-07T22:50:23Z
5,921,094
<p>Also, you might want to put the target files outside Apache's DocumentRoot directory, so that they are not reachable by any URL. Rules in .htaccess offer a certain amount of protection if they're written well, but if you're seeking for maximum security, just put the files away from web-reachable directory.</p>
1
2011-05-07T12:38:50Z
[ "python", "django", "security", "file-upload" ]
Matrix from Python to MATLAB
1,095,265
<p>I'm working with Python and MATLAB right now and I have a 2D array in Python that I need to write to a file and then be able to read it into MATLAB as a matrix. Any ideas on how to do this? </p> <p>Thanks!</p>
25
2009-07-07T22:55:08Z
1,095,296
<p>You could write the matrix in Python to a CSV file and read it in MATLAB using csvread.</p>
3
2009-07-07T23:03:12Z
[ "python", "matlab", "file-io", "import", "matrix" ]
Matrix from Python to MATLAB
1,095,265
<p>I'm working with Python and MATLAB right now and I have a 2D array in Python that I need to write to a file and then be able to read it into MATLAB as a matrix. Any ideas on how to do this? </p> <p>Thanks!</p>
25
2009-07-07T22:55:08Z
1,095,324
<p>If you use numpy/scipy, you can use the <code>scipy.io.savemat</code> function:</p> <pre><code>import numpy, scipy.io arr = numpy.arange(10) arr = arr.reshape((3, 3)) # 2d array of 3x3 scipy.io.savemat('c:/tmp/arrdata.mat', mdict={'arr': arr}) </code></pre> <p>Now, you can load this data into MATLAB using File -> Load Data. Select the file and the <code>arr</code> variable (a 3x3 matrix) will be available in your environment.</p> <p>Note: I did this on scipy 0.7.0. (scipy 0.6 has <code>savemat</code> in the <code>scipy.io.mio</code> module.) See the <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.io.savemat.html">latest documentation for more detail</a></p> <p>EDIT: updated link thanks to <a href="http://stackoverflow.com/questions/1095265/matrix-from-python-to-matlab#comment909707_1095324">@gnovice</a>.</p>
40
2009-07-07T23:13:52Z
[ "python", "matlab", "file-io", "import", "matrix" ]
Matrix from Python to MATLAB
1,095,265
<p>I'm working with Python and MATLAB right now and I have a 2D array in Python that I need to write to a file and then be able to read it into MATLAB as a matrix. Any ideas on how to do this? </p> <p>Thanks!</p>
25
2009-07-07T22:55:08Z
1,095,414
<p>I wrote a small function to do this same thing, without need for numpy. It takes a list of lists and returns a string with a MATLAB-formatted matrix.</p> <pre><code>def arrayOfArrayToMatlabString(array): return '[' + "\n ".join(" ".join("%6g" % val for val in line) for line in array) + ']' </code></pre> <p>Write <code>"myMatrix = " + arrayOfArrayToMatlabString(array)</code> to a <code>.m</code> file, open it in matlab, and execute it.</p>
4
2009-07-07T23:45:29Z
[ "python", "matlab", "file-io", "import", "matrix" ]
Matrix from Python to MATLAB
1,095,265
<p>I'm working with Python and MATLAB right now and I have a 2D array in Python that I need to write to a file and then be able to read it into MATLAB as a matrix. Any ideas on how to do this? </p> <p>Thanks!</p>
25
2009-07-07T22:55:08Z
1,095,505
<p>I think <a href="http://stackoverflow.com/questions/1095265/matrix-from-python-to-matlab/1095324#1095324">ars</a> has the most straight-forward answer for saving the data to a .mat file from Python (using <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.io.savemat.html">savemat</a>). To add just a little to their answer, you can also load the .mat file into MATLAB programmatically using the <a href="http://www.mathworks.com/access/helpdesk/help/techdoc/ref/load.shtml">LOAD</a> function instead of doing it by hand using the MATLAB command window menu...</p> <p>You can use either the <em>command syntax</em> form of LOAD:</p> <pre><code>load c:/tmp/arrdata.mat </code></pre> <p>or the <em>function syntax</em> form (if you have the file path stored in a string):</p> <pre><code>filePath = 'c:/tmp/arrdata.mat'; data = load(filePath); </code></pre>
7
2009-07-08T00:13:44Z
[ "python", "matlab", "file-io", "import", "matrix" ]
Matrix from Python to MATLAB
1,095,265
<p>I'm working with Python and MATLAB right now and I have a 2D array in Python that I need to write to a file and then be able to read it into MATLAB as a matrix. Any ideas on how to do this? </p> <p>Thanks!</p>
25
2009-07-07T22:55:08Z
6,885,144
<p>You can also <a href="http://mlabwrap.sourceforge.net/" rel="nofollow">call matlab</a> directly from python:</p> <pre><code>from mlabwrap import mlab import numpy a = numpy.array([1,2,3]) mlab.plot(a) </code></pre>
1
2011-07-30T18:26:42Z
[ "python", "matlab", "file-io", "import", "matrix" ]
Matrix from Python to MATLAB
1,095,265
<p>I'm working with Python and MATLAB right now and I have a 2D array in Python that I need to write to a file and then be able to read it into MATLAB as a matrix. Any ideas on how to do this? </p> <p>Thanks!</p>
25
2009-07-07T22:55:08Z
7,737,622
<p>I would probably use <code>numpy.savetxt('yourfile.mat',yourarray)</code> in Python and then <code>yourarray = load('yourfile.mat')</code> in MATLAB.</p>
2
2011-10-12T09:03:07Z
[ "python", "matlab", "file-io", "import", "matrix" ]
Finding partial strings in a list of strings - python
1,095,270
<p>I am trying to check if a user is a member of an Active Directory group, and I have this:</p> <pre><code>ldap.set_option(ldap.OPT_REFERRALS, 0) try: con = ldap.initialize(LDAP_URL) con.simple_bind_s(userid+"@"+ad_settings.AD_DNS_NAME, password) ADUser = con.search_ext_s(ad_settings.AD_SEARCH_DN, ldap.SCOPE_SUBTREE, \ "sAMAccountName=%s" % userid, ad_settings.AD_SEARCH_FIELDS)[0][1] except ldap.LDAPError: return None </code></pre> <p><code>ADUser</code> returns a list of strings:</p> <pre><code>{'givenName': ['xxxxx'], 'mail': ['xxxxx@example.com'], 'memberOf': ['CN=group1,OU=Projects,OU=Office,OU=company,DC=domain,DC=com', 'CN=group2,OU=Projects,OU=Office,OU=company,DC=domain,DC=com', 'CN=group3,OU=Projects,OU=Office,OU=company,DC=domain,DC=com', 'CN=group4,OU=Projects,OU=Office,OU=company,DC=domain,DC=com'], 'sAMAccountName': ['myloginid'], 'sn': ['Xxxxxxxx']} </code></pre> <p>Of course in the real world the group names are verbose and of varied structure, and users will belong to tens or hundreds of groups.</p> <p>If I get the list of groups out as <code>ADUser.get('memberOf')[0]</code>, what is the best way to check if any members of a separate list exist in the main list?</p> <p>For example, the check list would be <code>['group2', 'group16']</code> and I want to get a true/false answer as to whether <em>any</em> of the smaller list exist in the main list.</p>
0
2009-07-07T22:56:02Z
1,095,360
<p>You can use set intersection (&amp; operator) once you parse the group list out. For example:</p> <pre><code>&gt; memberOf = 'CN=group1,OU=Projects,OU=Office,OU=company,DC=domain,DC=com' &gt; groups = [token.split('=')[1] for token in memberOf.split(',')] &gt; groups ['group1', 'Projects', 'Office', 'company', 'domain', 'com'] &gt; checklist1 = ['group1', 'group16'] &gt; set(checklist1) &amp; set(groups) set(['group1']) &gt; checklist2 = ['group2', 'group16'] &gt; set(checklist2) &amp; set(groups) set([]) </code></pre> <p>Note that a conditional evaluation on a set works the same as for lists and tuples. True if there are any elements in the set, False otherwise. So, <code>"if set(checklist2) &amp; set(groups): ..."</code> would not execute since the condition evaluates to False in the above example (the opposite is true for the checklist1 test).</p> <p>Also see:</p> <p><a href="http://docs.python.org/library/sets.html" rel="nofollow">http://docs.python.org/library/sets.html</a></p>
1
2009-07-07T23:28:46Z
[ "python", "regex", "list" ]
Finding partial strings in a list of strings - python
1,095,270
<p>I am trying to check if a user is a member of an Active Directory group, and I have this:</p> <pre><code>ldap.set_option(ldap.OPT_REFERRALS, 0) try: con = ldap.initialize(LDAP_URL) con.simple_bind_s(userid+"@"+ad_settings.AD_DNS_NAME, password) ADUser = con.search_ext_s(ad_settings.AD_SEARCH_DN, ldap.SCOPE_SUBTREE, \ "sAMAccountName=%s" % userid, ad_settings.AD_SEARCH_FIELDS)[0][1] except ldap.LDAPError: return None </code></pre> <p><code>ADUser</code> returns a list of strings:</p> <pre><code>{'givenName': ['xxxxx'], 'mail': ['xxxxx@example.com'], 'memberOf': ['CN=group1,OU=Projects,OU=Office,OU=company,DC=domain,DC=com', 'CN=group2,OU=Projects,OU=Office,OU=company,DC=domain,DC=com', 'CN=group3,OU=Projects,OU=Office,OU=company,DC=domain,DC=com', 'CN=group4,OU=Projects,OU=Office,OU=company,DC=domain,DC=com'], 'sAMAccountName': ['myloginid'], 'sn': ['Xxxxxxxx']} </code></pre> <p>Of course in the real world the group names are verbose and of varied structure, and users will belong to tens or hundreds of groups.</p> <p>If I get the list of groups out as <code>ADUser.get('memberOf')[0]</code>, what is the best way to check if any members of a separate list exist in the main list?</p> <p>For example, the check list would be <code>['group2', 'group16']</code> and I want to get a true/false answer as to whether <em>any</em> of the smaller list exist in the main list.</p>
0
2009-07-07T22:56:02Z
1,095,909
<p>If the format example you give is somewhat reliable, something like:</p> <pre><code>import re grps = re.compile(r'CN=(\w+)').findall def anyof(short_group_list, adu): all_groups_of_user = set(g for gs in adu.get('memberOf',()) for g in grps(gs)) return sorted(all_groups_of_user.intersection(short_group_list)) </code></pre> <p>where you pass your list such as <code>['group2', 'group16']</code> as the first argument, your <code>ADUser</code> dict as the second argument; this returns an alphabetically sorted list (possibly empty, meaning "none") of the groups, among those in <code>short_group_list</code>, to which the user belongs. </p> <p>It's probably not much faster to just a bool, but, if you insist, changing the second statement of the function to:</p> <pre><code> return any(g for g in short_group_list if g in all_groups_of_user) </code></pre> <p>might possibly save a certain amount of time in the "true" case (since <code>any</code> short-circuits) though I suspect not in the "false" case (where the whole list must be traversed anyway). If you care about the performance issue, best is to benchmark both possibilities on data that's realistic for your use case!</p> <p>If performance isn't yet good enough (and a bool yes/no is sufficient, as you say), try reversing the looping logic:</p> <pre><code>def anyof_v2(short_group_list, adu): gset = set(short_group_list) return any(g for gs in adu.get('memberOf',()) for g in grps(gs) if g in gset) </code></pre> <p><code>any</code>'s short-circuit abilities might prove more useful here (at least in the "true" case, again -- because, again, there's no way to give a "false" result without examining ALL the possibilities anyway!-).</p>
2
2009-07-08T02:50:51Z
[ "python", "regex", "list" ]
Alternative Python imaging libraries on Google App Engine?
1,095,325
<p>I am thinking about uploading images to Google App Engine, but I need to brighten parts of the image. I am not sure if the App Engine imagine API will be sufficient. I consider to try an overlay with a white image and partial opacity. </p> <p>However, if that does not yield the desired results, would there be another Python imaging library that works with App Engine? Basically it would have to be pure Python (no associated C code or anything).</p>
4
2009-07-07T23:14:04Z
1,095,867
<p><a href="http://the.taoofmac.com/space/projects/PNGCanvas" rel="nofollow">PNGcanvas</a> might help, if PNG input and output is satisfactory -- it doesn't directly offer the "brighten" functionality you require, but it does let you load and save PNG files into memory and access them directly from Python, and it IS a single, simple Python source file.</p>
4
2009-07-08T02:30:26Z
[ "python", "google-app-engine", "python-imaging-library" ]
Get __name__ of calling function's module in Python
1,095,543
<p>Suppose <code>myapp/foo.py</code> contains:</p> <pre><code>def info(msg): caller_name = ???? print '[%s] %s' % (caller_name, msg) </code></pre> <p>And <code>myapp/bar.py</code> contains:</p> <pre><code>import foo foo.info('Hello') # =&gt; [myapp.foo] Hello </code></pre> <p>I want <code>caller_name</code> to be set to the <code>__name__</code> attribute of the calling functions' module (which is 'myapp.foo') in this case. How can this be done?</p>
54
2009-07-08T00:30:47Z
1,095,621
<p>Check out the inspect module:</p> <p><code>inspect.stack()</code> will return the stack information.</p> <p>Inside a function, <code>inspect.stack()[1]</code> will return your caller's stack. From there, you can get more information about the caller's function name, module, etc.</p> <p>See the docs for details:</p> <p><a href="http://docs.python.org/library/inspect.html">http://docs.python.org/library/inspect.html</a></p> <p>Also, Doug Hellmann has a nice writeup of the inspect module in his PyMOTW series:</p> <p><a href="http://pymotw.com/2/inspect/index.html#module-inspect">http://pymotw.com/2/inspect/index.html#module-inspect</a></p> <p>EDIT: Here's some code which does what you want, I think:</p> <pre><code>def info(msg): frm = inspect.stack()[1] mod = inspect.getmodule(frm[0]) print '[%s] %s' % (mod.__name__, msg) </code></pre>
80
2009-07-08T01:03:42Z
[ "python", "stack-trace", "introspection" ]
Get __name__ of calling function's module in Python
1,095,543
<p>Suppose <code>myapp/foo.py</code> contains:</p> <pre><code>def info(msg): caller_name = ???? print '[%s] %s' % (caller_name, msg) </code></pre> <p>And <code>myapp/bar.py</code> contains:</p> <pre><code>import foo foo.info('Hello') # =&gt; [myapp.foo] Hello </code></pre> <p>I want <code>caller_name</code> to be set to the <code>__name__</code> attribute of the calling functions' module (which is 'myapp.foo') in this case. How can this be done?</p>
54
2009-07-08T00:30:47Z
1,095,711
<p>I don't recommend do this, but you can accomplish your goal with the following method:</p> <pre><code>def caller_name(): frame=inspect.currentframe() frame=frame.f_back.f_back code=frame.f_code return code.co_filename </code></pre> <p>Then update your existing method as follows:</p> <pre><code>def info(msg): caller = caller_name() print '[%s] %s' % (caller, msg) </code></pre>
3
2009-07-08T01:32:12Z
[ "python", "stack-trace", "introspection" ]
Get __name__ of calling function's module in Python
1,095,543
<p>Suppose <code>myapp/foo.py</code> contains:</p> <pre><code>def info(msg): caller_name = ???? print '[%s] %s' % (caller_name, msg) </code></pre> <p>And <code>myapp/bar.py</code> contains:</p> <pre><code>import foo foo.info('Hello') # =&gt; [myapp.foo] Hello </code></pre> <p>I want <code>caller_name</code> to be set to the <code>__name__</code> attribute of the calling functions' module (which is 'myapp.foo') in this case. How can this be done?</p>
54
2009-07-08T00:30:47Z
5,071,539
<p>Confronted with a similar problem, I have found that <strong>sys._current_frames()</strong> from the sys module contains interesting information that can help you, without the need to import inspect, at least in specific use cases.</p> <pre><code>&gt;&gt;&gt; sys._current_frames() {4052: &lt;frame object at 0x03200C98&gt;} </code></pre> <p>You can then "move up" using f_back :</p> <pre><code>&gt;&gt;&gt; f = sys._current_frames().values()[0] &gt;&gt;&gt; print f.f_back.f_globals['__file__'] '/base/data/home/apps/apricot/1.6456165165151/caller.py' &gt;&gt;&gt; print f.f_back.f_globals['__name__'] '__main__' </code></pre> <p>For the filename you can also use f.f_back.f_code.co_filename, as suggested by Mark Roddy above. I am not sure of the limits and caveats of this method (multiple threads will most likely be a problem) but I intend to use it in my case.</p>
12
2011-02-21T21:35:29Z
[ "python", "stack-trace", "introspection" ]
Sending SIGINT to a subprocess of python
1,095,549
<p>I've got a python script managing a gdb process on windows, and I need to be able to send a SIGINT to the spawned process in order to halt the target process (managed by gdb) </p> <p>It appears that there is only SIGTERM available in win32, but clearly if I run gdb from the console and Ctrl+C, it thinks it's receiving a SIGINT. Is there a way I can fake this such that the functionality is available on all platforms?</p> <p>(I am using the subprocess module, and python 2.5/2.6)</p>
4
2009-07-08T00:34:14Z
1,095,597
<p>Windows doesn't have the unix signals IPC mechanism.</p> <p>I would look at sending a CTRL-C to the gdb process.</p>
1
2009-07-08T00:52:20Z
[ "python", "subprocess", "sigint" ]
Find module name of the originating exception in Python
1,095,601
<p>Example:</p> <pre><code>&gt;&gt;&gt; try: ... myapp.foo.doSomething() ... except Exception, e: ... print 'Thrown from:', modname(e) Thrown from: myapp.util.url </code></pre> <p>In the above example, the exception was actually thrown at myapp/util/url.py module. Is there a way to get the <code>__name__</code> of that module?</p> <p>My intention is to use this in <code>logging.getLogger</code> function.</p>
9
2009-07-08T00:55:16Z
1,095,627
<p>This should do the trick:</p> <pre><code>import inspect def modname(): t=inspect.trace() if t: return t[-1][1] </code></pre>
0
2009-07-08T01:06:58Z
[ "python", "exception", "logging", "stack-trace", "introspection" ]
Find module name of the originating exception in Python
1,095,601
<p>Example:</p> <pre><code>&gt;&gt;&gt; try: ... myapp.foo.doSomething() ... except Exception, e: ... print 'Thrown from:', modname(e) Thrown from: myapp.util.url </code></pre> <p>In the above example, the exception was actually thrown at myapp/util/url.py module. Is there a way to get the <code>__name__</code> of that module?</p> <p>My intention is to use this in <code>logging.getLogger</code> function.</p>
9
2009-07-08T00:55:16Z
1,095,656
<p>You can use the <a href="http://docs.python.org/library/traceback.html">traceback module</a>, along with <a href="http://docs.python.org/library/sys.html#sys.exc%5Finfo"><code>sys.exc_info()</code></a>, to get the traceback programmatically:</p> <pre><code>try: myapp.foo.doSomething() except Exception, e: exc_type, exc_value, exc_tb = sys.exc_info() filename, line_num, func_name, text = traceback.extract_tb(exc_tb)[-1] print 'Thrown from: %s' % filename </code></pre>
6
2009-07-08T01:15:58Z
[ "python", "exception", "logging", "stack-trace", "introspection" ]
Find module name of the originating exception in Python
1,095,601
<p>Example:</p> <pre><code>&gt;&gt;&gt; try: ... myapp.foo.doSomething() ... except Exception, e: ... print 'Thrown from:', modname(e) Thrown from: myapp.util.url </code></pre> <p>In the above example, the exception was actually thrown at myapp/util/url.py module. Is there a way to get the <code>__name__</code> of that module?</p> <p>My intention is to use this in <code>logging.getLogger</code> function.</p>
9
2009-07-08T00:55:16Z
1,096,213
<p>This should work:</p> <pre><code>import inspect try: some_bad_code() except Exception, e: frm = inspect.trace()[-1] mod = inspect.getmodule(frm[0]) print 'Thrown from', mod.__name__ </code></pre> <p>EDIT: Stephan202 mentions a corner case. In this case, I think we could default to the file name.</p> <pre><code>import inspect try: import bad_module except Exception, e: frm = inspect.trace()[-1] mod = inspect.getmodule(frm[0]) modname = mod.__name__ if mod else frm[1] print 'Thrown from', modname </code></pre> <p>The problem is that if the module doesn't get loaded (because an exception was thrown while reading the code in that file), then the <code>inspect.getmodule</code> call returns None. So, we just use the name of the file referenced by the offending frame. (Thanks for pointing this out, Stephan202!)</p>
8
2009-07-08T05:19:23Z
[ "python", "exception", "logging", "stack-trace", "introspection" ]
Find module name of the originating exception in Python
1,095,601
<p>Example:</p> <pre><code>&gt;&gt;&gt; try: ... myapp.foo.doSomething() ... except Exception, e: ... print 'Thrown from:', modname(e) Thrown from: myapp.util.url </code></pre> <p>In the above example, the exception was actually thrown at myapp/util/url.py module. Is there a way to get the <code>__name__</code> of that module?</p> <p>My intention is to use this in <code>logging.getLogger</code> function.</p>
9
2009-07-08T00:55:16Z
1,096,327
<p>Python's logging package already supports this - check the <a href="http://docs.python.org/library/logging.html#formatter-objects" rel="nofollow">documentation</a>. You just have to specify <code>%(module)s</code> in the format string. However, this gives you the module where the exception was <em>caught</em> - not necessarily the same as the one where it was <em>raised</em>. The traceback, of course, gives you the precise location where the exception was raised.</p>
0
2009-07-08T06:01:38Z
[ "python", "exception", "logging", "stack-trace", "introspection" ]
Find module name of the originating exception in Python
1,095,601
<p>Example:</p> <pre><code>&gt;&gt;&gt; try: ... myapp.foo.doSomething() ... except Exception, e: ... print 'Thrown from:', modname(e) Thrown from: myapp.util.url </code></pre> <p>In the above example, the exception was actually thrown at myapp/util/url.py module. Is there a way to get the <code>__name__</code> of that module?</p> <p>My intention is to use this in <code>logging.getLogger</code> function.</p>
9
2009-07-08T00:55:16Z
1,169,138
<p>I have a story about how CrashKit computes class names and package names from Python stack traces on the company blog: “<a href="http://blog.yoursway.com/2009/07/python-stack-trace-saga.html" rel="nofollow">Python stack trace saga</a>”. Working code included.</p>
0
2009-07-23T01:36:25Z
[ "python", "exception", "logging", "stack-trace", "introspection" ]
Does get_or_create() have to save right away? (Django)
1,095,663
<p>I need to use something like get_or_create() but the problem is that I have a lot of fields and I don't want to set defaults (which don't make sense anyway), and if I don't set defaults it returns an error, because it saves the object right away apparently.</p> <p>I can set the fields to null=True, but I don't want null fields.</p> <p>Is there any other method or any extra parameter that can be sent to get_or_create() so that it instantiates an object but doesn't save it until I call save() on it?</p> <p>Thanks.</p>
33
2009-07-08T01:17:30Z
1,095,706
<p>You can just do:</p> <pre><code>try: obj = Model.objects.get(**kwargs) except Model.DoesNotExist: obj = Model(**dict((k,v) for (k,v) in kwargs.items() if '__' not in k)) </code></pre> <p>which is pretty much what <a href="https://github.com/django/django/blob/master/django/db/models/query.py#L454" rel="nofollow"><code>get_or_create</code></a> does, sans commit.</p>
34
2009-07-08T01:29:09Z
[ "python", "django" ]
where does django install in ubuntu
1,095,725
<p>I am looking for the <strong>init</strong>.py file for django. I tried whereis and find, but I get a lot of dirs.</p>
29
2009-07-08T01:38:33Z
1,095,738
<p><a href="http://ubuntuforums.org/showthread.php?t=627773" rel="nofollow">http://ubuntuforums.org/showthread.php?t=627773</a></p>
2
2009-07-08T01:41:28Z
[ "python", "django", "ubuntu" ]
where does django install in ubuntu
1,095,725
<p>I am looking for the <strong>init</strong>.py file for django. I tried whereis and find, but I get a lot of dirs.</p>
29
2009-07-08T01:38:33Z
1,095,862
<p>you can just print it out.</p> <pre><code>&gt;&gt;&gt; import django &gt;&gt;&gt; print django.__file__ /var/lib/python-support/python2.5/django/__init__.pyc &gt;&gt;&gt; </code></pre> <p>or:</p> <pre><code>import inspect import django print inspect.getabsfile(django) </code></pre>
86
2009-07-08T02:26:58Z
[ "python", "django", "ubuntu" ]
where does django install in ubuntu
1,095,725
<p>I am looking for the <strong>init</strong>.py file for django. I tried whereis and find, but I get a lot of dirs.</p>
29
2009-07-08T01:38:33Z
1,251,732
<p>This (or something like this) also works when you are searching for files in other packages:</p> <pre><code>$ dpkg -L python-django | grep __init__.py </code></pre>
3
2009-08-09T16:50:09Z
[ "python", "django", "ubuntu" ]