title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
sequence
User Authentication in Pylons + AuthKit
47,801
<p>I am trying to create a web application using Pylons and the resources on the web point to the <a href="http://pylonsbook.com/alpha1/authentication_and_authorization">PylonsBook</a> page which isn't of much help. I want authentication and authorisation and is there anyway to setup Authkit to work easily with Pylons?</p> <p>I tried downloading the <a href="http://pypi.python.org/pypi/SimpleSiteTemplate/">SimpleSiteTemplate</a> from the cheeseshop but wasn't able to run the setup-app command. It throws up an error:</p> <pre><code> File "/home/cnu/env/lib/python2.5/site-packages/SQLAlchemy-0.4.7-py2.5.egg/sqlalchemy/schema.py", line 96, in __call__ table = metadata.tables[key] AttributeError: 'module' object has no attribute 'tables' </code></pre> <p>I use Pylons 0.9.7rc1, SQLAlchemy 0.4.7, Authkit 0.4.</p>
6
2008-09-06T20:17:45Z
948,216
<p>I gave up on authkit and rolled my own: <a href="http://tonylandis.com/openid-db-authentication-in-pylons-is-easy-with-rpx/" rel="nofollow">http://tonylandis.com/openid-db-authentication-in-pylons-is-easy-with-rpx/</a></p>
3
2009-06-04T01:41:31Z
[ "python", "authentication", "sqlalchemy", "pylons", "authkit" ]
What are the advantages of packaging your python library/application as an .egg file?
47,953
<p>I've read some about .egg files and I've noticed them in my lib directory but what are the advantages/disadvantages of using then as a developer?</p>
23
2008-09-06T23:35:30Z
47,956
<p>From the <a href="http://peak.telecommunity.com/DevCenter/PythonEggs">Python Enterprise Application Kit community</a>:</p> <blockquote> <p><em>"Eggs are to Pythons as Jars are to Java..."</em></p> <p>Python eggs are a way of bundling additional information with a Python project, that allows the project's dependencies to be checked and satisfied at runtime, as well as allowing projects to provide plugins for other projects. There are several binary formats that embody eggs, but the most common is '.egg' zipfile format, because it's a convenient one for distributing projects. All of the formats support including package-specific data, project-wide metadata, C extensions, and Python code.</p> <p>The primary benefits of Python Eggs are:</p> <ul> <li><p>They enable tools like the "Easy Install" Python package manager</p></li> <li><p>.egg files are a "zero installation" format for a Python package; no build or install step is required, just put them on PYTHONPATH or sys.path and use them (may require the runtime installed if C extensions or data files are used)</p></li> <li><p>They can include package metadata, such as the other eggs they depend on</p></li> <li><p>They allow "namespace packages" (packages that just contain other packages) to be split into separate distributions (e.g. zope.<em>, twisted.</em>, peak.* packages can be distributed as separate eggs, unlike normal packages which must always be placed under the same parent directory. This allows what are now huge monolithic packages to be distributed as separate components.)</p></li> <li><p>They allow applications or libraries to specify the needed version of a library, so that you can e.g. require("Twisted-Internet>=2.0") before doing an import twisted.internet.</p></li> <li><p>They're a great format for distributing extensions or plugins to extensible applications and frameworks (such as Trac, which uses eggs for plugins as of 0.9b1), because the egg runtime provides simple APIs to locate eggs and find their advertised entry points (similar to Eclipse's "extension point" concept).</p></li> <li><p>There are also other benefits that may come from having a standardized format, similar to the benefits of Java's "jar" format.</p></li> </ul> </blockquote>
29
2008-09-06T23:39:33Z
[ "python", "zip", "packaging", "software-distribution", "egg" ]
What are the advantages of packaging your python library/application as an .egg file?
47,953
<p>I've read some about .egg files and I've noticed them in my lib directory but what are the advantages/disadvantages of using then as a developer?</p>
23
2008-09-06T23:35:30Z
47,957
<p>.egg files are basically a nice way to deploy your python application. You can think of it as something like .jar files for Java. </p> <p>More info <a href="http://peak.telecommunity.com/DevCenter/PythonEggs" rel="nofollow">here</a>.</p>
2
2008-09-06T23:39:54Z
[ "python", "zip", "packaging", "software-distribution", "egg" ]
What are the advantages of packaging your python library/application as an .egg file?
47,953
<p>I've read some about .egg files and I've noticed them in my lib directory but what are the advantages/disadvantages of using then as a developer?</p>
23
2008-09-06T23:35:30Z
47,958
<p>Eggs are a pretty good way to distribute python apps. Think of it as a platform independent .deb file that will install all dependencies and whatnot. The advantage is that it's easy to use for the end user. The disadvantage are that it can be cumbersome to package your app up as a .egg file.</p> <p>You should also offer an alternative means of installation in addition to .eggs. There are some people who don't like using eggs because they don't like the idea of a software program installing whatever software it wants. These usually tend to be sysadmin types.</p>
3
2008-09-06T23:43:21Z
[ "python", "zip", "packaging", "software-distribution", "egg" ]
What are the advantages of packaging your python library/application as an .egg file?
47,953
<p>I've read some about .egg files and I've noticed them in my lib directory but what are the advantages/disadvantages of using then as a developer?</p>
23
2008-09-06T23:35:30Z
137,903
<p>Whatever you do, do not stop distributing your application, also, as a tarball, as that is the easiest packagable format for operating systems with a package sysetem.</p>
1
2008-09-26T05:26:03Z
[ "python", "zip", "packaging", "software-distribution", "egg" ]
What are the advantages of packaging your python library/application as an .egg file?
47,953
<p>I've read some about .egg files and I've noticed them in my lib directory but what are the advantages/disadvantages of using then as a developer?</p>
23
2008-09-06T23:35:30Z
138,090
<p>For simple Python programs, you probably don't need to use eggs. Distributing the raw .py files should suffice; it's like distributing source files for GNU/Linux. You can also use the various OS "packagers" (like py2exe or py2app) to create .exe, .dmg, or other files for different operating systems.</p> <p>More complex programs, e.g. Django, pretty much require eggs due to the various modules and dependencies required.</p>
1
2008-09-26T07:01:59Z
[ "python", "zip", "packaging", "software-distribution", "egg" ]
What are the advantages of packaging your python library/application as an .egg file?
47,953
<p>I've read some about .egg files and I've noticed them in my lib directory but what are the advantages/disadvantages of using then as a developer?</p>
23
2008-09-06T23:35:30Z
197,811
<p>One egg by itself is not better than a proper source release. The good part is the dependency handling. Like debian or rpm packages, you can say you depend on other eggs and they'll be installed automatically (through <a href="http://pypi.python.org" rel="nofollow">pypi.python.org</a>).</p> <p>A second comment: the egg format itself is a binary packaged format. Normal python packages that consist of just python code are best distributed as "source releases", so "python setup.py sdist" which result in a .tar.gz. These are also commonly called "eggs" when uploaded to pypi.</p> <p>Where you need binary eggs: when you're bundling some C code extension. You'll need several binary eggs (a 32bit unix one, a windows one, etc.) then.</p>
3
2008-10-13T14:40:35Z
[ "python", "zip", "packaging", "software-distribution", "egg" ]
Glade or no glade: What is the best way to use PyGtk?
48,123
<p>I've been learning python for a while now with some success. I even managed to create one or two (simple) programs using PyGtk + Glade.</p> <p>The thing is: I am not sure if the best way to use GTK with python is by building the interfaces using Glade.</p> <p>I was wondering if the more experienced ones among us (remember, I'm just a beginner) could point out the benefits and caveats of using Glade as opposed to creating everything in the code itself (assuming that learning the correct gtk bindings wouldn't exactly be a problem).</p>
27
2008-09-07T04:00:41Z
48,136
<p>Use GtkBuilder instead of Glade, it's integrated into Gtk itself instead of a separate library.</p> <p>The main benefit of Glade is that it's much, much easier to create the interface. It's a bit more work to connect signal handlers, but I've never felt that matters much.</p>
12
2008-09-07T04:20:06Z
[ "python", "gtk", "pygtk", "glade", "gtk2" ]
Glade or no glade: What is the best way to use PyGtk?
48,123
<p>I've been learning python for a while now with some success. I even managed to create one or two (simple) programs using PyGtk + Glade.</p> <p>The thing is: I am not sure if the best way to use GTK with python is by building the interfaces using Glade.</p> <p>I was wondering if the more experienced ones among us (remember, I'm just a beginner) could point out the benefits and caveats of using Glade as opposed to creating everything in the code itself (assuming that learning the correct gtk bindings wouldn't exactly be a problem).</p>
27
2008-09-07T04:00:41Z
48,734
<p>I would say that it depends: if you find that using Glade you can build the apps you want or need to make than that's absolutely fine. If however you actually want to learn how GTK works or you have some non-standard UI requirements you will <strong>have</strong> to dig into GTK internals (which are not that complicated).</p> <p>Personally I'm usually about 5 minutes into a rich client when I need some feature or customization that is simply impossible through a designer such as Glade or <a href="http://www.mono-project.com/Stetic">Stetic</a>. Perhaps it's just me. Nevertheless it is still useful for me to bootstrap window design using a graphical tool.</p> <p>My recommendation: if making rich clients using GTK is going to be a significant part of your job/hobby then learn GTK as well since you <strong>will</strong> need to write that code someday.</p> <p>P.S. I personally find <a href="http://www.mono-project.com/Stetic">Stetic</a> to be superior to Glade for design work, if a little bit more unstable.</p>
19
2008-09-07T20:09:47Z
[ "python", "gtk", "pygtk", "glade", "gtk2" ]
Glade or no glade: What is the best way to use PyGtk?
48,123
<p>I've been learning python for a while now with some success. I even managed to create one or two (simple) programs using PyGtk + Glade.</p> <p>The thing is: I am not sure if the best way to use GTK with python is by building the interfaces using Glade.</p> <p>I was wondering if the more experienced ones among us (remember, I'm just a beginner) could point out the benefits and caveats of using Glade as opposed to creating everything in the code itself (assuming that learning the correct gtk bindings wouldn't exactly be a problem).</p>
27
2008-09-07T04:00:41Z
54,313
<p>Glade is very useful for creating interfaces, it means you can easily change the GUI without doing much coding. You'll find that if you want to do anything useful (e.g. build a treeview) you will have to get familiar with various parts of the GTK documentation - in practice finding a good tutorial/examples. </p>
5
2008-09-10T15:04:33Z
[ "python", "gtk", "pygtk", "glade", "gtk2" ]
Glade or no glade: What is the best way to use PyGtk?
48,123
<p>I've been learning python for a while now with some success. I even managed to create one or two (simple) programs using PyGtk + Glade.</p> <p>The thing is: I am not sure if the best way to use GTK with python is by building the interfaces using Glade.</p> <p>I was wondering if the more experienced ones among us (remember, I'm just a beginner) could point out the benefits and caveats of using Glade as opposed to creating everything in the code itself (assuming that learning the correct gtk bindings wouldn't exactly be a problem).</p>
27
2008-09-07T04:00:41Z
106,889
<p>I started out using glade, but soon moved to just doing everything in code. Glade is nice for simple things, and it's good when you're learning how GTK organizes the widgets (how things are packed, etc). Constructing everything in code, however, you have much more flexibility. Plus, you don't have the glade dependency.</p>
4
2008-09-20T03:04:01Z
[ "python", "gtk", "pygtk", "glade", "gtk2" ]
Glade or no glade: What is the best way to use PyGtk?
48,123
<p>I've been learning python for a while now with some success. I even managed to create one or two (simple) programs using PyGtk + Glade.</p> <p>The thing is: I am not sure if the best way to use GTK with python is by building the interfaces using Glade.</p> <p>I was wondering if the more experienced ones among us (remember, I'm just a beginner) could point out the benefits and caveats of using Glade as opposed to creating everything in the code itself (assuming that learning the correct gtk bindings wouldn't exactly be a problem).</p>
27
2008-09-07T04:00:41Z
107,959
<p>I usually start with Glade until I come to a point where it doesn't have the features I need, e.g. creating a wizard. As long as I'm using the standard widgets that Glade provides, there's really no reason to hand-code the GUI.</p> <p>The more comfortable I become with how Glade formats the code, the better my hand-coding becomes. Not to mention, it's real easy to use Glade to make the underlying framework so you don't have to worry about all the initializations.</p>
4
2008-09-20T11:40:16Z
[ "python", "gtk", "pygtk", "glade", "gtk2" ]
Glade or no glade: What is the best way to use PyGtk?
48,123
<p>I've been learning python for a while now with some success. I even managed to create one or two (simple) programs using PyGtk + Glade.</p> <p>The thing is: I am not sure if the best way to use GTK with python is by building the interfaces using Glade.</p> <p>I was wondering if the more experienced ones among us (remember, I'm just a beginner) could point out the benefits and caveats of using Glade as opposed to creating everything in the code itself (assuming that learning the correct gtk bindings wouldn't exactly be a problem).</p>
27
2008-09-07T04:00:41Z
199,167
<p>For quick and simple screens I use Glade. But for anything that needs finer levels of control, I create a custom classes for what I actually need (this is important, because it's too easy to get carried away with generalisations).</p> <p>With a skinny applications specific classes, I can rapidly change the look and feel application wide from a single place. Rather like using CSS to mantain consistency for web sites.</p>
1
2008-10-13T22:02:10Z
[ "python", "gtk", "pygtk", "glade", "gtk2" ]
Glade or no glade: What is the best way to use PyGtk?
48,123
<p>I've been learning python for a while now with some success. I even managed to create one or two (simple) programs using PyGtk + Glade.</p> <p>The thing is: I am not sure if the best way to use GTK with python is by building the interfaces using Glade.</p> <p>I was wondering if the more experienced ones among us (remember, I'm just a beginner) could point out the benefits and caveats of using Glade as opposed to creating everything in the code itself (assuming that learning the correct gtk bindings wouldn't exactly be a problem).</p>
27
2008-09-07T04:00:41Z
305,667
<p>I recommend using Glade for rapid development, but not for learning. Why? because some times you will need to tune up some widgets in order to work as you want they to work, and if you don't really know/understand the properties attributes of every widget then you will be in troubles.</p>
2
2008-11-20T15:33:11Z
[ "python", "gtk", "pygtk", "glade", "gtk2" ]
Glade or no glade: What is the best way to use PyGtk?
48,123
<p>I've been learning python for a while now with some success. I even managed to create one or two (simple) programs using PyGtk + Glade.</p> <p>The thing is: I am not sure if the best way to use GTK with python is by building the interfaces using Glade.</p> <p>I was wondering if the more experienced ones among us (remember, I'm just a beginner) could point out the benefits and caveats of using Glade as opposed to creating everything in the code itself (assuming that learning the correct gtk bindings wouldn't exactly be a problem).</p>
27
2008-09-07T04:00:41Z
524,614
<p>If you're writing a traditional GUI application which reuses a lot of standard components from GTK+ (buttons, labels, containers etc.) I'd personally go with Glade + Kiwi (a convenience framework for building GTK+ GUI applications). </p> <p>The single greatest advantage to using Glade is that it greatly reduces layout/packing code. Here's an extremely simply example which already shows the issues with manually laying out a GUI (without using any helper functions): </p> <pre><code>container = gtk.HBox() label = gtk.Label(str="test") container.add(label) </code></pre> <p>For more examples take a <a href="http://marcin.af.gliwice.pl/if-then-else-20071113232114" rel="nofollow">look here</a>. Even if you're writing a complicated custom widget you can always create a placeholder in Glade and replace that after instantiation. </p> <p>It shouldn't be all too long now for the Glade team to release a new version of the designer (3.6.0). This new version will add support for GtkBuilder, which replaces libglade (the actual library that transforms the Glade XML files into a widget tree). The new Glade designer also once again adds support for defining catalogs (sets of widgets) in Python, so you can easily add your own custom widgets.</p>
4
2009-02-07T21:19:04Z
[ "python", "gtk", "pygtk", "glade", "gtk2" ]
Glade or no glade: What is the best way to use PyGtk?
48,123
<p>I've been learning python for a while now with some success. I even managed to create one or two (simple) programs using PyGtk + Glade.</p> <p>The thing is: I am not sure if the best way to use GTK with python is by building the interfaces using Glade.</p> <p>I was wondering if the more experienced ones among us (remember, I'm just a beginner) could point out the benefits and caveats of using Glade as opposed to creating everything in the code itself (assuming that learning the correct gtk bindings wouldn't exactly be a problem).</p>
27
2008-09-07T04:00:41Z
751,707
<p>Personally I would recommend coding it out instead of using Glade. I'm still learning python and pyGtk but I will say that writing out the UI by hand gave me a lot of insight on how things work under the hood. </p> <p>Once you have it learned I'd say to give glade, or other UI designers a try but definitely learn how to do it the "hard" way first.</p>
1
2009-04-15T13:32:09Z
[ "python", "gtk", "pygtk", "glade", "gtk2" ]
Glade or no glade: What is the best way to use PyGtk?
48,123
<p>I've been learning python for a while now with some success. I even managed to create one or two (simple) programs using PyGtk + Glade.</p> <p>The thing is: I am not sure if the best way to use GTK with python is by building the interfaces using Glade.</p> <p>I was wondering if the more experienced ones among us (remember, I'm just a beginner) could point out the benefits and caveats of using Glade as opposed to creating everything in the code itself (assuming that learning the correct gtk bindings wouldn't exactly be a problem).</p>
27
2008-09-07T04:00:41Z
2,149,087
<p>First, start to put this in perspective.</p> <p>You will be using GTK. This is a huge C library built in 1993 using the best traditions of 1970s coding style. It was built to help implement the GIMP, a Photoshop competitor wanna-be with user interface blunders of legend. A typical gui field might have forty or more parameters, mostly repetitive, having getters and setters. There will be pain.</p> <p>The GTK itself manages a complete dynamic type system in C using GObject. This makes debugging a special joy that requires manually walking through arrays of pointers to methods full of generic argument lists with implicit inheritance. You will also be jumping through Pango libraries when you least expect it, e.g., using a Pango constant for where in a label the ellipsis go when the page is small. Expect more pain.</p> <p>By now, you are probably vowing to wrap all your GTK interactions in a Model-View-Controller architecture specific to your application. This is good.</p> <p>Using Glade, or gtkBuilder, or Stetic, will help coral the huge coupling problem of forty parameters to a function. Glade provides a basic GUI builder to drag and drop components together. The parameters and inherited parameters are somewhat separated out. The output of Glade is .glade XML file which you will then read in, attach your callbacks ("signal handlers") to identically named functions, and query or update the in-memory version of that XML to get widgets that you then use pyGTK to manipulate. Glade itself is a creaky and not well maintained. </p> <p>Using pyGTK gives you annoyingly fine grained control in order to build your GUI. This will be verbose, copy-and-paste code. Each attribute will be a separate function call. The attribute setter does not return anything, so chaining the calls is out of the question. Usually, your IDE will give only minimal help on what functions mean and you will be constantly referring to DevHelp or some other tool.</p> <p>One would almost expect GTK GUIs were meant to fail.</p>
1
2010-01-27T17:45:36Z
[ "python", "gtk", "pygtk", "glade", "gtk2" ]
Glade or no glade: What is the best way to use PyGtk?
48,123
<p>I've been learning python for a while now with some success. I even managed to create one or two (simple) programs using PyGtk + Glade.</p> <p>The thing is: I am not sure if the best way to use GTK with python is by building the interfaces using Glade.</p> <p>I was wondering if the more experienced ones among us (remember, I'm just a beginner) could point out the benefits and caveats of using Glade as opposed to creating everything in the code itself (assuming that learning the correct gtk bindings wouldn't exactly be a problem).</p>
27
2008-09-07T04:00:41Z
24,449,263
<p>You may use glade-2 to design, and use <a href="https://gist.github.com/shellexy/0ad0864b7e4e99a0a95d" rel="nofollow">glade2py.py</a> to generating the pure pygtk code, it use pygtkcompat to support gtk3</p>
-1
2014-06-27T10:09:16Z
[ "python", "gtk", "pygtk", "glade", "gtk2" ]
Embedding a remote Python shell in an application
48,176
<p>You can embed the <a href="http://ipython.scipy.org/">IPython</a> shell inside of your application so that it launches the shell in the foreground. Is there a way to embed a telnet server in a python app so that you can telnet to a certain port and launch a remote IPython shell? </p> <p>Any tips for redirecting the input/output streams for IPython or how to hook it up to a telnet server library or recommendations for other libraries that could be used to implement this are much appreciated. </p>
5
2008-09-07T05:21:42Z
48,214
<p>Python includes a <a href="http://www.python.org/doc/lib/module-telnetlib.html" rel="nofollow">telnet client</a>, but not a telnet server. You can implement a telnet server using <a href="http://twistedmatrix.com" rel="nofollow">Twisted</a>. <a href="http://twistedmatrix.com/pipermail/twisted-python/2004-August/008335.html" rel="nofollow">Here's an example</a>. As for hooking these things together, that's up to you.</p>
2
2008-09-07T06:58:49Z
[ "python", "networking" ]
Embedding a remote Python shell in an application
48,176
<p>You can embed the <a href="http://ipython.scipy.org/">IPython</a> shell inside of your application so that it launches the shell in the foreground. Is there a way to embed a telnet server in a python app so that you can telnet to a certain port and launch a remote IPython shell? </p> <p>Any tips for redirecting the input/output streams for IPython or how to hook it up to a telnet server library or recommendations for other libraries that could be used to implement this are much appreciated. </p>
5
2008-09-07T05:21:42Z
48,266
<p>I think you should base your server class on the <a href="http://www.python.org/doc/lib/module-SocketServer.html" rel="nofollow"><code>SocketServer</code></a> class from the standard library. You'll need to write a <code>RequestHandler</code> to read and echo input but a lot of the heavy lifting is already done for you.</p> <p>You can use the <a href="http://docs.python.org/lib/node632.html" rel="nofollow"><code>ThreadingMixIn</code></a> to make the server multi-threaded very easily. </p>
0
2008-09-07T09:17:40Z
[ "python", "networking" ]
Embedding a remote Python shell in an application
48,176
<p>You can embed the <a href="http://ipython.scipy.org/">IPython</a> shell inside of your application so that it launches the shell in the foreground. Is there a way to embed a telnet server in a python app so that you can telnet to a certain port and launch a remote IPython shell? </p> <p>Any tips for redirecting the input/output streams for IPython or how to hook it up to a telnet server library or recommendations for other libraries that could be used to implement this are much appreciated. </p>
5
2008-09-07T05:21:42Z
55,654
<p>Use Twisted Manhole. Docs are a bit lacking, but it's easy enough to set up a telnet-based remote server and it comes with a GTK-based GUI.</p> <ul> <li><a href="http://twistedmatrix.com/" rel="nofollow">Main Twisted site</a></li> <li><a href="http://twistedmatrix.com/documents/8.1.0/api/twisted.manhole.html" rel="nofollow">twisted.manhole API docs</a></li> </ul>
1
2008-09-11T01:39:33Z
[ "python", "networking" ]
Embedding a remote Python shell in an application
48,176
<p>You can embed the <a href="http://ipython.scipy.org/">IPython</a> shell inside of your application so that it launches the shell in the foreground. Is there a way to embed a telnet server in a python app so that you can telnet to a certain port and launch a remote IPython shell? </p> <p>Any tips for redirecting the input/output streams for IPython or how to hook it up to a telnet server library or recommendations for other libraries that could be used to implement this are much appreciated. </p>
5
2008-09-07T05:21:42Z
1,764,950
<p>Try to use xmlrpc namespace</p>
0
2009-11-19T17:10:32Z
[ "python", "networking" ]
Project structure for Google App Engine
48,458
<p>I started an application in Google App Engine right when it came out, to play with the technology and work on a pet project that I had been thinking about for a long time but never gotten around to starting. The result is <a href="http://www.bowlsk.com" rel="nofollow">BowlSK</a>. However, as it has grown, and features have been added, it has gotten really difficult to keep things organized - mainly due to the fact that this is my first python project, and I didn't know anything about it until I started working.</p> <p>What I have:</p> <ul> <li>Main Level contains: <ul> <li>all .py files (didn't know how to make packages work)</li> <li>all .html templates for main level pages</li> </ul></li> <li>Subdirectories: <ul> <li>separate folders for css, images, js, etc.</li> <li>folders that hold .html templates for subdirecty-type urls</li> </ul></li> </ul> <p>Example:<br/> <a href="http://www.bowlsk.com/" rel="nofollow">http://www.bowlsk.com/</a> maps to HomePage (default package), template at "index.html"<br/> <a href="http://www.bowlsk.com/games/view-series.html?series=7130" rel="nofollow">http://www.bowlsk.com/games/view-series.html?series=7130</a> maps to ViewSeriesPage (again, default package), template at "games/view-series.html"</p> <p>It's nasty. How do I restructure? I had 2 ideas:</p> <ul> <li><p>Main Folder containing: appdef, indexes, main.py?</p> <ul> <li>Subfolder for code. Does this have to be my first package?</li> <li>Subfolder for templates. Folder heirarchy would match package heirarchy</li> <li>Individual subfolders for css, images, js, etc.</li> </ul></li> <li><p>Main Folder containing appdef, indexes, main.py?</p> <ul> <li>Subfolder for code + templates. This way I have the handler class right next to the template, because in this stage, I'm adding lots of features, so modifications to one mean modifications to the other. Again, do I have to have this folder name be the first package name for my classes? I'd like the folder to be "src", but I don't want my classes to be "src.WhateverPage"</li> </ul></li> </ul> <p>Is there a best practice? With Django 1.0 on the horizon, is there something I can do now to improve my ability to integrate with it when it becomes the official GAE templating engine? I would simply start trying these things, and seeing which seems better, but pyDev's refactoring support doesn't seem to handle package moves very well, so it will likely be a non-trivial task to get all of this working again.</p>
112
2008-09-07T14:08:47Z
48,467
<p>I am not entirely up to date on the latest best practices, et cetera when it comes to code layout, but when I did my first GAE application, I used something along your second option, where the code and templates are next to eachother.</p> <p>There was two reasons for this - one, it kept the code and template nearby, and secondly, I had the directory structure layout mimic that of the website - making it (for me) a bit easier too remember where everything was.</p>
1
2008-09-07T14:25:20Z
[ "python", "google-app-engine" ]
Project structure for Google App Engine
48,458
<p>I started an application in Google App Engine right when it came out, to play with the technology and work on a pet project that I had been thinking about for a long time but never gotten around to starting. The result is <a href="http://www.bowlsk.com" rel="nofollow">BowlSK</a>. However, as it has grown, and features have been added, it has gotten really difficult to keep things organized - mainly due to the fact that this is my first python project, and I didn't know anything about it until I started working.</p> <p>What I have:</p> <ul> <li>Main Level contains: <ul> <li>all .py files (didn't know how to make packages work)</li> <li>all .html templates for main level pages</li> </ul></li> <li>Subdirectories: <ul> <li>separate folders for css, images, js, etc.</li> <li>folders that hold .html templates for subdirecty-type urls</li> </ul></li> </ul> <p>Example:<br/> <a href="http://www.bowlsk.com/" rel="nofollow">http://www.bowlsk.com/</a> maps to HomePage (default package), template at "index.html"<br/> <a href="http://www.bowlsk.com/games/view-series.html?series=7130" rel="nofollow">http://www.bowlsk.com/games/view-series.html?series=7130</a> maps to ViewSeriesPage (again, default package), template at "games/view-series.html"</p> <p>It's nasty. How do I restructure? I had 2 ideas:</p> <ul> <li><p>Main Folder containing: appdef, indexes, main.py?</p> <ul> <li>Subfolder for code. Does this have to be my first package?</li> <li>Subfolder for templates. Folder heirarchy would match package heirarchy</li> <li>Individual subfolders for css, images, js, etc.</li> </ul></li> <li><p>Main Folder containing appdef, indexes, main.py?</p> <ul> <li>Subfolder for code + templates. This way I have the handler class right next to the template, because in this stage, I'm adding lots of features, so modifications to one mean modifications to the other. Again, do I have to have this folder name be the first package name for my classes? I'd like the folder to be "src", but I don't want my classes to be "src.WhateverPage"</li> </ul></li> </ul> <p>Is there a best practice? With Django 1.0 on the horizon, is there something I can do now to improve my ability to integrate with it when it becomes the official GAE templating engine? I would simply start trying these things, and seeing which seems better, but pyDev's refactoring support doesn't seem to handle package moves very well, so it will likely be a non-trivial task to get all of this working again.</p>
112
2008-09-07T14:08:47Z
67,533
<p>I think the first option is considered the best practice. And make the code folder your first package. The Rietveld project developed by Guido van Rossum is a very good model to learn from. Have a look at it: <a href="http://code.google.com/p/rietveld" rel="nofollow">http://code.google.com/p/rietveld</a></p> <p>With regard to Django 1.0, I suggest you start using the Django trunk code instead of the GAE built in django port. Again, have a look at how it's done in Rietveld.</p>
5
2008-09-15T22:11:12Z
[ "python", "google-app-engine" ]
Project structure for Google App Engine
48,458
<p>I started an application in Google App Engine right when it came out, to play with the technology and work on a pet project that I had been thinking about for a long time but never gotten around to starting. The result is <a href="http://www.bowlsk.com" rel="nofollow">BowlSK</a>. However, as it has grown, and features have been added, it has gotten really difficult to keep things organized - mainly due to the fact that this is my first python project, and I didn't know anything about it until I started working.</p> <p>What I have:</p> <ul> <li>Main Level contains: <ul> <li>all .py files (didn't know how to make packages work)</li> <li>all .html templates for main level pages</li> </ul></li> <li>Subdirectories: <ul> <li>separate folders for css, images, js, etc.</li> <li>folders that hold .html templates for subdirecty-type urls</li> </ul></li> </ul> <p>Example:<br/> <a href="http://www.bowlsk.com/" rel="nofollow">http://www.bowlsk.com/</a> maps to HomePage (default package), template at "index.html"<br/> <a href="http://www.bowlsk.com/games/view-series.html?series=7130" rel="nofollow">http://www.bowlsk.com/games/view-series.html?series=7130</a> maps to ViewSeriesPage (again, default package), template at "games/view-series.html"</p> <p>It's nasty. How do I restructure? I had 2 ideas:</p> <ul> <li><p>Main Folder containing: appdef, indexes, main.py?</p> <ul> <li>Subfolder for code. Does this have to be my first package?</li> <li>Subfolder for templates. Folder heirarchy would match package heirarchy</li> <li>Individual subfolders for css, images, js, etc.</li> </ul></li> <li><p>Main Folder containing appdef, indexes, main.py?</p> <ul> <li>Subfolder for code + templates. This way I have the handler class right next to the template, because in this stage, I'm adding lots of features, so modifications to one mean modifications to the other. Again, do I have to have this folder name be the first package name for my classes? I'd like the folder to be "src", but I don't want my classes to be "src.WhateverPage"</li> </ul></li> </ul> <p>Is there a best practice? With Django 1.0 on the horizon, is there something I can do now to improve my ability to integrate with it when it becomes the official GAE templating engine? I would simply start trying these things, and seeing which seems better, but pyDev's refactoring support doesn't seem to handle package moves very well, so it will likely be a non-trivial task to get all of this working again.</p>
112
2008-09-07T14:08:47Z
70,271
<p>First, I would suggest you have a look at "<a href="http://sites.google.com/site/io/rapid-development-with-python-django-and-google-app-engine">Rapid Development with Python, Django, and Google App Engine</a>"</p> <p>GvR describes a general/standard project layout on page 10 of his <a href="http://sites.google.com/site/io/rapid-development-with-python-django-and-google-app-engine/rapid_development_with_django_gae.pdf?attredirects=0">slide presentation</a>. </p> <p>Here I'll post a slightly modified version of the layout/structure from that page. I pretty much follow this pattern myself. You also mentioned you had trouble with packages. Just make sure each of your sub folders has an __init__.py file. It's ok if its empty.</p> <h2>Boilerplate files</h2> <ul> <li>These hardly vary between projects</li> <li>app.yaml: direct all non-static requests to main.py </li> <li>main.py: initialize app and send it all requests </li> </ul> <h2>Project lay-out</h2> <ul> <li>static/*: static files; served directly by App Engine</li> <li>myapp/*.py: app-specific python code <ul> <li>views.py, models.py, tests.py, __init__.py, and more</li> </ul></li> <li>templates/*.html: templates (or myapp/templates/*.html)</li> </ul> <p>Here are some code examples that may help as well:</p> <h2>main.py</h2> <pre><code>import wsgiref.handlers from google.appengine.ext import webapp from myapp.views import * application = webapp.WSGIApplication([ ('/', IndexHandler), ('/foo', FooHandler) ], debug=True) def main(): wsgiref.handlers.CGIHandler().run(application) </code></pre> <h2>myapp/views.py</h2> <pre><code>import os import datetime import logging import time from google.appengine.api import urlfetch from google.appengine.ext.webapp import template from google.appengine.api import users from google.appengine.ext import webapp from models import * class IndexHandler(webapp.RequestHandler): def get(self): date = "foo" # Do some processing template_values = {'data': data } path = os.path.join(os.path.dirname(__file__) + '/../templates/', 'main.html') self.response.out.write(template.render(path, template_values)) class FooHandler(webapp.RequestHandler): def get(self): #logging.debug("start of handler") </code></pre> <h2>myapp/models.py</h2> <pre><code>from google.appengine.ext import db class SampleModel(db.Model): </code></pre> <p>I think this layout works great for new and relatively small to medium projects. For larger projects I would suggest breaking up the views and models to have their own sub-folders with something like:</p> <h2>Project lay-out</h2> <ul> <li>static/: static files; served directly by App Engine <ul> <li>js/*.js</li> <li>images/*.gif|png|jpg</li> <li>css/*.css</li> </ul></li> <li>myapp/: app structure <ul> <li>models/*.py</li> <li>views/*.py</li> <li>tests/*.py</li> <li>templates/*.html: templates</li> </ul></li> </ul>
96
2008-09-16T08:10:50Z
[ "python", "google-app-engine" ]
Project structure for Google App Engine
48,458
<p>I started an application in Google App Engine right when it came out, to play with the technology and work on a pet project that I had been thinking about for a long time but never gotten around to starting. The result is <a href="http://www.bowlsk.com" rel="nofollow">BowlSK</a>. However, as it has grown, and features have been added, it has gotten really difficult to keep things organized - mainly due to the fact that this is my first python project, and I didn't know anything about it until I started working.</p> <p>What I have:</p> <ul> <li>Main Level contains: <ul> <li>all .py files (didn't know how to make packages work)</li> <li>all .html templates for main level pages</li> </ul></li> <li>Subdirectories: <ul> <li>separate folders for css, images, js, etc.</li> <li>folders that hold .html templates for subdirecty-type urls</li> </ul></li> </ul> <p>Example:<br/> <a href="http://www.bowlsk.com/" rel="nofollow">http://www.bowlsk.com/</a> maps to HomePage (default package), template at "index.html"<br/> <a href="http://www.bowlsk.com/games/view-series.html?series=7130" rel="nofollow">http://www.bowlsk.com/games/view-series.html?series=7130</a> maps to ViewSeriesPage (again, default package), template at "games/view-series.html"</p> <p>It's nasty. How do I restructure? I had 2 ideas:</p> <ul> <li><p>Main Folder containing: appdef, indexes, main.py?</p> <ul> <li>Subfolder for code. Does this have to be my first package?</li> <li>Subfolder for templates. Folder heirarchy would match package heirarchy</li> <li>Individual subfolders for css, images, js, etc.</li> </ul></li> <li><p>Main Folder containing appdef, indexes, main.py?</p> <ul> <li>Subfolder for code + templates. This way I have the handler class right next to the template, because in this stage, I'm adding lots of features, so modifications to one mean modifications to the other. Again, do I have to have this folder name be the first package name for my classes? I'd like the folder to be "src", but I don't want my classes to be "src.WhateverPage"</li> </ul></li> </ul> <p>Is there a best practice? With Django 1.0 on the horizon, is there something I can do now to improve my ability to integrate with it when it becomes the official GAE templating engine? I would simply start trying these things, and seeing which seems better, but pyDev's refactoring support doesn't seem to handle package moves very well, so it will likely be a non-trivial task to get all of this working again.</p>
112
2008-09-07T14:08:47Z
153,862
<p>My usual layout looks something like this:</p> <ul> <li>app.yaml</li> <li>index.yaml</li> <li>request.py - contains the basic WSGI app</li> <li>lib <ul> <li><code>__init__.py</code> - common functionality, including a request handler base class</li> </ul></li> <li>controllers - contains all the handlers. request.yaml imports these.</li> <li>templates <ul> <li>all the django templates, used by the controllers</li> </ul></li> <li>model <ul> <li>all the datastore model classes</li> </ul></li> <li>static <ul> <li>static files (css, images, etc). Mapped to /static by app.yaml</li> </ul></li> </ul> <p>I can provide examples of what my app.yaml, request.py, lib/<strong>init</strong>.py, and sample controllers look like, if this isn't clear.</p>
14
2008-09-30T16:30:58Z
[ "python", "google-app-engine" ]
Project structure for Google App Engine
48,458
<p>I started an application in Google App Engine right when it came out, to play with the technology and work on a pet project that I had been thinking about for a long time but never gotten around to starting. The result is <a href="http://www.bowlsk.com" rel="nofollow">BowlSK</a>. However, as it has grown, and features have been added, it has gotten really difficult to keep things organized - mainly due to the fact that this is my first python project, and I didn't know anything about it until I started working.</p> <p>What I have:</p> <ul> <li>Main Level contains: <ul> <li>all .py files (didn't know how to make packages work)</li> <li>all .html templates for main level pages</li> </ul></li> <li>Subdirectories: <ul> <li>separate folders for css, images, js, etc.</li> <li>folders that hold .html templates for subdirecty-type urls</li> </ul></li> </ul> <p>Example:<br/> <a href="http://www.bowlsk.com/" rel="nofollow">http://www.bowlsk.com/</a> maps to HomePage (default package), template at "index.html"<br/> <a href="http://www.bowlsk.com/games/view-series.html?series=7130" rel="nofollow">http://www.bowlsk.com/games/view-series.html?series=7130</a> maps to ViewSeriesPage (again, default package), template at "games/view-series.html"</p> <p>It's nasty. How do I restructure? I had 2 ideas:</p> <ul> <li><p>Main Folder containing: appdef, indexes, main.py?</p> <ul> <li>Subfolder for code. Does this have to be my first package?</li> <li>Subfolder for templates. Folder heirarchy would match package heirarchy</li> <li>Individual subfolders for css, images, js, etc.</li> </ul></li> <li><p>Main Folder containing appdef, indexes, main.py?</p> <ul> <li>Subfolder for code + templates. This way I have the handler class right next to the template, because in this stage, I'm adding lots of features, so modifications to one mean modifications to the other. Again, do I have to have this folder name be the first package name for my classes? I'd like the folder to be "src", but I don't want my classes to be "src.WhateverPage"</li> </ul></li> </ul> <p>Is there a best practice? With Django 1.0 on the horizon, is there something I can do now to improve my ability to integrate with it when it becomes the official GAE templating engine? I would simply start trying these things, and seeing which seems better, but pyDev's refactoring support doesn't seem to handle package moves very well, so it will likely be a non-trivial task to get all of this working again.</p>
112
2008-09-07T14:08:47Z
3,105,295
<p>I like <a href="http://webpy.org/" rel="nofollow">webpy</a> so I've adopted it as templating framework on Google App Engine.<br> My package folders are typically organized like this:</p> <pre><code>app.yaml application.py index.yaml /app /config /controllers /db /lib /models /static /docs /images /javascripts /stylesheets test/ utility/ views/ </code></pre> <p><a href="http://github.com/systempuntoout/stackprinter" rel="nofollow">Here</a> is an example.</p>
2
2010-06-23T20:30:50Z
[ "python", "google-app-engine" ]
Project structure for Google App Engine
48,458
<p>I started an application in Google App Engine right when it came out, to play with the technology and work on a pet project that I had been thinking about for a long time but never gotten around to starting. The result is <a href="http://www.bowlsk.com" rel="nofollow">BowlSK</a>. However, as it has grown, and features have been added, it has gotten really difficult to keep things organized - mainly due to the fact that this is my first python project, and I didn't know anything about it until I started working.</p> <p>What I have:</p> <ul> <li>Main Level contains: <ul> <li>all .py files (didn't know how to make packages work)</li> <li>all .html templates for main level pages</li> </ul></li> <li>Subdirectories: <ul> <li>separate folders for css, images, js, etc.</li> <li>folders that hold .html templates for subdirecty-type urls</li> </ul></li> </ul> <p>Example:<br/> <a href="http://www.bowlsk.com/" rel="nofollow">http://www.bowlsk.com/</a> maps to HomePage (default package), template at "index.html"<br/> <a href="http://www.bowlsk.com/games/view-series.html?series=7130" rel="nofollow">http://www.bowlsk.com/games/view-series.html?series=7130</a> maps to ViewSeriesPage (again, default package), template at "games/view-series.html"</p> <p>It's nasty. How do I restructure? I had 2 ideas:</p> <ul> <li><p>Main Folder containing: appdef, indexes, main.py?</p> <ul> <li>Subfolder for code. Does this have to be my first package?</li> <li>Subfolder for templates. Folder heirarchy would match package heirarchy</li> <li>Individual subfolders for css, images, js, etc.</li> </ul></li> <li><p>Main Folder containing appdef, indexes, main.py?</p> <ul> <li>Subfolder for code + templates. This way I have the handler class right next to the template, because in this stage, I'm adding lots of features, so modifications to one mean modifications to the other. Again, do I have to have this folder name be the first package name for my classes? I'd like the folder to be "src", but I don't want my classes to be "src.WhateverPage"</li> </ul></li> </ul> <p>Is there a best practice? With Django 1.0 on the horizon, is there something I can do now to improve my ability to integrate with it when it becomes the official GAE templating engine? I would simply start trying these things, and seeing which seems better, but pyDev's refactoring support doesn't seem to handle package moves very well, so it will likely be a non-trivial task to get all of this working again.</p>
112
2008-09-07T14:08:47Z
12,535,000
<p>I implemented a google app engine boilerplate today and checked it on github. This is along the lines described by Nick Johnson above (who used to work for Google).</p> <p>Follow this link <a href="https://github.com/droot/gae-boilerplate">gae-boilerplate</a></p>
10
2012-09-21T17:07:02Z
[ "python", "google-app-engine" ]
How do I implement a pre-commit hook script in SVN that calls dos2unix to validate checked-in file
48,562
<p>I was wondering if anyone here had some experience writing this type of script and if they could give me some pointers.</p> <p>I would like to modify this <a href="http://wordaligned.org/articles/a-subversion-pre-commit-hook" rel="nofollow">script</a> to validate that the check-in file does not have a Carriage Return in the EOL formatting. The EOL format is CR LF in Windows and LF in Unix. When a User checks-in code with the Windows format. It does not compile in Unix anymore. I know this can be done on the client side but I need to have this validation done on the server side. To achieve this, I need to do the following:</p> <p>1) Make sure the file I check is not a binary, I dont know how to do this with svnlook, should I check the mime:type of the file? The <a href="http://svnbook.red-bean.com/nightly/en/svn.reposadmin.create.html" rel="nofollow">Red Book</a> does not indicate this clearly or I must have not seen it.</p> <p>2) I would like to run the <a href="http://linux.about.com/od/commands/l/blcmdl1_dos2uni.htm" rel="nofollow">dos2unix</a> command to validate that the file has the correct EOL format. I would compare the output of the dos2unix command against the original file. If there is a diff between both, I give an error message to the client and cancel the check-in.</p> <p>I would like your comments/feedback on this approach.</p>
7
2008-09-07T16:32:55Z
48,575
<p>What exactly are you trying to do?</p> <p>Of course, there are numerous places to learn about svn pre-commit hooks (e.g. <a href="http://wordaligned.org/articles/a-subversion-pre-commit-hook" rel="nofollow"> here </a>, <a href="http://www.windley.com/archives/2008/08/using_a_precommit_hook_to_check_puppet_syntax.shtml" rel="nofollow"> here</a>, and in the <a href="http://svnbook.red-bean.com/nightly/en/svn.reposadmin.create.html" rel="nofollow">Red Book</a>) but it depends what you're trying to do and what is available on your system. </p> <p>Can you be more specific? </p>
1
2008-09-07T16:48:51Z
[ "python", "svn", "dos2unix" ]
How do I implement a pre-commit hook script in SVN that calls dos2unix to validate checked-in file
48,562
<p>I was wondering if anyone here had some experience writing this type of script and if they could give me some pointers.</p> <p>I would like to modify this <a href="http://wordaligned.org/articles/a-subversion-pre-commit-hook" rel="nofollow">script</a> to validate that the check-in file does not have a Carriage Return in the EOL formatting. The EOL format is CR LF in Windows and LF in Unix. When a User checks-in code with the Windows format. It does not compile in Unix anymore. I know this can be done on the client side but I need to have this validation done on the server side. To achieve this, I need to do the following:</p> <p>1) Make sure the file I check is not a binary, I dont know how to do this with svnlook, should I check the mime:type of the file? The <a href="http://svnbook.red-bean.com/nightly/en/svn.reposadmin.create.html" rel="nofollow">Red Book</a> does not indicate this clearly or I must have not seen it.</p> <p>2) I would like to run the <a href="http://linux.about.com/od/commands/l/blcmdl1_dos2uni.htm" rel="nofollow">dos2unix</a> command to validate that the file has the correct EOL format. I would compare the output of the dos2unix command against the original file. If there is a diff between both, I give an error message to the client and cancel the check-in.</p> <p>I would like your comments/feedback on this approach.</p>
7
2008-09-07T16:32:55Z
50,507
<p>I think you can avoid a commit hook script in this case by using the <code>svn:eol-style</code> property as described in the SVNBook:</p> <ul> <li><p><a href="http://svnbook.red-bean.com/en/1.7/svn.advanced.props.file-portability.html#svn.advanced.props.special.eol-style" rel="nofollow">End-of-Line Character Sequences</a></p></li> <li><p><a href="http://svnbook.red-bean.com/en/1.7/svn.ref.properties.html" rel="nofollow">Subversion Properties</a></p></li> </ul> <p>This way SVN can worry about your line endings for you.</p> <p>Good luck!</p>
4
2008-09-08T19:45:24Z
[ "python", "svn", "dos2unix" ]
Python: No module named core.exceptions
48,777
<p>I'm trying to get Google AppEngine to work on my Debian box and am getting the following error when I try to access my page:</p> <pre><code>&lt;type 'exceptions.ImportError'&gt;: No module named core.exceptions </code></pre> <p>The same app works fine for me when I run it on my other Ubuntu box, so I know it's not a problem with the app itself. However, I need to get it working on this Debian box. It originally had python 2.4 but after AppEngine complained about it I installed the python2.5 and python2.5-dev packages (to no avail). </p> <p>I saw on this <a href="http://groups.google.com/group/google-appengine/browse_thread/thread/8f2459d2df9d735a/df2b1e9bb76f87c0?show_docid=df2b1e9bb76f87c0&amp;fwc=1" rel="nofollow">Google Group post</a> that it may be due to the version of AppEngine and just to reinstall it, but that didn't work. Any ideas?</p> <p>Edit 1: Also tried uninstalling python2.4 and 2.5 then reinstalling 2.5, which also didn't work.</p> <p>Edit 2: Turns out when I made AppEngine into a CVS project it didn't add the core directory into my project, so when I checked it out there literally was no module named core.exceptions. Re-downloading that folder resolved the problem.</p>
2
2008-09-07T20:57:16Z
48,806
<p><code>core.exceptions</code> is part of django; what version of django do you have installed? The AppEngine comes with the appropriate version for whatever release you've downloaded (in the lib/django directory). It can be installed by going to that directory and running <strong><code>python setup.py install</code></strong></p>
4
2008-09-07T21:28:54Z
[ "python", "google-app-engine" ]
Calling python from a c++ program for distribution
49,137
<p>I would like to call python script files from my c++ program. </p> <p>I am not sure that the people I will distribute to will have python installed.</p> <p>Basically I'm looking for a .lib file that I can use that has an Apache like distribution license.</p>
18
2008-09-08T03:53:39Z
49,148
<p>Boost has a python interface library which could help you.</p> <p><a href="http://www.boost.org/doc/libs/release/libs/python/doc/index.html" rel="nofollow">Boost.Python</a></p>
15
2008-09-08T04:01:10Z
[ "c++", "python", "embedded-language" ]
Calling python from a c++ program for distribution
49,137
<p>I would like to call python script files from my c++ program. </p> <p>I am not sure that the people I will distribute to will have python installed.</p> <p>Basically I'm looking for a .lib file that I can use that has an Apache like distribution license.</p>
18
2008-09-08T03:53:39Z
49,319
<p>Embeding the Python interpreter inside your C++ app will let you run Python programs using your application run Python scripts. It will also make it easier possible for those scripts to call C++ functions in your application. If this is what you want then the Boost library mentioned previously may be what you want to make it easier to create the link. In the past I have used <a href="http://www.swig.org/" rel="nofollow">SWIG</a> to generate Python interfaces to C++ code. It was not clear from your question whether you wanted the Python scripts to call your C++ program or whether you just wanted the C++ to call Python.</p> <p>Many of the Python functions use modules which are not built into the Python interpreter. If your Python scripts call these functions then you will either need to have your users install Python or include the python runtime files with your application. It will depend on what modules you import in you Python scripts.</p>
1
2008-09-08T08:36:45Z
[ "c++", "python", "embedded-language" ]
Calling python from a c++ program for distribution
49,137
<p>I would like to call python script files from my c++ program. </p> <p>I am not sure that the people I will distribute to will have python installed.</p> <p>Basically I'm looking for a .lib file that I can use that has an Apache like distribution license.</p>
18
2008-09-08T03:53:39Z
49,439
<p>Boost is probably the best choice, however if you're wanting something that's more standalone, and if this is for use with Windows (which seems feasible given that they are the people least likely to have Python installed), then you can use <a href="http://www.py2exe.org" rel="nofollow">py2exe</a> to create a DLL with entry points suitable for COM objects. You can then interface with the library via COM. (Obviously this is not at all useful as a cross-platform solution).</p>
1
2008-09-08T10:37:53Z
[ "c++", "python", "embedded-language" ]
Calling python from a c++ program for distribution
49,137
<p>I would like to call python script files from my c++ program. </p> <p>I am not sure that the people I will distribute to will have python installed.</p> <p>Basically I'm looking for a .lib file that I can use that has an Apache like distribution license.</p>
18
2008-09-08T03:53:39Z
328,451
<blockquote> <p>I would like to call python script files from my c++ program.</p> </blockquote> <p>This means that you want to embed Python in your C++ application. As mentioned in <a href="http://docs.python.org/extending/embedding.html">Embedding Python in Another Application</a>:</p> <blockquote> <p>Embedding Python is similar to extending it, but not quite. The difference is that when you extend Python, the main program of the application is still the Python interpreter, while if you embed Python, the main program may have nothing to do with Python — instead, some parts of the application occasionally call the Python interpreter to run some Python code.</p> </blockquote> <p>I suggest that you first go through <a href="http://docs.python.org/extending/embedding.html">Embedding Python in Another Application</a>. Then refer the following examples</p> <ol> <li><p><a href="http://www.codeproject.com/KB/cpp/embedpython_1.aspx">Embedding Python in C/C++: Part I</a></p></li> <li><p><a href="http://www.codeproject.com/KB/cpp/embedpython_2.aspx">Embedding Python in C/C++: Part II</a></p></li> <li><p><a href="http://www.linuxjournal.com/article/3641">Embedding Python in Multi-Threaded C/C++ Applications</a></p></li> </ol> <p>If you like <a href="http://www.boost.org/doc/libs/release/libs/python/doc/tutorial/doc/html/python/embedding.html">Boost.Python</a>, you may visit the following links:</p> <ol> <li><a href="http://members.gamedev.net/sicrane/articles/EmbeddingPythonPart1.html">Embedding Python with Boost.Python Part 1</a></li> </ol>
32
2008-11-30T04:52:03Z
[ "c++", "python", "embedded-language" ]
How do I turn a python program into an .egg file?
49,164
<p>How do I turn a python program into an .egg file?</p>
13
2008-09-08T04:21:22Z
49,169
<p><a href="http://peak.telecommunity.com/DevCenter/setuptools">Setuptools</a> is the software that creates <a href="http://peak.telecommunity.com/DevCenter/PythonEggs">.egg files</a>. It's an extension of the <a href="http://docs.python.org/lib/module-distutils.html"><code>distutils</code></a> package in the standard library.</p> <p>The process involves creating a <code>setup.py</code> file, then <code>python setup.py bdist_egg</code> creates an .egg package.</p>
9
2008-09-08T04:33:39Z
[ "python", "deployment", "egg" ]
How do I turn a python program into an .egg file?
49,164
<p>How do I turn a python program into an .egg file?</p>
13
2008-09-08T04:21:22Z
49,175
<p>Also, if you need to get an .egg package off a single .py file app, check this link: <a href="http://peak.telecommunity.com/DevCenter/EasyInstall#packaging-others-projects-as-eggs" rel="nofollow">EasyInstall - Packaging others projects as eggs</a>.</p>
3
2008-09-08T04:47:44Z
[ "python", "deployment", "egg" ]
Can parallel traversals be done in MATLAB just as in Python?
49,307
<p>Using the <code>zip</code> function, Python allows for loops to traverse multiple sequences in parallel. </p> <p><code>for (x,y) in zip(List1, List2):</code></p> <p>Does MATLAB have an equivalent syntax? If not, what is the best way to iterate over two parallel arrays at the same time using MATLAB?</p>
7
2008-09-08T08:25:55Z
49,514
<p>If I'm not mistaken the zip function you use in python <a href="http://groups.google.com/group/comp.lang.python/browse_thread/thread/195e57735ff6ee56">creates a pair of the items found in list1 and list2</a>. Basically it still is a for loop with the addition that it will retrieve the data from the two seperate lists for you, instead that you have to do it yourself.</p> <p>So maybe your best option is to use a <em>standard</em> for loop like this:</p> <pre><code>for i=1:length(a) c(i) = a(i) + b(i); end </code></pre> <p>or whatever you have to do with the data.</p> <p>If you really are talking about parallel computing then you should take a look at the <a href="http://www.mathworks.com/products/parallel-computing/">Parallel Computing Toolbox</a> for matlab, and more specifically at <a href="http://www.mathworks.com/access/helpdesk/help/toolbox/distcomp/index.html?/access/helpdesk/help/toolbox/distcomp/brb2x2l-1.html">parfor</a></p>
5
2008-09-08T11:34:08Z
[ "python", "arrays", "matlab", "for-loop" ]
Can parallel traversals be done in MATLAB just as in Python?
49,307
<p>Using the <code>zip</code> function, Python allows for loops to traverse multiple sequences in parallel. </p> <p><code>for (x,y) in zip(List1, List2):</code></p> <p>Does MATLAB have an equivalent syntax? If not, what is the best way to iterate over two parallel arrays at the same time using MATLAB?</p>
7
2008-09-08T08:25:55Z
51,137
<p>Tested only in octave... (no matlab license). Variations of arrayfun() exist, check the documentation.</p> <pre><code>#!/usr/bin/octave -qf function result = dostuff(my_ten, my_one) result = my_ten + my_one endfunction tens = [ 10 20 30 ]; ones = [ 1 2 3]; x = arrayfun(@dostuff, tens, ones); x </code></pre> <p>Yields...</p> <pre><code>x = 11 22 33 </code></pre>
3
2008-09-09T02:32:46Z
[ "python", "arrays", "matlab", "for-loop" ]
Can parallel traversals be done in MATLAB just as in Python?
49,307
<p>Using the <code>zip</code> function, Python allows for loops to traverse multiple sequences in parallel. </p> <p><code>for (x,y) in zip(List1, List2):</code></p> <p>Does MATLAB have an equivalent syntax? If not, what is the best way to iterate over two parallel arrays at the same time using MATLAB?</p>
7
2008-09-08T08:25:55Z
65,903
<p>If x and y are column vectors, you can do:</p> <pre><code>for i=[x';y'] # do stuff with i(1) and i(2) end </code></pre> <p>(with row vectors, just use <code>x</code> and <code>y</code>).</p> <p>Here is an example run:</p> <pre class="lang-matlab prettyprint-override"><code>&gt;&gt; x=[1 ; 2; 3;] x = 1 2 3 &gt;&gt; y=[10 ; 20; 30;] y = 10 20 30 &gt;&gt; for i=[x';y'] disp(['size of i = ' num2str(size(i)) ', i(1) = ' num2str(i(1)) ', i(2) = ' num2str(i(2))]) end size of i = 2 1, i(1) = 1, i(2) = 10 size of i = 2 1, i(1) = 2, i(2) = 20 size of i = 2 1, i(1) = 3, i(2) = 30 &gt;&gt; </code></pre>
12
2008-09-15T19:20:15Z
[ "python", "arrays", "matlab", "for-loop" ]
Can parallel traversals be done in MATLAB just as in Python?
49,307
<p>Using the <code>zip</code> function, Python allows for loops to traverse multiple sequences in parallel. </p> <p><code>for (x,y) in zip(List1, List2):</code></p> <p>Does MATLAB have an equivalent syntax? If not, what is the best way to iterate over two parallel arrays at the same time using MATLAB?</p>
7
2008-09-08T08:25:55Z
80,737
<p>I second mattiast's answer.</p> <p>But, to dig a little deeper, is there no way to vectorize what you're trying to accomplish and avoid the iterative for loop? Perhaps with more details about what goes on inside the loop we could help vectorize the solution...</p>
1
2008-09-17T07:15:12Z
[ "python", "arrays", "matlab", "for-loop" ]
Can parallel traversals be done in MATLAB just as in Python?
49,307
<p>Using the <code>zip</code> function, Python allows for loops to traverse multiple sequences in parallel. </p> <p><code>for (x,y) in zip(List1, List2):</code></p> <p>Does MATLAB have an equivalent syntax? If not, what is the best way to iterate over two parallel arrays at the same time using MATLAB?</p>
7
2008-09-08T08:25:55Z
138,886
<p>for loops in MATLAB used to be slow, but this is not true anymore.</p> <p>So Vectorizing is not always the miracle solution. just use the profiler, and tic and toc functions to help you identify possible bottlenecks</p>
1
2008-09-26T11:31:27Z
[ "python", "arrays", "matlab", "for-loop" ]
Can parallel traversals be done in MATLAB just as in Python?
49,307
<p>Using the <code>zip</code> function, Python allows for loops to traverse multiple sequences in parallel. </p> <p><code>for (x,y) in zip(List1, List2):</code></p> <p>Does MATLAB have an equivalent syntax? If not, what is the best way to iterate over two parallel arrays at the same time using MATLAB?</p>
7
2008-09-08T08:25:55Z
218,618
<p>I would recommend to join the two arrays for the computation:</p> <pre><code>% assuming you have column vectors a and b x = [a b]; for i = 1:length(a) % do stuff with one row... x(i,:); end </code></pre> <p>This will work great if your functions can work with vectors. Then again, many functions can even work with matrices, so you wouldn't even need the loop.</p>
1
2008-10-20T14:22:59Z
[ "python", "arrays", "matlab", "for-loop" ]
How does one decrypt a PDF with an owner password, but no user password?
49,455
<p>Although the <a href="http://www.adobe.com/devnet/pdf/pdf_reference.html" rel="nofollow">PDF specification</a> is available from Adobe, it's not exactly the simplest document to read through. PDF allows documents to be encrypted so that either a user password and/or an owner password is required to do various things with the document (display, print, etc). A common use is to lock a PDF so that end users can read it without entering any password, but a password is required to do anything else.</p> <p>I'm trying to parse PDFs that are locked in this way (to get the same privileges as you would get opening them in any reader). Using an empty string as the user password doesn't work, but it seems (section 3.5.2 of the spec) that there has to be a user password to create the hash for the admin password.</p> <p>What I would like is either an explanation of how to do this, or any code that I can read (ideally Python, C, or C++, but anything readable will do) that does this so that I can understand what I'm meant to be doing. Standalone code, rather than reading through (e.g.) the gsview source, would be best.</p>
1
2008-09-08T10:55:13Z
49,485
<p>A plugin for GSview for viewing encrypted PDFs is <a href="http://www.cs.cmu.edu/~dst/Adobe/Gallery/Keating/" rel="nofollow">here</a>.</p> <p>If this works for you, you may be able to look at the source.</p>
1
2008-09-08T11:12:56Z
[ "c++", "python", "pdf", "passwords", "encryption" ]
How does one decrypt a PDF with an owner password, but no user password?
49,455
<p>Although the <a href="http://www.adobe.com/devnet/pdf/pdf_reference.html" rel="nofollow">PDF specification</a> is available from Adobe, it's not exactly the simplest document to read through. PDF allows documents to be encrypted so that either a user password and/or an owner password is required to do various things with the document (display, print, etc). A common use is to lock a PDF so that end users can read it without entering any password, but a password is required to do anything else.</p> <p>I'm trying to parse PDFs that are locked in this way (to get the same privileges as you would get opening them in any reader). Using an empty string as the user password doesn't work, but it seems (section 3.5.2 of the spec) that there has to be a user password to create the hash for the admin password.</p> <p>What I would like is either an explanation of how to do this, or any code that I can read (ideally Python, C, or C++, but anything readable will do) that does this so that I can understand what I'm meant to be doing. Standalone code, rather than reading through (e.g.) the gsview source, would be best.</p>
1
2008-09-08T10:55:13Z
107,838
<p>If I remember correctly, there is a fixed padding string of 32 (?) bytes to apply to any password. All passwords need to be 32 bytes at the start of computing the encryption key, either by truncating or adding some of those padding bytes.</p> <p>If no user password was set you simply have to pad with all 32 bytes of the string, i.e. use the 32 padding bytes as the starting point for computing the encryption key.</p> <p>I have to admit it's been a while since I've done this, I do remember that the encryption part of the PDF is an absolute mess as it got changed significantly in nearly every revision, requiring you to cope with a lot of cases to handle all PDF's.</p> <p>Good luck.</p>
1
2008-09-20T10:27:58Z
[ "c++", "python", "pdf", "passwords", "encryption" ]
How does one decrypt a PDF with an owner password, but no user password?
49,455
<p>Although the <a href="http://www.adobe.com/devnet/pdf/pdf_reference.html" rel="nofollow">PDF specification</a> is available from Adobe, it's not exactly the simplest document to read through. PDF allows documents to be encrypted so that either a user password and/or an owner password is required to do various things with the document (display, print, etc). A common use is to lock a PDF so that end users can read it without entering any password, but a password is required to do anything else.</p> <p>I'm trying to parse PDFs that are locked in this way (to get the same privileges as you would get opening them in any reader). Using an empty string as the user password doesn't work, but it seems (section 3.5.2 of the spec) that there has to be a user password to create the hash for the admin password.</p> <p>What I would like is either an explanation of how to do this, or any code that I can read (ideally Python, C, or C++, but anything readable will do) that does this so that I can understand what I'm meant to be doing. Standalone code, rather than reading through (e.g.) the gsview source, would be best.</p>
1
2008-09-08T10:55:13Z
110,110
<p>xpdf is probably a good reference implementation for this sort of problem. I have successfully used them to open encrypted pdfs before.</p>
0
2008-09-21T03:04:42Z
[ "c++", "python", "pdf", "passwords", "encryption" ]
Java -> Python?
49,824
<p>Besides the dynamic nature of Python (and the syntax), what are some of the major features of the Python language that Java doesn't have, and vice versa?</p>
23
2008-09-08T14:36:24Z
49,828
<p>I think this pair of articles by Philip J. Eby does a great job discussing the differences between the two languages (mostly about philosophy/mentality rather than specific language features). </p> <ul> <li><a href="http://dirtsimple.org/2004/12/python-is-not-java.html">Python is Not Java</a></li> <li><a href="http://dirtsimple.org/2004/12/java-is-not-python-either.html">Java is Not Python, either</a></li> </ul>
15
2008-09-08T14:40:36Z
[ "java", "python" ]
Java -> Python?
49,824
<p>Besides the dynamic nature of Python (and the syntax), what are some of the major features of the Python language that Java doesn't have, and vice versa?</p>
23
2008-09-08T14:36:24Z
49,837
<p>One key difference in Python is <a href="http://weblog.hotales.org/cgi-bin/weblog/nb.cgi/view/python/2005/02/19/1" rel="nofollow">significant whitespace</a>. This puts a lot of people off - me too for a long time - but once you get going it seems natural and makes much more sense than <code>;</code>s everywhere.</p> <p>From a personal perspective, Python has the following benefits over Java:</p> <ul> <li>No <a href="http://en.wikipedia.org/wiki/Exception_handling#Checked_exceptions" rel="nofollow">Checked Exceptions</a></li> <li>Optional Arguments</li> <li>Much less boilerplate and less verbose generally</li> </ul> <p>Other than those, <a href="http://wiki.python.org/moin/LanguageComparisons" rel="nofollow">this page on the Python Wiki</a> is a good place to look with lots of links to interesting articles.</p>
4
2008-09-08T14:43:09Z
[ "java", "python" ]
Java -> Python?
49,824
<p>Besides the dynamic nature of Python (and the syntax), what are some of the major features of the Python language that Java doesn't have, and vice versa?</p>
23
2008-09-08T14:36:24Z
49,911
<p>With <a href="http://www.jython.org/Project/" rel="nofollow">Jython</a> you can have both. It's only at Python 2.2, but still very useful if you need an embedded interpreter that has access to the Java runtime.</p>
3
2008-09-08T15:13:58Z
[ "java", "python" ]
Java -> Python?
49,824
<p>Besides the dynamic nature of Python (and the syntax), what are some of the major features of the Python language that Java doesn't have, and vice versa?</p>
23
2008-09-08T14:36:24Z
49,953
<ol> <li><p>List comprehensions. I often find myself filtering/mapping lists, and being able to say <code>[line.replace("spam","eggs") for line in open("somefile.txt") if line.startswith("nee")]</code> is really nice.</p></li> <li><p>Functions are first class objects. They can be passed as parameters to other functions, defined inside other function, and have lexical scope. This makes it really easy to say things like <code>people.sort(key=lambda p: p.age)</code> and thus sort a bunch of people on their age without having to define a custom comparator class or something equally verbose.</p></li> <li><p>Everything is an object. Java has basic types which aren't objects, which is why many classes in the standard library define 9 different versions of functions (for boolean, byte, char, double, float, int, long, Object, short). <code>Array.sort</code> is a good example. Autoboxing helps, although it makes things awkward when something turns out to be null.</p></li> <li><p>Properties. Python lets you create classes with read-only fields, lazily-generated fields, as well as fields which are checked upon assignment to make sure they're never 0 or null or whatever you want to guard against, etc.'</p></li> <li><p>Default and keyword arguments. In Java if you want a constructor that can take up to 5 optional arguments, you must define 6 different versions of that constructor. And there's no way at all to say <code>Student(name="Eli", age=25)</code></p></li> <li><p>Functions can only return 1 thing. In Python you have tuple assignment, so you can say <code>spam, eggs = nee()</code> but in Java you'd need to either resort to mutable out parameters or have a custom class with 2 fields and then have two additional lines of code to extract those fields.</p></li> <li><p>Built-in syntax for lists and dictionaries.</p></li> <li><p>Operator Overloading.</p></li> <li><p>Generally better designed libraries. For example, to parse an XML document in Java, you say<br /> <code>Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse("test.xml");</code><br /> and in Python you say<br /> <code>doc = parse("test.xml")</code></p></li> </ol> <p>Anyway, I could go on and on with further examples, but Python is just overall a much more flexible and expressive language. It's also dynamically typed, which I really like, but which comes with some disadvantages.</p> <p>Java has much better performance than Python and has way better tool support. Sometimes those things matter a lot and Java is the better language than Python for a task; I continue to use Java for some new projects despite liking Python a lot more. But as a language I think Python is superior for most things I find myself needing to accomplish.</p>
40
2008-09-08T15:35:32Z
[ "java", "python" ]
Java -> Python?
49,824
<p>Besides the dynamic nature of Python (and the syntax), what are some of the major features of the Python language that Java doesn't have, and vice versa?</p>
23
2008-09-08T14:36:24Z
51,512
<p>Apart from what Eli Courtwright said:</p> <ul> <li>I find iterators in Python more concise. You can use <em>for i in something</em>, and it works with pretty much everything. Yeah, Java has gotten better since 1.5, but for example you can iterate through a string in python with this same construct.</li> <li>Introspection: In python you can get at runtime information about an object or a module about its symbols, methods, or even its docstrings. You can also instantiate them dynamically. Java has some of this, but usually in Java it takes half a page of code to get an instance of a class, whereas in Python it is about 3 lines. And as far as I know the docstrings thing is not available in Java</li> </ul>
2
2008-09-09T10:11:54Z
[ "java", "python" ]
Open source alternative to MATLAB's fmincon function?
49,926
<p>Is there an open-source alternative to MATLAB's <a href="http://www.mathworks.com/access/helpdesk/help/toolbox/optim/index.html?/access/helpdesk/help/toolbox/optim/ug/fmincon.html"><code>fmincon</code></a> function for constrained linear optimization? I'm rewriting a MATLAB program to use Python / <a href="http://numpy.scipy.org/">NumPy</a> / <a href="http://www.scipy.org/">SciPy</a> and this is the only function I haven't found an equivalent to. A NumPy-based solution would be ideal, but any language will do.</p>
22
2008-09-08T15:19:59Z
49,929
<p>There is a program called <a href="http://www.scilab.org/" rel="nofollow">SciLab</a> that is a MATLAB clone.</p> <p>I haven't used it at all, but it is open source and might have the function you are looking for.</p>
0
2008-09-08T15:21:43Z
[ "python", "matlab", "numpy", "numerical", "scientific-computing" ]
Open source alternative to MATLAB's fmincon function?
49,926
<p>Is there an open-source alternative to MATLAB's <a href="http://www.mathworks.com/access/helpdesk/help/toolbox/optim/index.html?/access/helpdesk/help/toolbox/optim/ug/fmincon.html"><code>fmincon</code></a> function for constrained linear optimization? I'm rewriting a MATLAB program to use Python / <a href="http://numpy.scipy.org/">NumPy</a> / <a href="http://www.scipy.org/">SciPy</a> and this is the only function I haven't found an equivalent to. A NumPy-based solution would be ideal, but any language will do.</p>
22
2008-09-08T15:19:59Z
49,930
<p><a href="http://www.gnu.org/software/octave/" rel="nofollow">GNU Octave</a> is another MATLAB clone that might have what you need.</p>
3
2008-09-08T15:22:49Z
[ "python", "matlab", "numpy", "numerical", "scientific-computing" ]
Open source alternative to MATLAB's fmincon function?
49,926
<p>Is there an open-source alternative to MATLAB's <a href="http://www.mathworks.com/access/helpdesk/help/toolbox/optim/index.html?/access/helpdesk/help/toolbox/optim/ug/fmincon.html"><code>fmincon</code></a> function for constrained linear optimization? I'm rewriting a MATLAB program to use Python / <a href="http://numpy.scipy.org/">NumPy</a> / <a href="http://www.scipy.org/">SciPy</a> and this is the only function I haven't found an equivalent to. A NumPy-based solution would be ideal, but any language will do.</p>
22
2008-09-08T15:19:59Z
50,041
<p>I don't know if it's in there, but there's a python distribution called <a href="http://www.enthought.com/" rel="nofollow">Enthought</a> that might have what you're looking for. It was designed specifically for data analysis has over 60 additional libraries.</p>
0
2008-09-08T16:02:04Z
[ "python", "matlab", "numpy", "numerical", "scientific-computing" ]
Open source alternative to MATLAB's fmincon function?
49,926
<p>Is there an open-source alternative to MATLAB's <a href="http://www.mathworks.com/access/helpdesk/help/toolbox/optim/index.html?/access/helpdesk/help/toolbox/optim/ug/fmincon.html"><code>fmincon</code></a> function for constrained linear optimization? I'm rewriting a MATLAB program to use Python / <a href="http://numpy.scipy.org/">NumPy</a> / <a href="http://www.scipy.org/">SciPy</a> and this is the only function I haven't found an equivalent to. A NumPy-based solution would be ideal, but any language will do.</p>
22
2008-09-08T15:19:59Z
70,798
<p>The open source Python package,<a href="http://www.scipy.org/">SciPy</a>, has quite a large set of optimization routines including some for multivariable problems with constraints (which is what fmincon does I believe). Once you have SciPy installed type the following at the Python command prompt</p> <p>help(scipy.optimize)</p> <p>The resulting document is extensive and includes the following which I believe might be of use to you.</p> <pre><code> Constrained Optimizers (multivariate) fmin_l_bfgs_b -- Zhu, Byrd, and Nocedal's L-BFGS-B constrained optimizer (if you use this please quote their papers -- see help) fmin_tnc -- Truncated Newton Code originally written by Stephen Nash and adapted to C by Jean-Sebastien Roy. fmin_cobyla -- Constrained Optimization BY Linear Approximation </code></pre>
13
2008-09-16T09:45:06Z
[ "python", "matlab", "numpy", "numerical", "scientific-computing" ]
Open source alternative to MATLAB's fmincon function?
49,926
<p>Is there an open-source alternative to MATLAB's <a href="http://www.mathworks.com/access/helpdesk/help/toolbox/optim/index.html?/access/helpdesk/help/toolbox/optim/ug/fmincon.html"><code>fmincon</code></a> function for constrained linear optimization? I'm rewriting a MATLAB program to use Python / <a href="http://numpy.scipy.org/">NumPy</a> / <a href="http://www.scipy.org/">SciPy</a> and this is the only function I haven't found an equivalent to. A NumPy-based solution would be ideal, but any language will do.</p>
22
2008-09-08T15:19:59Z
196,806
<p>Is your problem convex? Linear? Non-linear? I agree that SciPy.optimize will probably do the job, but fmincon is a sort of bazooka for solving optimization problems, and you'll be better off if you can confine it to one of the categories below (in increasing level of difficulty to solve efficiently)</p> <p>Linear Program (LP) Quadratic Program (QP) Convex Quadratically-Constrained Quadratic Program (QCQP) Second Order Cone Program (SOCP) Semidefinite Program (SDP) Non-Linear Convex Problem Non-Convex Problem</p> <p>There are also combinatoric problems such as Mixed-Integer Linear Programs (MILP), but you didn't mention any sort of integrality constraints, suffice to say that they fall into a different class of problems.</p> <p>The CVXOpt package will be of great use to you if your problem is convex. </p> <p>If your problem is not convex, you need to choose between finding a local solution or the global solution. Many convex solvers 'sort of' work in a non-convex domain. Finding a good approximation to the global solution would require some form Simulated Annealing or Genetic Algorithm. Finding the global solution will require an enumeration of all local solutions or a combinatorial strategy such as Branch and Bound.</p>
22
2008-10-13T05:51:51Z
[ "python", "matlab", "numpy", "numerical", "scientific-computing" ]
Open source alternative to MATLAB's fmincon function?
49,926
<p>Is there an open-source alternative to MATLAB's <a href="http://www.mathworks.com/access/helpdesk/help/toolbox/optim/index.html?/access/helpdesk/help/toolbox/optim/ug/fmincon.html"><code>fmincon</code></a> function for constrained linear optimization? I'm rewriting a MATLAB program to use Python / <a href="http://numpy.scipy.org/">NumPy</a> / <a href="http://www.scipy.org/">SciPy</a> and this is the only function I haven't found an equivalent to. A NumPy-based solution would be ideal, but any language will do.</p>
22
2008-09-08T15:19:59Z
444,167
<p>Have a look at <a href="http://www.aemdesign.com/downloadfsqp.htm" rel="nofollow">http://www.aemdesign.com/downloadfsqp.htm</a>.</p> <p>There you will find C code which provides the same functionality as <code>fmincon</code>. (However, using a different algorithm. You can read the manual if you are interested in the details.)</p> <p>It's open source but not under GPL. </p>
1
2009-01-14T18:38:44Z
[ "python", "matlab", "numpy", "numerical", "scientific-computing" ]
Open source alternative to MATLAB's fmincon function?
49,926
<p>Is there an open-source alternative to MATLAB's <a href="http://www.mathworks.com/access/helpdesk/help/toolbox/optim/index.html?/access/helpdesk/help/toolbox/optim/ug/fmincon.html"><code>fmincon</code></a> function for constrained linear optimization? I'm rewriting a MATLAB program to use Python / <a href="http://numpy.scipy.org/">NumPy</a> / <a href="http://www.scipy.org/">SciPy</a> and this is the only function I haven't found an equivalent to. A NumPy-based solution would be ideal, but any language will do.</p>
22
2008-09-08T15:19:59Z
765,053
<p>For numerical optimization in Python you may take a look at OpenOpt solvers:</p> <p><a href="http://openopt.org/NLP" rel="nofollow">http://openopt.org/NLP</a></p> <p><a href="http://openopt.org/Problems" rel="nofollow">http://openopt.org/Problems</a></p>
3
2009-04-19T08:10:36Z
[ "python", "matlab", "numpy", "numerical", "scientific-computing" ]
Open source alternative to MATLAB's fmincon function?
49,926
<p>Is there an open-source alternative to MATLAB's <a href="http://www.mathworks.com/access/helpdesk/help/toolbox/optim/index.html?/access/helpdesk/help/toolbox/optim/ug/fmincon.html"><code>fmincon</code></a> function for constrained linear optimization? I'm rewriting a MATLAB program to use Python / <a href="http://numpy.scipy.org/">NumPy</a> / <a href="http://www.scipy.org/">SciPy</a> and this is the only function I haven't found an equivalent to. A NumPy-based solution would be ideal, but any language will do.</p>
22
2008-09-08T15:19:59Z
1,856,211
<p>Python optimization software:</p> <ul> <li><p><strong>OpenOpt</strong> <a href="http://openopt.org" rel="nofollow">http://openopt.org</a> <strong>(this one is numpy-based as you wish, with automatic differentiation by FuncDesigner)</strong></p></li> <li><p><strong>Pyomo</strong> <a href="https://software.sandia.gov/trac/coopr/wiki/Package/pyomo" rel="nofollow">https://software.sandia.gov/trac/coopr/wiki/Package/pyomo</a></p></li> <li><p><strong>CVXOPT</strong> <a href="http://abel.ee.ucla.edu/cvxopt/" rel="nofollow">http://abel.ee.ucla.edu/cvxopt/</a></p></li> <li><p><strong>NLPy</strong> <a href="http://nlpy.sourceforge.net/" rel="nofollow">http://nlpy.sourceforge.net/</a></p></li> </ul>
12
2009-12-06T18:51:50Z
[ "python", "matlab", "numpy", "numerical", "scientific-computing" ]
What Python way would you suggest to check whois database records?
50,394
<p>I'm trying to get a webservice up and running that actually requires to check whois databases. What I'm doing right now is ugly and I'd like to avoid it as much as I can: I call gwhois command and parse its output. Ugly.</p> <p>I did some search to try to find a pythonic way to do this task. Generally I got quite much nothing - <a href="http://mail.python.org/pipermail/python-list/2000-March/028122.html">this old discussion list link</a> has a way to check if domain exist. Quite not what I was looking for... But still, it was best anwser Google gave me - everything else is just a bunch of unanwsered questions.</p> <p>Any of you have succeeded to get some method up and running? I'd very much appreciate some tips, or should I just do it the opensource-way, sit down and code something by myself? :) </p>
7
2008-09-08T18:43:52Z
50,413
<p>Another way to do it is to use <code>urllib2</code> module to parse some other page's whois service (many sites like that exist). But that seems like even more of a hack that what you do now, and would give you a dependency on whatever whois site you chose, which is bad.</p> <p>I hate to say it, but unless you want to re-implement <code>whois</code> in your program (which would be re-inventing the wheel), running <code>whois</code> on the OS and parsing the output (ie what you are doing now) seems like the right way to do it.</p>
0
2008-09-08T18:53:37Z
[ "python", "sysadmin", "whois" ]
What Python way would you suggest to check whois database records?
50,394
<p>I'm trying to get a webservice up and running that actually requires to check whois databases. What I'm doing right now is ugly and I'd like to avoid it as much as I can: I call gwhois command and parse its output. Ugly.</p> <p>I did some search to try to find a pythonic way to do this task. Generally I got quite much nothing - <a href="http://mail.python.org/pipermail/python-list/2000-March/028122.html">this old discussion list link</a> has a way to check if domain exist. Quite not what I was looking for... But still, it was best anwser Google gave me - everything else is just a bunch of unanwsered questions.</p> <p>Any of you have succeeded to get some method up and running? I'd very much appreciate some tips, or should I just do it the opensource-way, sit down and code something by myself? :) </p>
7
2008-09-08T18:43:52Z
50,423
<p>Parsing another webpage woulnd't be as bad (assuming their html woulnd't be very bad), but it would actually tie me to them - if they're down, I'm down :) </p> <p>Actually I found some old project on sourceforge: <a href="http://sourceforge.net/projects/rwhois/" rel="nofollow">rwhois.py</a>. What scares me a bit is that their last update is from 2003. But, it might seem as a good place to start reimplementation of what I do right now... Well, I felt obligued to post the link to this project anyway, just for further reference.</p>
0
2008-09-08T19:00:58Z
[ "python", "sysadmin", "whois" ]
What Python way would you suggest to check whois database records?
50,394
<p>I'm trying to get a webservice up and running that actually requires to check whois databases. What I'm doing right now is ugly and I'd like to avoid it as much as I can: I call gwhois command and parse its output. Ugly.</p> <p>I did some search to try to find a pythonic way to do this task. Generally I got quite much nothing - <a href="http://mail.python.org/pipermail/python-list/2000-March/028122.html">this old discussion list link</a> has a way to check if domain exist. Quite not what I was looking for... But still, it was best anwser Google gave me - everything else is just a bunch of unanwsered questions.</p> <p>Any of you have succeeded to get some method up and running? I'd very much appreciate some tips, or should I just do it the opensource-way, sit down and code something by myself? :) </p>
7
2008-09-08T18:43:52Z
55,385
<p>There's nothing wrong with using a command line utility to do what you want. If you put a nice wrapper around the service, you can implement the internals however you want! For example:</p> <pre><code>class Whois(object): _whois_by_query_cache = {} def __init__(self, query): """Initializes the instance variables to defaults. See :meth:`lookup` for details on how to submit the query.""" self.query = query self.domain = None # ... other fields. def lookup(self): """Submits the `whois` query and stores results internally.""" # ... implementation </code></pre> <p>Now, whether or not you roll your own using urllib, wrap around a command line utility (like you're doing), or import a third party library and use that (like <a href="http://stackoverflow.com/questions/50394#50423" rel="nofollow">you're saying</a>), this interface stays the same.</p> <p>This approach is generally not considered ugly at all -- <strong>sometimes command utilities do what you want and you should be able to leverage them</strong>. If speed ends up being a bottleneck, your abstraction makes the process of switching to a native Python implementation transparent to your client code.</p> <p><a href="http://www.python.org/dev/peps/pep-0020/" rel="nofollow">Practicality beats purity</a> -- that's what's Pythonic. :)</p>
4
2008-09-10T21:44:53Z
[ "python", "sysadmin", "whois" ]
What Python way would you suggest to check whois database records?
50,394
<p>I'm trying to get a webservice up and running that actually requires to check whois databases. What I'm doing right now is ugly and I'd like to avoid it as much as I can: I call gwhois command and parse its output. Ugly.</p> <p>I did some search to try to find a pythonic way to do this task. Generally I got quite much nothing - <a href="http://mail.python.org/pipermail/python-list/2000-March/028122.html">this old discussion list link</a> has a way to check if domain exist. Quite not what I was looking for... But still, it was best anwser Google gave me - everything else is just a bunch of unanwsered questions.</p> <p>Any of you have succeeded to get some method up and running? I'd very much appreciate some tips, or should I just do it the opensource-way, sit down and code something by myself? :) </p>
7
2008-09-08T18:43:52Z
68,218
<p>I don't know if gwhois does something special with the server output; however, you can plainly connect to the whois server on port whois (43), send your query, read all the data in the reply and parse them. To make life a little easier, you could use the telnetlib.Telnet class (even if the whois protocol is much simpler than the telnet protocol) instead of plain sockets.</p> <p>The tricky parts:</p> <ul> <li>which whois server will you ask? RIPE, ARIN, APNIC, LACNIC, AFRINIC, JPNIC, VERIO etc LACNIC could be a useful fallback, since they tend to reply with useful data to requests outside of their domain.</li> <li>what are the exact options and arguments for each whois server? some offer help, others don't. In general, plain domain names work without any special options.</li> </ul>
1
2008-09-16T00:23:53Z
[ "python", "sysadmin", "whois" ]
What Python way would you suggest to check whois database records?
50,394
<p>I'm trying to get a webservice up and running that actually requires to check whois databases. What I'm doing right now is ugly and I'd like to avoid it as much as I can: I call gwhois command and parse its output. Ugly.</p> <p>I did some search to try to find a pythonic way to do this task. Generally I got quite much nothing - <a href="http://mail.python.org/pipermail/python-list/2000-March/028122.html">this old discussion list link</a> has a way to check if domain exist. Quite not what I was looking for... But still, it was best anwser Google gave me - everything else is just a bunch of unanwsered questions.</p> <p>Any of you have succeeded to get some method up and running? I'd very much appreciate some tips, or should I just do it the opensource-way, sit down and code something by myself? :) </p>
7
2008-09-08T18:43:52Z
2,408,136
<pre><code>import socket socket.gethostbyname_ex('url.com') </code></pre> <p>if it returns a gaierror you know know it's not registered with any DNS</p>
0
2010-03-09T10:07:39Z
[ "python", "sysadmin", "whois" ]
What Python way would you suggest to check whois database records?
50,394
<p>I'm trying to get a webservice up and running that actually requires to check whois databases. What I'm doing right now is ugly and I'd like to avoid it as much as I can: I call gwhois command and parse its output. Ugly.</p> <p>I did some search to try to find a pythonic way to do this task. Generally I got quite much nothing - <a href="http://mail.python.org/pipermail/python-list/2000-March/028122.html">this old discussion list link</a> has a way to check if domain exist. Quite not what I was looking for... But still, it was best anwser Google gave me - everything else is just a bunch of unanwsered questions.</p> <p>Any of you have succeeded to get some method up and running? I'd very much appreciate some tips, or should I just do it the opensource-way, sit down and code something by myself? :) </p>
7
2008-09-08T18:43:52Z
2,410,537
<p>here is a ready-to-use solution that works for me; written for Python 3.1 (when backporting to Py2.x, take special care of the bytes / Unicode text distinctions). your single point of access is the method <code>DRWHO.whois()</code>, which expects a domain name to be passed in; it will then try to resolve the name using the provider configured as <code>DRWHO.whois_providers[ '*' ]</code> (a more complete solution could differentiate providers according to the top level domain). <code>DRWHO.whois()</code> will return a dictionary with a single entry <code>text</code>, which contains the response text sent back by the WHOIS server. Again, a more complete solution would then try and parse the text (which must be done separately for each provider, as there is no standard format) and return a more structured format (e.g., set a flag <code>available</code> which specifies whether or not the domain looks available). have fun!</p> <pre><code>########################################################################## import asyncore as _sys_asyncore from asyncore import loop as _sys_asyncore_loop import socket as _sys_socket ########################################################################## class _Whois_request( _sys_asyncore.dispatcher_with_send, object ): # simple whois requester # original code by Frederik Lundh #----------------------------------------------------------------------- whoisPort = 43 #----------------------------------------------------------------------- def __init__(self, consumer, host, provider ): _sys_asyncore.dispatcher_with_send.__init__(self) self.consumer = consumer self.query = host self.create_socket( _sys_socket.AF_INET, _sys_socket.SOCK_STREAM ) self.connect( ( provider, self.whoisPort, ) ) #----------------------------------------------------------------------- def handle_connect(self): self.send( bytes( '%s\r\n' % ( self.query, ), 'utf-8' ) ) #----------------------------------------------------------------------- def handle_expt(self): self.close() # connection failed, shutdown self.consumer.abort() #----------------------------------------------------------------------- def handle_read(self): # get data from server self.consumer.feed( self.recv( 2048 ) ) #----------------------------------------------------------------------- def handle_close(self): self.close() self.consumer.close() ########################################################################## class _Whois_consumer( object ): # original code by Frederik Lundh #----------------------------------------------------------------------- def __init__( self, host, provider, result ): self.texts_as_bytes = [] self.host = host self.provider = provider self.result = result #----------------------------------------------------------------------- def feed( self, text ): self.texts_as_bytes.append( text.strip() ) #----------------------------------------------------------------------- def abort(self): del self.texts_as_bytes[:] self.finalize() #----------------------------------------------------------------------- def close(self): self.finalize() #----------------------------------------------------------------------- def finalize( self ): # join bytestrings and decode them (witha a guessed encoding): text_as_bytes = b'\n'.join( self.texts_as_bytes ) self.result[ 'text' ] = text_as_bytes.decode( 'utf-8' ) ########################################################################## class DRWHO: #----------------------------------------------------------------------- whois_providers = { '~isa': 'DRWHO/whois-providers', '*': 'whois.opensrs.net', } #----------------------------------------------------------------------- def whois( self, domain ): R = {} provider = self._get_whois_provider( '*' ) self._fetch_whois( provider, domain, R ) return R #----------------------------------------------------------------------- def _get_whois_provider( self, top_level_domain ): providers = self.whois_providers R = providers.get( top_level_domain, None ) if R is None: R = providers[ '*' ] return R #----------------------------------------------------------------------- def _fetch_whois( self, provider, domain, pod ): #..................................................................... consumer = _Whois_consumer( domain, provider, pod ) request = _Whois_request( consumer, domain, provider ) #..................................................................... _sys_asyncore_loop() # loops until requests have been processed #========================================================================= DRWHO = DRWHO() domain = 'example.com' whois = DRWHO.whois( domain ) print( whois[ 'text' ] ) </code></pre>
0
2010-03-09T16:17:23Z
[ "python", "sysadmin", "whois" ]
What Python way would you suggest to check whois database records?
50,394
<p>I'm trying to get a webservice up and running that actually requires to check whois databases. What I'm doing right now is ugly and I'd like to avoid it as much as I can: I call gwhois command and parse its output. Ugly.</p> <p>I did some search to try to find a pythonic way to do this task. Generally I got quite much nothing - <a href="http://mail.python.org/pipermail/python-list/2000-March/028122.html">this old discussion list link</a> has a way to check if domain exist. Quite not what I was looking for... But still, it was best anwser Google gave me - everything else is just a bunch of unanwsered questions.</p> <p>Any of you have succeeded to get some method up and running? I'd very much appreciate some tips, or should I just do it the opensource-way, sit down and code something by myself? :) </p>
7
2008-09-08T18:43:52Z
4,078,336
<p>Look at this: <a href="http://code.google.com/p/pywhois/">http://code.google.com/p/pywhois/</a></p> <p>pywhois - Python module for retrieving WHOIS information of domains</p> <p>Goal: - Create a simple importable Python module which will produce parsed WHOIS data for a given domain. - Able to extract data for all the popular TLDs (com, org, net, ...) - Query a WHOIS server directly instead of going through an intermediate web service like many others do. - Works with Python 2.4+ and no external dependencies</p> <p>Example:</p> <pre><code>&gt;&gt;&gt; import pywhois &gt;&gt;&gt; w = pywhois.whois('google.com') &gt;&gt;&gt; w.expiration_date ['14-sep-2011'] &gt;&gt;&gt; w.emails ['[email protected]', '[email protected]', '[email protected]', '[email protected]'] &gt;&gt;&gt; print w ... </code></pre>
8
2010-11-02T13:53:05Z
[ "python", "sysadmin", "whois" ]
What Python way would you suggest to check whois database records?
50,394
<p>I'm trying to get a webservice up and running that actually requires to check whois databases. What I'm doing right now is ugly and I'd like to avoid it as much as I can: I call gwhois command and parse its output. Ugly.</p> <p>I did some search to try to find a pythonic way to do this task. Generally I got quite much nothing - <a href="http://mail.python.org/pipermail/python-list/2000-March/028122.html">this old discussion list link</a> has a way to check if domain exist. Quite not what I was looking for... But still, it was best anwser Google gave me - everything else is just a bunch of unanwsered questions.</p> <p>Any of you have succeeded to get some method up and running? I'd very much appreciate some tips, or should I just do it the opensource-way, sit down and code something by myself? :) </p>
7
2008-09-08T18:43:52Z
5,494,113
<p>Here is the whois client re-implemented in Python: <a href="http://code.activestate.com/recipes/577364-whois-client/" rel="nofollow">http://code.activestate.com/recipes/577364-whois-client/</a></p>
4
2011-03-31T00:37:11Z
[ "python", "sysadmin", "whois" ]
What Python way would you suggest to check whois database records?
50,394
<p>I'm trying to get a webservice up and running that actually requires to check whois databases. What I'm doing right now is ugly and I'd like to avoid it as much as I can: I call gwhois command and parse its output. Ugly.</p> <p>I did some search to try to find a pythonic way to do this task. Generally I got quite much nothing - <a href="http://mail.python.org/pipermail/python-list/2000-March/028122.html">this old discussion list link</a> has a way to check if domain exist. Quite not what I was looking for... But still, it was best anwser Google gave me - everything else is just a bunch of unanwsered questions.</p> <p>Any of you have succeeded to get some method up and running? I'd very much appreciate some tips, or should I just do it the opensource-way, sit down and code something by myself? :) </p>
7
2008-09-08T18:43:52Z
11,343,954
<p>Found this question in the process of my own search for a python whois library.</p> <p>Don't know that I agree with cdleary's answer that using a library that wraps a command is always the best way to go - but I can see his reasons why he said this.</p> <p>Pro: cmd-line whois handles all the hard work (socket calls, parsing, etc)</p> <p>Con: not portable; module may not work depending on underlying whois command. Slower, since running a command and most likely shell in addition to whois command. Affected if not UNIX (Windows), different UNIX, older UNIX, or older whois command</p> <p>I am looking for a whois module that can handle whois IP lookups and I am not interested in coding my own whois client. </p> <p>Here are the modules that I (lightly) tried out and more information about it:</p> <p>pywhoisapi:</p> <ul> <li>Home: <a href="http://code.google.com/p/pywhoisapi/" rel="nofollow">http://code.google.com/p/pywhoisapi/</a></li> <li>Design: REST client accessing ARIN whois REST service</li> <li>Pros: Able to handle IP address lookups</li> <li>Cons: Able to pull information from whois servers of other RIRs?</li> </ul> <p>BulkWhois</p> <ul> <li>Home: <a href="http://pypi.python.org/pypi/BulkWhois/0.2.1" rel="nofollow">http://pypi.python.org/pypi/BulkWhois/0.2.1</a></li> <li>Design: telnet client accessing whois telnet query interface from RIR(?)</li> <li>Pros: Able to handle IP address lookups</li> <li>Cons: Able to pull information from whois servers of other RIRs?</li> </ul> <p>pywhois:</p> <ul> <li>Home: <a href="http://code.google.com/p/pywhois/" rel="nofollow">http://code.google.com/p/pywhois/</a></li> <li>Design: REST client accessing RRID whois services</li> <li>Pros: Accessses many RRIDs; has python 3.x branch</li> <li>Cons: does not seem to handle IP address lookups</li> </ul> <p>python-whois:</p> <ul> <li>Home: <a href="http://code.google.com/p/python-whois/" rel="nofollow">http://code.google.com/p/python-whois/</a></li> <li>Design: wraps "whois" command</li> <li>Cons: does not seem to handle IP address lookups</li> </ul> <p>whoisclient - fork of python-whois</p> <ul> <li>Home: <a href="http://gitorious.org/python-whois" rel="nofollow">http://gitorious.org/python-whois</a></li> <li>Design: wraps "whois" command</li> <li>Depends on: IPy.py</li> <li>Cons: does not seem to handle IP address lookups</li> </ul> <p>Update: I ended up using pywhoisapi for the reverse IP lookups that I was doing</p>
5
2012-07-05T12:03:17Z
[ "python", "sysadmin", "whois" ]
How do I get the path and name of the file that is currently executing?
50,499
<p>I have scripts calling other script files but I need to get the filepath of the file that is currently running within the process. </p> <p>For example, let's say I have three files. Using <a href="http://docs.python.org/library/functions.html#execfile">execfile</a>:</p> <ul> <li><code>script_1.py</code> calls <code>script_2.py</code>. </li> <li>In turn, <code>script_2.py</code> calls <code>script_3.py</code>. </li> </ul> <p>How can I get the file name and path of <strong><code>script_3.py</code></strong>, <em>from code within <code>script_3.py</code></em>, without having to pass that information as arguments from <code>script_2.py</code>?</p> <p>(Executing <code>os.getcwd()</code> returns the original starting script's filepath not the current file's.)</p>
262
2008-09-08T19:41:10Z
50,502
<p>It's not entirely clear what you mean by "the filepath of the file that is currently running within the process". <code>sys.argv[0]</code> usually contains the location of the script that was invoked by the Python interpreter. Check the <a href="https://docs.python.org/2/library/sys.html" rel="nofollow">sys documentation</a> for more details.</p> <p>As @Tim and @Pat Notz have pointed out, the __file__ attribute provides access to</p> <blockquote> <p>the file from which the module was loaded, if it was loaded from a file</p> </blockquote>
11
2008-09-08T19:42:56Z
[ "python", "scripting", "file" ]
How do I get the path and name of the file that is currently executing?
50,499
<p>I have scripts calling other script files but I need to get the filepath of the file that is currently running within the process. </p> <p>For example, let's say I have three files. Using <a href="http://docs.python.org/library/functions.html#execfile">execfile</a>:</p> <ul> <li><code>script_1.py</code> calls <code>script_2.py</code>. </li> <li>In turn, <code>script_2.py</code> calls <code>script_3.py</code>. </li> </ul> <p>How can I get the file name and path of <strong><code>script_3.py</code></strong>, <em>from code within <code>script_3.py</code></em>, without having to pass that information as arguments from <code>script_2.py</code>?</p> <p>(Executing <code>os.getcwd()</code> returns the original starting script's filepath not the current file's.)</p>
262
2008-09-08T19:41:10Z
50,505
<p>I think it's just <code>__file__</code> Sounds like you may also want to checkout the <a href="https://docs.python.org/2/library/inspect.html" rel="nofollow">inspect module</a>.</p>
5
2008-09-08T19:44:07Z
[ "python", "scripting", "file" ]
How do I get the path and name of the file that is currently executing?
50,499
<p>I have scripts calling other script files but I need to get the filepath of the file that is currently running within the process. </p> <p>For example, let's say I have three files. Using <a href="http://docs.python.org/library/functions.html#execfile">execfile</a>:</p> <ul> <li><code>script_1.py</code> calls <code>script_2.py</code>. </li> <li>In turn, <code>script_2.py</code> calls <code>script_3.py</code>. </li> </ul> <p>How can I get the file name and path of <strong><code>script_3.py</code></strong>, <em>from code within <code>script_3.py</code></em>, without having to pass that information as arguments from <code>script_2.py</code>?</p> <p>(Executing <code>os.getcwd()</code> returns the original starting script's filepath not the current file's.)</p>
262
2008-09-08T19:41:10Z
50,521
<p>The <code>__file__</code> attribute works for both the file containing the main execution code as well as imported modules.</p> <p>See <a href="https://web.archive.org/web/20090918095828/http://pyref.infogami.com/__file__" rel="nofollow">https://web.archive.org/web/20090918095828/http://pyref.infogami.com/__file__</a></p>
7
2008-09-08T19:56:19Z
[ "python", "scripting", "file" ]
How do I get the path and name of the file that is currently executing?
50,499
<p>I have scripts calling other script files but I need to get the filepath of the file that is currently running within the process. </p> <p>For example, let's say I have three files. Using <a href="http://docs.python.org/library/functions.html#execfile">execfile</a>:</p> <ul> <li><code>script_1.py</code> calls <code>script_2.py</code>. </li> <li>In turn, <code>script_2.py</code> calls <code>script_3.py</code>. </li> </ul> <p>How can I get the file name and path of <strong><code>script_3.py</code></strong>, <em>from code within <code>script_3.py</code></em>, without having to pass that information as arguments from <code>script_2.py</code>?</p> <p>(Executing <code>os.getcwd()</code> returns the original starting script's filepath not the current file's.)</p>
262
2008-09-08T19:41:10Z
50,905
<p>p1.py:</p> <pre><code>execfile("p2.py") </code></pre> <p>p2.py:</p> <pre><code>import inspect, os print inspect.getfile(inspect.currentframe()) # script filename (usually with path) print os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) # script directory </code></pre>
168
2008-09-08T23:02:42Z
[ "python", "scripting", "file" ]
How do I get the path and name of the file that is currently executing?
50,499
<p>I have scripts calling other script files but I need to get the filepath of the file that is currently running within the process. </p> <p>For example, let's say I have three files. Using <a href="http://docs.python.org/library/functions.html#execfile">execfile</a>:</p> <ul> <li><code>script_1.py</code> calls <code>script_2.py</code>. </li> <li>In turn, <code>script_2.py</code> calls <code>script_3.py</code>. </li> </ul> <p>How can I get the file name and path of <strong><code>script_3.py</code></strong>, <em>from code within <code>script_3.py</code></em>, without having to pass that information as arguments from <code>script_2.py</code>?</p> <p>(Executing <code>os.getcwd()</code> returns the original starting script's filepath not the current file's.)</p>
262
2008-09-08T19:41:10Z
50,986
<p>You can use <code>inspect.stack()</code></p> <pre><code>import inspect,os inspect.stack()[0] =&gt; (&lt;frame object at 0x00AC2AC0&gt;, 'g:\\Python\\Test\\_GetCurrentProgram.py', 15, '&lt;module&gt;', ['print inspect.stack()[0]\n'], 0) os.path.abspath (inspect.stack()[0][1]) =&gt; 'g:\\Python\\Test\\_GetCurrentProgram.py' </code></pre>
3
2008-09-09T00:00:52Z
[ "python", "scripting", "file" ]
How do I get the path and name of the file that is currently executing?
50,499
<p>I have scripts calling other script files but I need to get the filepath of the file that is currently running within the process. </p> <p>For example, let's say I have three files. Using <a href="http://docs.python.org/library/functions.html#execfile">execfile</a>:</p> <ul> <li><code>script_1.py</code> calls <code>script_2.py</code>. </li> <li>In turn, <code>script_2.py</code> calls <code>script_3.py</code>. </li> </ul> <p>How can I get the file name and path of <strong><code>script_3.py</code></strong>, <em>from code within <code>script_3.py</code></em>, without having to pass that information as arguments from <code>script_2.py</code>?</p> <p>(Executing <code>os.getcwd()</code> returns the original starting script's filepath not the current file's.)</p>
262
2008-09-08T19:41:10Z
1,955,163
<pre><code>__file__ </code></pre> <p>as others have said. You may want to use: </p> <pre><code>os.path.realpath(__file__) </code></pre>
260
2009-12-23T20:33:47Z
[ "python", "scripting", "file" ]
How do I get the path and name of the file that is currently executing?
50,499
<p>I have scripts calling other script files but I need to get the filepath of the file that is currently running within the process. </p> <p>For example, let's say I have three files. Using <a href="http://docs.python.org/library/functions.html#execfile">execfile</a>:</p> <ul> <li><code>script_1.py</code> calls <code>script_2.py</code>. </li> <li>In turn, <code>script_2.py</code> calls <code>script_3.py</code>. </li> </ul> <p>How can I get the file name and path of <strong><code>script_3.py</code></strong>, <em>from code within <code>script_3.py</code></em>, without having to pass that information as arguments from <code>script_2.py</code>?</p> <p>(Executing <code>os.getcwd()</code> returns the original starting script's filepath not the current file's.)</p>
262
2008-09-08T19:41:10Z
1,992,378
<pre><code>import sys print sys.path[0] </code></pre> <p>this would print the path of the currently executing script</p>
4
2010-01-02T18:34:55Z
[ "python", "scripting", "file" ]
How do I get the path and name of the file that is currently executing?
50,499
<p>I have scripts calling other script files but I need to get the filepath of the file that is currently running within the process. </p> <p>For example, let's say I have three files. Using <a href="http://docs.python.org/library/functions.html#execfile">execfile</a>:</p> <ul> <li><code>script_1.py</code> calls <code>script_2.py</code>. </li> <li>In turn, <code>script_2.py</code> calls <code>script_3.py</code>. </li> </ul> <p>How can I get the file name and path of <strong><code>script_3.py</code></strong>, <em>from code within <code>script_3.py</code></em>, without having to pass that information as arguments from <code>script_2.py</code>?</p> <p>(Executing <code>os.getcwd()</code> returns the original starting script's filepath not the current file's.)</p>
262
2008-09-08T19:41:10Z
2,345,265
<p>The suggestions marked as best are all true if your script consists of only one file. </p> <p>If you want to find out the name of the executable (i.e. the root file passed to the python interpreter for the current program) from a file that may be imported as a module, you need to do this (let's assume this is in a file named <em>foo.py</em>):</p> <p><code>import inspect</code></p> <p><code>print inspect.stack()[-1][1]</code></p> <p>Because the last thing (<code>[-1]</code>) on the stack is the first thing that went into it (stacks are LIFO/FILO data structures).</p> <p>Then in file <em>bar.py</em> if you <code>import foo</code> it'll print <em>bar.py</em>, rather than <em>foo.py</em>, which would be the value of all of these:</p> <ul> <li><code>__file__</code></li> <li><code>inspect.getfile(inspect.currentframe())</code></li> <li><code>inspect.stack()[0][1]</code></li> </ul>
30
2010-02-26T22:25:29Z
[ "python", "scripting", "file" ]
How do I get the path and name of the file that is currently executing?
50,499
<p>I have scripts calling other script files but I need to get the filepath of the file that is currently running within the process. </p> <p>For example, let's say I have three files. Using <a href="http://docs.python.org/library/functions.html#execfile">execfile</a>:</p> <ul> <li><code>script_1.py</code> calls <code>script_2.py</code>. </li> <li>In turn, <code>script_2.py</code> calls <code>script_3.py</code>. </li> </ul> <p>How can I get the file name and path of <strong><code>script_3.py</code></strong>, <em>from code within <code>script_3.py</code></em>, without having to pass that information as arguments from <code>script_2.py</code>?</p> <p>(Executing <code>os.getcwd()</code> returns the original starting script's filepath not the current file's.)</p>
262
2008-09-08T19:41:10Z
2,665,888
<pre><code>import sys print sys.argv[0] </code></pre>
4
2010-04-19T07:47:21Z
[ "python", "scripting", "file" ]
How do I get the path and name of the file that is currently executing?
50,499
<p>I have scripts calling other script files but I need to get the filepath of the file that is currently running within the process. </p> <p>For example, let's say I have three files. Using <a href="http://docs.python.org/library/functions.html#execfile">execfile</a>:</p> <ul> <li><code>script_1.py</code> calls <code>script_2.py</code>. </li> <li>In turn, <code>script_2.py</code> calls <code>script_3.py</code>. </li> </ul> <p>How can I get the file name and path of <strong><code>script_3.py</code></strong>, <em>from code within <code>script_3.py</code></em>, without having to pass that information as arguments from <code>script_2.py</code>?</p> <p>(Executing <code>os.getcwd()</code> returns the original starting script's filepath not the current file's.)</p>
262
2008-09-08T19:41:10Z
5,152,554
<p>I used the approach with __file__<br> <code>os.path.abspath(__file__)</code><br> but there is a little trick, it returns the .py file when the code is run the first time, next runs give the name of *.pyc file<br> so I stayed with:<br> <code>inspect.getfile(inspect.currentframe())</code><br> or<br> <code>sys._getframe().f_code.co_filename</code> </p>
0
2011-03-01T09:23:09Z
[ "python", "scripting", "file" ]
How do I get the path and name of the file that is currently executing?
50,499
<p>I have scripts calling other script files but I need to get the filepath of the file that is currently running within the process. </p> <p>For example, let's say I have three files. Using <a href="http://docs.python.org/library/functions.html#execfile">execfile</a>:</p> <ul> <li><code>script_1.py</code> calls <code>script_2.py</code>. </li> <li>In turn, <code>script_2.py</code> calls <code>script_3.py</code>. </li> </ul> <p>How can I get the file name and path of <strong><code>script_3.py</code></strong>, <em>from code within <code>script_3.py</code></em>, without having to pass that information as arguments from <code>script_2.py</code>?</p> <p>(Executing <code>os.getcwd()</code> returns the original starting script's filepath not the current file's.)</p>
262
2008-09-08T19:41:10Z
6,628,348
<p>I think this is cleaner:</p> <pre><code>import inspect print inspect.stack()[0][1] </code></pre> <p>and gets the same information as:</p> <pre><code>print inspect.getfile(inspect.currentframe()) </code></pre> <p>Where [0] is the current frame in the stack (top of stack) and [1] is for the file name, increase to go backwards in the stack i.e.</p> <pre><code>print inspect.stack()[1][1] </code></pre> <p>would be the file name of the script that called the current frame. Also, using [-1] will get you to the bottom of the stack, the original calling script.</p>
38
2011-07-08T17:50:28Z
[ "python", "scripting", "file" ]
How do I get the path and name of the file that is currently executing?
50,499
<p>I have scripts calling other script files but I need to get the filepath of the file that is currently running within the process. </p> <p>For example, let's say I have three files. Using <a href="http://docs.python.org/library/functions.html#execfile">execfile</a>:</p> <ul> <li><code>script_1.py</code> calls <code>script_2.py</code>. </li> <li>In turn, <code>script_2.py</code> calls <code>script_3.py</code>. </li> </ul> <p>How can I get the file name and path of <strong><code>script_3.py</code></strong>, <em>from code within <code>script_3.py</code></em>, without having to pass that information as arguments from <code>script_2.py</code>?</p> <p>(Executing <code>os.getcwd()</code> returns the original starting script's filepath not the current file's.)</p>
262
2008-09-08T19:41:10Z
11,861,785
<p>I have a script that must work under windows environment. This code snipped is what I've finished with:</p> <pre><code>import os,sys PROJECT_PATH = os.path.abspath(os.path.split(sys.argv[0])[0]) </code></pre> <p>it's quite a hacky decision. But it requires no external libraries and it's the most important thing in my case.</p>
5
2012-08-08T09:42:27Z
[ "python", "scripting", "file" ]
How do I get the path and name of the file that is currently executing?
50,499
<p>I have scripts calling other script files but I need to get the filepath of the file that is currently running within the process. </p> <p>For example, let's say I have three files. Using <a href="http://docs.python.org/library/functions.html#execfile">execfile</a>:</p> <ul> <li><code>script_1.py</code> calls <code>script_2.py</code>. </li> <li>In turn, <code>script_2.py</code> calls <code>script_3.py</code>. </li> </ul> <p>How can I get the file name and path of <strong><code>script_3.py</code></strong>, <em>from code within <code>script_3.py</code></em>, without having to pass that information as arguments from <code>script_2.py</code>?</p> <p>(Executing <code>os.getcwd()</code> returns the original starting script's filepath not the current file's.)</p>
262
2008-09-08T19:41:10Z
14,429,192
<p>if you want just the filename without <code>./</code> or <code>.py</code> you can try this</p> <pre><code>filename = testscript.py file_name = __file__[2:-3] </code></pre> <p><code>file_name</code> will print testscript you can generate whatever you want by changing the index inside []</p>
0
2013-01-20T20:52:13Z
[ "python", "scripting", "file" ]
How do I get the path and name of the file that is currently executing?
50,499
<p>I have scripts calling other script files but I need to get the filepath of the file that is currently running within the process. </p> <p>For example, let's say I have three files. Using <a href="http://docs.python.org/library/functions.html#execfile">execfile</a>:</p> <ul> <li><code>script_1.py</code> calls <code>script_2.py</code>. </li> <li>In turn, <code>script_2.py</code> calls <code>script_3.py</code>. </li> </ul> <p>How can I get the file name and path of <strong><code>script_3.py</code></strong>, <em>from code within <code>script_3.py</code></em>, without having to pass that information as arguments from <code>script_2.py</code>?</p> <p>(Executing <code>os.getcwd()</code> returns the original starting script's filepath not the current file's.)</p>
262
2008-09-08T19:41:10Z
14,493,064
<pre><code>import os import wx # return the full path of this file print(os.getcwd()) icon = wx.Icon(os.getcwd() + '/img/image.png', wx.BITMAP_TYPE_PNG, 16, 16) # put the icon on the frame self.SetIcon(icon) </code></pre>
-1
2013-01-24T02:43:09Z
[ "python", "scripting", "file" ]
How do I get the path and name of the file that is currently executing?
50,499
<p>I have scripts calling other script files but I need to get the filepath of the file that is currently running within the process. </p> <p>For example, let's say I have three files. Using <a href="http://docs.python.org/library/functions.html#execfile">execfile</a>:</p> <ul> <li><code>script_1.py</code> calls <code>script_2.py</code>. </li> <li>In turn, <code>script_2.py</code> calls <code>script_3.py</code>. </li> </ul> <p>How can I get the file name and path of <strong><code>script_3.py</code></strong>, <em>from code within <code>script_3.py</code></em>, without having to pass that information as arguments from <code>script_2.py</code>?</p> <p>(Executing <code>os.getcwd()</code> returns the original starting script's filepath not the current file's.)</p>
262
2008-09-08T19:41:10Z
18,168,345
<pre><code>import os print os.path.basename(__file__) </code></pre> <p>this will give us the filename only. i.e. if abspath of file is c:\abcd\abc.py then 2nd line will print abc.py</p>
13
2013-08-11T03:05:05Z
[ "python", "scripting", "file" ]
How do I get the path and name of the file that is currently executing?
50,499
<p>I have scripts calling other script files but I need to get the filepath of the file that is currently running within the process. </p> <p>For example, let's say I have three files. Using <a href="http://docs.python.org/library/functions.html#execfile">execfile</a>:</p> <ul> <li><code>script_1.py</code> calls <code>script_2.py</code>. </li> <li>In turn, <code>script_2.py</code> calls <code>script_3.py</code>. </li> </ul> <p>How can I get the file name and path of <strong><code>script_3.py</code></strong>, <em>from code within <code>script_3.py</code></em>, without having to pass that information as arguments from <code>script_2.py</code>?</p> <p>(Executing <code>os.getcwd()</code> returns the original starting script's filepath not the current file's.)</p>
262
2008-09-08T19:41:10Z
24,390,114
<pre><code>import os os.path.dirname(os.path.abspath(__file__)) </code></pre> <p>No need for inspect or any other library.</p> <p>This worked for me when I had to import a script (from a different directory then the executed script), that used a configuration file residing in the same folder as the imported script.</p>
4
2014-06-24T15:04:34Z
[ "python", "scripting", "file" ]
How do I get the path and name of the file that is currently executing?
50,499
<p>I have scripts calling other script files but I need to get the filepath of the file that is currently running within the process. </p> <p>For example, let's say I have three files. Using <a href="http://docs.python.org/library/functions.html#execfile">execfile</a>:</p> <ul> <li><code>script_1.py</code> calls <code>script_2.py</code>. </li> <li>In turn, <code>script_2.py</code> calls <code>script_3.py</code>. </li> </ul> <p>How can I get the file name and path of <strong><code>script_3.py</code></strong>, <em>from code within <code>script_3.py</code></em>, without having to pass that information as arguments from <code>script_2.py</code>?</p> <p>(Executing <code>os.getcwd()</code> returns the original starting script's filepath not the current file's.)</p>
262
2008-09-08T19:41:10Z
28,356,929
<pre><code>import os os.path.dirname(__file__) # relative directory path os.path.abspath(__file__) # absolute file path os.path.basename(__file__) # the file name only </code></pre>
23
2015-02-06T01:05:18Z
[ "python", "scripting", "file" ]
How do I get the path and name of the file that is currently executing?
50,499
<p>I have scripts calling other script files but I need to get the filepath of the file that is currently running within the process. </p> <p>For example, let's say I have three files. Using <a href="http://docs.python.org/library/functions.html#execfile">execfile</a>:</p> <ul> <li><code>script_1.py</code> calls <code>script_2.py</code>. </li> <li>In turn, <code>script_2.py</code> calls <code>script_3.py</code>. </li> </ul> <p>How can I get the file name and path of <strong><code>script_3.py</code></strong>, <em>from code within <code>script_3.py</code></em>, without having to pass that information as arguments from <code>script_2.py</code>?</p> <p>(Executing <code>os.getcwd()</code> returns the original starting script's filepath not the current file's.)</p>
262
2008-09-08T19:41:10Z
30,831,888
<p>This should work:</p> <pre><code>import os,sys filename=os.path.basename(os.path.realpath(sys.argv[0])) dirname=os.path.dirname(os.path.realpath(sys.argv[0])) </code></pre>
1
2015-06-14T16:37:44Z
[ "python", "scripting", "file" ]
How do I get the path and name of the file that is currently executing?
50,499
<p>I have scripts calling other script files but I need to get the filepath of the file that is currently running within the process. </p> <p>For example, let's say I have three files. Using <a href="http://docs.python.org/library/functions.html#execfile">execfile</a>:</p> <ul> <li><code>script_1.py</code> calls <code>script_2.py</code>. </li> <li>In turn, <code>script_2.py</code> calls <code>script_3.py</code>. </li> </ul> <p>How can I get the file name and path of <strong><code>script_3.py</code></strong>, <em>from code within <code>script_3.py</code></em>, without having to pass that information as arguments from <code>script_2.py</code>?</p> <p>(Executing <code>os.getcwd()</code> returns the original starting script's filepath not the current file's.)</p>
262
2008-09-08T19:41:10Z
31,867,043
<p>Here is an experiment based on the answers in this thread - with Python 2.7.10 on Windows.</p> <p><strong>The stack-based ones are the only ones that seem to give reliable results. The last two have the shortest syntax</strong>, ie -</p> <pre><code>print os.path.abspath(inspect.stack()[0][1]) # C:\testpath\lib\script3.py print os.path.dirname(os.path.abspath(inspect.stack()[0][1])) # C:\testpath\lib </code></pre> <p>Here's to these being added to <strong>sys</strong> as functions! Credit to @Usagi and @pablog</p> <p>Based on the following three files, and running script1.py from its folder with <code>python script1.py</code> (also tried execfiles with absolute paths and calling from a separate folder). </p> <p>C:\testpath\script1.py: <code>execfile('script2.py')</code><br> C:\testpath\script2.py: <code>execfile('lib/script3.py')</code><br> C:\testpath\lib\script3.py:</p> <pre><code>import sys import os import inspect print "Python " + sys.version print print __file__ # script1.py print sys.argv[0] # script1.py print inspect.stack()[0][1] # lib/script3.py print sys.path[0] # C:\testpath print print os.path.realpath(__file__) # C:\testpath\script1.py print os.path.abspath(__file__) # C:\testpath\script1.py print os.path.basename(__file__) # script1.py print os.path.basename(os.path.realpath(sys.argv[0])) # script1.py print print sys.path[0] # C:\testpath print os.path.abspath(os.path.split(sys.argv[0])[0]) # C:\testpath print os.path.dirname(os.path.abspath(__file__)) # C:\testpath print os.path.dirname(os.path.realpath(sys.argv[0])) # C:\testpath print os.path.dirname(__file__) # (empty string) print print inspect.getfile(inspect.currentframe()) # lib/script3.py print os.path.abspath(inspect.getfile(inspect.currentframe())) # C:\testpath\lib\script3.py print os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) # C:\testpath\lib print print os.path.abspath(inspect.stack()[0][1]) # C:\testpath\lib\script3.py print os.path.dirname(os.path.abspath(inspect.stack()[0][1])) # C:\testpath\lib print </code></pre>
22
2015-08-06T22:50:01Z
[ "python", "scripting", "file" ]
How do I get the path and name of the file that is currently executing?
50,499
<p>I have scripts calling other script files but I need to get the filepath of the file that is currently running within the process. </p> <p>For example, let's say I have three files. Using <a href="http://docs.python.org/library/functions.html#execfile">execfile</a>:</p> <ul> <li><code>script_1.py</code> calls <code>script_2.py</code>. </li> <li>In turn, <code>script_2.py</code> calls <code>script_3.py</code>. </li> </ul> <p>How can I get the file name and path of <strong><code>script_3.py</code></strong>, <em>from code within <code>script_3.py</code></em>, without having to pass that information as arguments from <code>script_2.py</code>?</p> <p>(Executing <code>os.getcwd()</code> returns the original starting script's filepath not the current file's.)</p>
262
2008-09-08T19:41:10Z
37,815,779
<p>I wrote a function which take into account eclipse <strong>debugger</strong> and <strong>unittest</strong>. It return the folder of the first script you launch. You can optionally specify the <em>__file__</em> var, but the main thing is that you don't have to share this variable across all your <strong>calling hierarchy</strong>.</p> <p>Maybe you can handle others stack particular cases I didn't see, but for me it's ok.</p> <pre><code>import inspect, os def getRootDirectory(_file_=None): """ Get the directory of the root execution file Can help: http://stackoverflow.com/questions/50499/how-do-i-get-the-path-and-name-of-the-file-that-is-currently-executing For eclipse user with unittest or debugger, the function search for the correct folder in the stack You can pass __file__ (with 4 underscores) if you want the caller directory """ # If we don't have the __file__ : if _file_ is None: # We get the last : rootFile = inspect.stack()[-1][1] folder = os.path.abspath(rootFile) # If we use unittest : if ("/pysrc" in folder) &amp; ("org.python.pydev" in folder): previous = None # We search from left to right the case.py : for el in inspect.stack(): currentFile = os.path.abspath(el[1]) if ("unittest/case.py" in currentFile) | ("org.python.pydev" in currentFile): break previous = currentFile folder = previous # We return the folder : return os.path.dirname(folder) else: # We return the folder according to specified __file__ : return os.path.dirname(os.path.realpath(_file_)) </code></pre>
0
2016-06-14T15:06:50Z
[ "python", "scripting", "file" ]
Django Sessions
50,568
<p>I'm looking at sessions in Django, and by default they are stored in the database. What are the benefits of filesystem and cache sessions and when should I use them?</p>
34
2008-09-08T20:16:16Z
50,668
<p>The filesystem backend is only worth looking at if you're not going to use a database for any other part of your system. If you are using a database then the filesystem backend has nothing to recommend it.</p> <p>The memcache backend is much quicker than the database backend, but you run the risk of a session being purged and some of your session data being lost.</p> <p>If you're a really, really high traffic website and code carefully so you can cope with losing a session then use memcache. If you're not using a database use the file system cache, but the default database backend is the best, safest and simplest option in almost all cases.</p>
25
2008-09-08T20:58:29Z
[ "python", "django", "session", "caching", "mongodb" ]
Django Sessions
50,568
<p>I'm looking at sessions in Django, and by default they are stored in the database. What are the benefits of filesystem and cache sessions and when should I use them?</p>
34
2008-09-08T20:16:16Z
51,511
<p>I'm no Django expert, so this answer is about session stores generally. Downvote if I'm wrong.</p> <h2>Performance and Scalability</h2> <p>Choice of session store has an effect on performance and scalability. This should only be a big problem if you have a very popular application.</p> <p>Both database and filesystem session stores are (usually) backed by disks so you can have a lot of sessions cheaply (because disks are cheap), but requests will often have to wait for the data to be read (because disks are slow). Memcached sessions use RAM, so will cost more to support the same number of concurrent sessions (because RAM is expensive), but may be faster (because RAM is fast).</p> <p>Filesystem sessions are tied to the box where your application is running, so you can't load balance between multiple application servers if your site gets huge. Database and memcached sessions let you have multiple application servers talking to a shared session store.</p> <h2>Simplicity</h2> <p>Choice of session store will also impact how easy it is to deploy your site. Changing away from the default will cost some complexity. Memcached and RDBMSs both have their own complexities, but your application is probably going to be using an RDBMS anyway.</p> <p>Unless you have a very popular application, simplicity should be the larger concern.</p> <h2>Bonus</h2> <p>Another approach is to store <a href="https://docs.djangoproject.com/en/1.8/topics/http/sessions/#using-cookie-based-sessions" rel="nofollow">session data in cookies</a> (all of it, not just an ID). This has the advantage that the session store automatically scales with the number of users, but it has disadvantages too. You (or your framework) need to be careful to stop users forging session data. You also need to keep each session small because the whole thing will be sent with every request.</p>
19
2008-09-09T10:11:33Z
[ "python", "django", "session", "caching", "mongodb" ]
Django Sessions
50,568
<p>I'm looking at sessions in Django, and by default they are stored in the database. What are the benefits of filesystem and cache sessions and when should I use them?</p>
34
2008-09-08T20:16:16Z
100,464
<p>One thing that has to be considered when choosing session backend is "how often session data is modified"? Even sites with moderate traffic will suffer if session data is modified on each request, making many database trips to store and retrieve data.</p> <p>In my previous work we used memcache as session backend exclusively and it worked really well. Our administrative team put really great effort in making two special memcached instances stable as a rock, but after bit of twiddling with initial setup, we did not have any interrupts of session backends operations.</p>
3
2008-09-19T08:20:37Z
[ "python", "django", "session", "caching", "mongodb" ]
Django Sessions
50,568
<p>I'm looking at sessions in Django, and by default they are stored in the database. What are the benefits of filesystem and cache sessions and when should I use them?</p>
34
2008-09-08T20:16:16Z
326,046
<p>If the database have a DBA that isn't you, you may not be allowed to use a database-backed session (it being a front-end matter only). Until django supports easily merging data from several databases, so that you can have frontend-specific stuff like sessions and user-messages (the messages in django.contrib.auth are also stored in the db) in a separate db, you need to keep this in mind.</p>
1
2008-11-28T15:34:56Z
[ "python", "django", "session", "caching", "mongodb" ]
Django Sessions
50,568
<p>I'm looking at sessions in Django, and by default they are stored in the database. What are the benefits of filesystem and cache sessions and when should I use them?</p>
34
2008-09-08T20:16:16Z
1,939,548
<p>As of Django 1.1 you can use the cached_db session back end.</p> <p>This stores the session in the cache (only use with memcached), and writes it back to the DB. If it has fallen out of the cache, it will be read from the DB.</p> <p>Although this is slower than just using memcached for storing the session, it adds persistence to the session.</p> <p>For more information, see: <a href="http://docs.djangoproject.com/en/dev/topics/http/sessions/#using-cached-sessions">Django Docs: Using Cached Sessions</a></p>
9
2009-12-21T11:21:56Z
[ "python", "django", "session", "caching", "mongodb" ]
How do you create a weak reference to an object in Python?
50,923
<p>How do you create a weak reference to an object in Python? </p>
4
2008-09-08T23:10:53Z
50,929
<pre><code>&gt;&gt;&gt; import weakref &gt;&gt;&gt; class Object: ... pass ... &gt;&gt;&gt; o = Object() &gt;&gt;&gt; r = weakref.ref(o) &gt;&gt;&gt; # if the reference is still active, r() will be o, otherwise None &gt;&gt;&gt; do_something_with_o(r()) </code></pre> <p>See the <a href="http://docs.python.org/lib/module-weakref.html">wearkref module docs</a> for more details. You can also use <code>weakref.proxy</code> to create an object that proxies o. Will throw <code>ReferenceError</code> if used when the referent is no longer referenced.</p>
10
2008-09-08T23:13:16Z
[ "python", "weak-references" ]
What is the simplest way to find the difference between 2 times in python?
51,010
<p>I have 2 time values which have the type <code>datetime.time</code>. I want to find their difference. The obvious thing to do is t1 - t2, but this doesn't work. It works for objects of type <code>datetime.datetime</code> but not for <code>datetime.time</code>. So what is the best way to do this?</p>
9
2008-09-09T00:28:58Z
51,015
<p>It seems that this isn't supported, since there wouldn't be a good way to deal with overflows in datetime.time. I know this isn't an answer directly, but maybe someone with more python experience than me can take this a little further. For more info, see this: <a href="http://bugs.python.org/issue3250" rel="nofollow">http://bugs.python.org/issue3250</a></p>
1
2008-09-09T00:37:28Z
[ "python", "datetime", "time" ]
What is the simplest way to find the difference between 2 times in python?
51,010
<p>I have 2 time values which have the type <code>datetime.time</code>. I want to find their difference. The obvious thing to do is t1 - t2, but this doesn't work. It works for objects of type <code>datetime.datetime</code> but not for <code>datetime.time</code>. So what is the best way to do this?</p>
9
2008-09-09T00:28:58Z
51,023
<p>You could transform both into <a href="http://docs.python.org/lib/datetime-timedelta.html" rel="nofollow">timedelta objects</a> and subtract these from each other, which will take care to of the carry-overs. For example:</p> <pre><code>&gt;&gt;&gt; import datetime as dt &gt;&gt;&gt; t1 = dt.time(23, 5, 5, 5) &gt;&gt;&gt; t2 = dt.time(10, 5, 5, 5) &gt;&gt;&gt; dt1 = dt.timedelta(hours=t1.hour, minutes=t1.minute, seconds=t1.second, microseconds=t1.microsecond) &gt;&gt;&gt; dt2 = dt.timedelta(hours=t2.hour, minutes=t2.minute, seconds=t2.second, microseconds=t2.microsecond) &gt;&gt;&gt; print(dt1-dt2) 13:00:00 &gt;&gt;&gt; print(dt2-dt1) -1 day, 11:00:00 &gt;&gt;&gt; print(abs(dt2-dt1)) 13:00:00 </code></pre> <p>Negative timedelta objects in Python get a negative day field, with the other fields positive. You could check beforehand: comparison works on both time objects and timedelta objects:</p> <pre><code>&gt;&gt;&gt; dt2 &lt; dt1 True &gt;&gt;&gt; t2 &lt; t1 True </code></pre>
5
2008-09-09T00:42:31Z
[ "python", "datetime", "time" ]
What is the simplest way to find the difference between 2 times in python?
51,010
<p>I have 2 time values which have the type <code>datetime.time</code>. I want to find their difference. The obvious thing to do is t1 - t2, but this doesn't work. It works for objects of type <code>datetime.datetime</code> but not for <code>datetime.time</code>. So what is the best way to do this?</p>
9
2008-09-09T00:28:58Z
51,029
<p>Firstly, note that a datetime.time is a time of day, independent of a given day, and so the different between any two datetime.time values is going to be less than 24 hours.</p> <p>One approach is to convert both datetime.time values into comparable values (such as milliseconds), and find the difference.</p> <pre><code>t1, t2 = datetime.time(...), datetime.time(...) t1_ms = (t1.hour*60*60 + t1.minute*60 + t1.second)*1000 + t1.microsecond t2_ms = (t2.hour*60*60 + t2.minute*60 + t2.second)*1000 + t2.microsecond delta_ms = max([t1_ms, t2_ms]) - min([t1_ms, t2_ms]) </code></pre> <p>It's a little lame, but it works.</p>
-2
2008-09-09T00:47:48Z
[ "python", "datetime", "time" ]
What is the simplest way to find the difference between 2 times in python?
51,010
<p>I have 2 time values which have the type <code>datetime.time</code>. I want to find their difference. The obvious thing to do is t1 - t2, but this doesn't work. It works for objects of type <code>datetime.datetime</code> but not for <code>datetime.time</code>. So what is the best way to do this?</p>
9
2008-09-09T00:28:58Z
51,042
<p>Also a little silly, but you could try picking an arbitrary day and embedding each time in it, using <code>datetime.datetime.combine</code>, then subtracting:</p> <pre><code>&gt;&gt;&gt; import datetime &gt;&gt;&gt; t1 = datetime.time(2,3,4) &gt;&gt;&gt; t2 = datetime.time(18,20,59) &gt;&gt;&gt; dummydate = datetime.date(2000,1,1) &gt;&gt;&gt; datetime.datetime.combine(dummydate,t2) - datetime.datetime.combine(dummydate,t1) datetime.timedelta(0, 58675) </code></pre>
16
2008-09-09T00:53:24Z
[ "python", "datetime", "time" ]
What is the simplest way to find the difference between 2 times in python?
51,010
<p>I have 2 time values which have the type <code>datetime.time</code>. I want to find their difference. The obvious thing to do is t1 - t2, but this doesn't work. It works for objects of type <code>datetime.datetime</code> but not for <code>datetime.time</code>. So what is the best way to do this?</p>
9
2008-09-09T00:28:58Z
108,599
<p>Python has pytz (<a href="http://pytz.sourceforge.net" rel="nofollow">http://pytz.sourceforge.net</a>) module which can be used for arithmetic of 'time' objects. It takes care of DST offsets as well. The above page has a number of examples that illustrate the usage of pytz.</p>
3
2008-09-20T16:13:22Z
[ "python", "datetime", "time" ]
What is the simplest way to find the difference between 2 times in python?
51,010
<p>I have 2 time values which have the type <code>datetime.time</code>. I want to find their difference. The obvious thing to do is t1 - t2, but this doesn't work. It works for objects of type <code>datetime.datetime</code> but not for <code>datetime.time</code>. So what is the best way to do this?</p>
9
2008-09-09T00:28:58Z
108,603
<p>Retrieve the times in milliseconds and then do the subtraction.</p>
-1
2008-09-20T16:16:44Z
[ "python", "datetime", "time" ]