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
How do I efficiently filter computed values within a Python list comprehension?
130,262
<p>The Python list comprehension syntax makes it easy to filter values within a comprehension. For example:</p> <pre><code>result = [x**2 for x in mylist if type(x) is int] </code></pre> <p>Will return a list of the squares of integers in mylist. However, what if the test involves some (costly) computation and you want to filter on the result? One option is:</p> <pre><code>result = [expensive(x) for x in mylist if expensive(x)] </code></pre> <p>This will result in a list of non-"false" expensive(x) values, however expensive() is called twice for each x. Is there a comprehension syntax that allows you to do this test while only calling expensive once per x?</p>
16
2008-09-24T22:08:57Z
873,661
<p>I will have a preference for:</p> <pre><code>itertools.ifilter(bool, (expensive(x) for x in mylist)) </code></pre> <p>This has the advantage to:</p> <ul> <li>avoid None as the function (will be eliminated in Python 3): <a href="http://bugs.python.org/issue2186" rel="nofollow">http://bugs.python.org/issue2186</a></li> <li>use only iterators.</li> </ul>
1
2009-05-17T01:01:11Z
[ "python", "list-comprehension" ]
How do I efficiently filter computed values within a Python list comprehension?
130,262
<p>The Python list comprehension syntax makes it easy to filter values within a comprehension. For example:</p> <pre><code>result = [x**2 for x in mylist if type(x) is int] </code></pre> <p>Will return a list of the squares of integers in mylist. However, what if the test involves some (costly) computation and you want to filter on the result? One option is:</p> <pre><code>result = [expensive(x) for x in mylist if expensive(x)] </code></pre> <p>This will result in a list of non-"false" expensive(x) values, however expensive() is called twice for each x. Is there a comprehension syntax that allows you to do this test while only calling expensive once per x?</p>
16
2008-09-24T22:08:57Z
874,319
<p>There is the plain old use of a <code>for</code> loop to append to a list, too:</p> <pre><code>result = [] for x in mylist: expense = expensive(x) if expense: result.append(expense) </code></pre>
0
2009-05-17T10:25:40Z
[ "python", "list-comprehension" ]
How to pass all Visual Studio 2008 "Macros" to Python script?
130,587
<p><em>[NOTE: This questions is similar to but <strong>not the same</strong> as <a href="http://stackoverflow.com/questions/128634/how-to-use-system-environment-variables-in-vs-2008-post-build-events">this one</a>.]</em></p> <p>Visual Studio defines several dozen "Macros" which are sort of simulated environment variables (completely unrelated to C++ macros) which contain information about the build in progress. Examples:</p> <pre> ConfigurationName Release TargetPath D:\work\foo\win\Release\foo.exe VCInstallDir C:\ProgramFiles\Microsoft Visual Studio 9.0\VC\ </pre> <p>Here is the complete set of 43 built-in Macros that I see (yours may differ depending on which version of VS you use and which tools you have enabled):</p> <pre> ConfigurationName IntDir RootNamespace TargetFileName DevEnvDir OutDir SafeInputName TargetFramework FrameworkDir ParentName SafeParentName TargetName FrameworkSDKDir PlatformName SafeRootNamespace TargetPath FrameworkVersion ProjectDir SolutionDir VCInstallDir FxCopDir ProjectExt SolutionExt VSInstallDir InputDir ProjectFileName SolutionFileName WebDeployPath InputExt ProjectName SolutionName WebDeployRoot InputFileName ProjectPath SolutionPath WindowsSdkDir InputName References TargetDir WindowsSdkDirIA64 InputPath RemoteMachine TargetExt </pre> <p>Of these, only four (<code>FrameworkDir</code>, <code>FrameworkSDKDir</code>, <code>VCInstallDir</code> and <code>VSInstallDir</code>) are set in the environment used for build-events.</p> <p>As Brian mentions, user-defined Macros can be defined such as to be set in the environment in which build tasks execute. My problem is with the built-in Macros.</p> <p>I use a Visual Studio Post-Build Event to run a python script as part of my build process. I'd like to pass the entire set of Macros (built-in and user-defined) to my script in the environment but I don't know how. Within my script I can access regular environment variables (e.g., Path, SystemRoot) but NOT these "Macros". All I can do now is pass them on-by-one as named options which I then process within my script. For example, this is what my Post-Build Event command line looks like:</p> <pre> postbuild.py --t="$(TargetPath)" --c="$(ConfigurationName)" </pre> <p>Besides being a pain in the neck, there is a limit on the size of Post-Build Event command line so I can't pass dozens Macros using this method even if I wanted to because the command line is truncated.</p> <p>Does anyone know if there is a way to pass the entire set of Macro names and values to a command that does NOT require switching to MSBuild (which I believe is not available for native VC++) or some other make-like build tool?</p>
2
2008-09-24T23:28:24Z
130,773
<p>This is a bit hacky, but it could work.</p> <p>Why not call multiple .py scripts in a row?</p> <p>Each scripts can pass in a small subset of the parameters, and the values to a temp text file. The final script will read and work off of the temp text file.</p> <p>I agree that this method is filled with danger and WTF's, but sometimes you have to just hack stuff together.</p>
0
2008-09-25T00:24:23Z
[ "python", "visual-studio", "visual-studio-2008", "visual-c++", "visual-studio-2005" ]
How to pass all Visual Studio 2008 "Macros" to Python script?
130,587
<p><em>[NOTE: This questions is similar to but <strong>not the same</strong> as <a href="http://stackoverflow.com/questions/128634/how-to-use-system-environment-variables-in-vs-2008-post-build-events">this one</a>.]</em></p> <p>Visual Studio defines several dozen "Macros" which are sort of simulated environment variables (completely unrelated to C++ macros) which contain information about the build in progress. Examples:</p> <pre> ConfigurationName Release TargetPath D:\work\foo\win\Release\foo.exe VCInstallDir C:\ProgramFiles\Microsoft Visual Studio 9.0\VC\ </pre> <p>Here is the complete set of 43 built-in Macros that I see (yours may differ depending on which version of VS you use and which tools you have enabled):</p> <pre> ConfigurationName IntDir RootNamespace TargetFileName DevEnvDir OutDir SafeInputName TargetFramework FrameworkDir ParentName SafeParentName TargetName FrameworkSDKDir PlatformName SafeRootNamespace TargetPath FrameworkVersion ProjectDir SolutionDir VCInstallDir FxCopDir ProjectExt SolutionExt VSInstallDir InputDir ProjectFileName SolutionFileName WebDeployPath InputExt ProjectName SolutionName WebDeployRoot InputFileName ProjectPath SolutionPath WindowsSdkDir InputName References TargetDir WindowsSdkDirIA64 InputPath RemoteMachine TargetExt </pre> <p>Of these, only four (<code>FrameworkDir</code>, <code>FrameworkSDKDir</code>, <code>VCInstallDir</code> and <code>VSInstallDir</code>) are set in the environment used for build-events.</p> <p>As Brian mentions, user-defined Macros can be defined such as to be set in the environment in which build tasks execute. My problem is with the built-in Macros.</p> <p>I use a Visual Studio Post-Build Event to run a python script as part of my build process. I'd like to pass the entire set of Macros (built-in and user-defined) to my script in the environment but I don't know how. Within my script I can access regular environment variables (e.g., Path, SystemRoot) but NOT these "Macros". All I can do now is pass them on-by-one as named options which I then process within my script. For example, this is what my Post-Build Event command line looks like:</p> <pre> postbuild.py --t="$(TargetPath)" --c="$(ConfigurationName)" </pre> <p>Besides being a pain in the neck, there is a limit on the size of Post-Build Event command line so I can't pass dozens Macros using this method even if I wanted to because the command line is truncated.</p> <p>Does anyone know if there is a way to pass the entire set of Macro names and values to a command that does NOT require switching to MSBuild (which I believe is not available for native VC++) or some other make-like build tool?</p>
2
2008-09-24T23:28:24Z
135,078
<p>You might want to look into PropertySheets. These are files containing Visual C++ settings, including user macros. The sheets can inherit from other sheets and are attached to VC++ projects using the PropertyManager View in Visual Studio. When you create one of these sheets, there is an interface for creating user macros. When you add a macro using this mechanism, there is a checkbox for setting the user macro as an environment variable. We use this type of mechanism in our build system to rapidly set up projects to perform out-of-place builds. Our various build directories are all defined as user macros. I have not actually verified that the environment variables are set in an external script called from post-build. I tend to use these macros as command line arguments to my post-build scripts - but I would expect accessing them as environment variables should work for you.</p>
2
2008-09-25T18:29:30Z
[ "python", "visual-studio", "visual-studio-2008", "visual-c++", "visual-studio-2005" ]
How to pass all Visual Studio 2008 "Macros" to Python script?
130,587
<p><em>[NOTE: This questions is similar to but <strong>not the same</strong> as <a href="http://stackoverflow.com/questions/128634/how-to-use-system-environment-variables-in-vs-2008-post-build-events">this one</a>.]</em></p> <p>Visual Studio defines several dozen "Macros" which are sort of simulated environment variables (completely unrelated to C++ macros) which contain information about the build in progress. Examples:</p> <pre> ConfigurationName Release TargetPath D:\work\foo\win\Release\foo.exe VCInstallDir C:\ProgramFiles\Microsoft Visual Studio 9.0\VC\ </pre> <p>Here is the complete set of 43 built-in Macros that I see (yours may differ depending on which version of VS you use and which tools you have enabled):</p> <pre> ConfigurationName IntDir RootNamespace TargetFileName DevEnvDir OutDir SafeInputName TargetFramework FrameworkDir ParentName SafeParentName TargetName FrameworkSDKDir PlatformName SafeRootNamespace TargetPath FrameworkVersion ProjectDir SolutionDir VCInstallDir FxCopDir ProjectExt SolutionExt VSInstallDir InputDir ProjectFileName SolutionFileName WebDeployPath InputExt ProjectName SolutionName WebDeployRoot InputFileName ProjectPath SolutionPath WindowsSdkDir InputName References TargetDir WindowsSdkDirIA64 InputPath RemoteMachine TargetExt </pre> <p>Of these, only four (<code>FrameworkDir</code>, <code>FrameworkSDKDir</code>, <code>VCInstallDir</code> and <code>VSInstallDir</code>) are set in the environment used for build-events.</p> <p>As Brian mentions, user-defined Macros can be defined such as to be set in the environment in which build tasks execute. My problem is with the built-in Macros.</p> <p>I use a Visual Studio Post-Build Event to run a python script as part of my build process. I'd like to pass the entire set of Macros (built-in and user-defined) to my script in the environment but I don't know how. Within my script I can access regular environment variables (e.g., Path, SystemRoot) but NOT these "Macros". All I can do now is pass them on-by-one as named options which I then process within my script. For example, this is what my Post-Build Event command line looks like:</p> <pre> postbuild.py --t="$(TargetPath)" --c="$(ConfigurationName)" </pre> <p>Besides being a pain in the neck, there is a limit on the size of Post-Build Event command line so I can't pass dozens Macros using this method even if I wanted to because the command line is truncated.</p> <p>Does anyone know if there is a way to pass the entire set of Macro names and values to a command that does NOT require switching to MSBuild (which I believe is not available for native VC++) or some other make-like build tool?</p>
2
2008-09-24T23:28:24Z
4,695,601
<p>As far as I can tell, the method described in the question is the only way to pass build variables to a Python script.</p> <p>Perhaps Visual Studio 2010 has something better?</p>
0
2011-01-14T20:28:15Z
[ "python", "visual-studio", "visual-studio-2008", "visual-c++", "visual-studio-2005" ]
Python Date Comparisons
130,618
<p>I would like to find out if a particular python datetime object is older than X hours or minutes. I am trying to do something similar to: </p> <pre><code>if (datetime.now() - self.timestamp) &gt; 100 # Where 100 is either seconds or minutes </code></pre> <p>This generates a type error. </p> <p>What is the proper way to do date time comparison in python? I already looked at <a href="http://wiki.python.org/moin/WorkingWithTime">WorkingWithTime</a> which is close but not exactly what I want. I assume I just want the datetime object represented in seconds so that I can do a normal int comparison. </p> <p>Please post lists of datetime best practices.</p>
57
2008-09-24T23:34:31Z
130,623
<p>You can subtract two <a href="http://docs.python.org/lib/module-datetime.html" rel="nofollow">datetime</a> objects to find the difference between them.<br /> You can use <code>datetime.fromtimestamp</code> to parse a POSIX time stamp.</p>
0
2008-09-24T23:35:26Z
[ "python", "datetime" ]
Python Date Comparisons
130,618
<p>I would like to find out if a particular python datetime object is older than X hours or minutes. I am trying to do something similar to: </p> <pre><code>if (datetime.now() - self.timestamp) &gt; 100 # Where 100 is either seconds or minutes </code></pre> <p>This generates a type error. </p> <p>What is the proper way to do date time comparison in python? I already looked at <a href="http://wiki.python.org/moin/WorkingWithTime">WorkingWithTime</a> which is close but not exactly what I want. I assume I just want the datetime object represented in seconds so that I can do a normal int comparison. </p> <p>Please post lists of datetime best practices.</p>
57
2008-09-24T23:34:31Z
130,647
<p>You can use a combination of the 'days' and 'seconds' attributes of the returned object to figure out the answer, like this:</p> <pre><code>def seconds_difference(stamp1, stamp2): delta = stamp1 - stamp2 return 24*60*60*delta.days + delta.seconds + delta.microseconds/1000000. </code></pre> <p>Use abs() in the answer if you always want a positive number of seconds.</p> <p>To discover how many seconds into the past a timestamp is, you can use it like this:</p> <pre><code>if seconds_difference(datetime.datetime.now(), timestamp) &lt; 100: pass </code></pre>
1
2008-09-24T23:40:43Z
[ "python", "datetime" ]
Python Date Comparisons
130,618
<p>I would like to find out if a particular python datetime object is older than X hours or minutes. I am trying to do something similar to: </p> <pre><code>if (datetime.now() - self.timestamp) &gt; 100 # Where 100 is either seconds or minutes </code></pre> <p>This generates a type error. </p> <p>What is the proper way to do date time comparison in python? I already looked at <a href="http://wiki.python.org/moin/WorkingWithTime">WorkingWithTime</a> which is close but not exactly what I want. I assume I just want the datetime object represented in seconds so that I can do a normal int comparison. </p> <p>Please post lists of datetime best practices.</p>
57
2008-09-24T23:34:31Z
130,652
<p>Compare the difference to a timedelta that you create:</p> <pre><code>if datetime.datetime.now() - timestamp &gt; datetime.timedelta(seconds = 5): print 'older' </code></pre>
5
2008-09-24T23:42:01Z
[ "python", "datetime" ]
Python Date Comparisons
130,618
<p>I would like to find out if a particular python datetime object is older than X hours or minutes. I am trying to do something similar to: </p> <pre><code>if (datetime.now() - self.timestamp) &gt; 100 # Where 100 is either seconds or minutes </code></pre> <p>This generates a type error. </p> <p>What is the proper way to do date time comparison in python? I already looked at <a href="http://wiki.python.org/moin/WorkingWithTime">WorkingWithTime</a> which is close but not exactly what I want. I assume I just want the datetime object represented in seconds so that I can do a normal int comparison. </p> <p>Please post lists of datetime best practices.</p>
57
2008-09-24T23:34:31Z
130,665
<p>Use the <code>datetime.timedelta</code> class:</p> <pre><code>&gt;&gt;&gt; from datetime import datetime, timedelta &gt;&gt;&gt; then = datetime.now() - timedelta(hours = 2) &gt;&gt;&gt; now = datetime.now() &gt;&gt;&gt; (now - then) &gt; timedelta(days = 1) False &gt;&gt;&gt; (now - then) &gt; timedelta(hours = 1) True </code></pre> <p>Your example could be written as:</p> <pre><code>if (datetime.now() - self.timestamp) &gt; timedelta(seconds = 100) </code></pre> <p>or</p> <pre><code>if (datetime.now() - self.timestamp) &gt; timedelta(minutes = 100) </code></pre>
102
2008-09-24T23:44:27Z
[ "python", "datetime" ]
Python Date Comparisons
130,618
<p>I would like to find out if a particular python datetime object is older than X hours or minutes. I am trying to do something similar to: </p> <pre><code>if (datetime.now() - self.timestamp) &gt; 100 # Where 100 is either seconds or minutes </code></pre> <p>This generates a type error. </p> <p>What is the proper way to do date time comparison in python? I already looked at <a href="http://wiki.python.org/moin/WorkingWithTime">WorkingWithTime</a> which is close but not exactly what I want. I assume I just want the datetime object represented in seconds so that I can do a normal int comparison. </p> <p>Please post lists of datetime best practices.</p>
57
2008-09-24T23:34:31Z
130,669
<p>Like so:</p> <pre><code># self.timestamp should be a datetime object if (datetime.now() - self.timestamp).seconds &gt; 100: print "object is over 100 seconds old" </code></pre>
0
2008-09-24T23:45:28Z
[ "python", "datetime" ]
Python Date Comparisons
130,618
<p>I would like to find out if a particular python datetime object is older than X hours or minutes. I am trying to do something similar to: </p> <pre><code>if (datetime.now() - self.timestamp) &gt; 100 # Where 100 is either seconds or minutes </code></pre> <p>This generates a type error. </p> <p>What is the proper way to do date time comparison in python? I already looked at <a href="http://wiki.python.org/moin/WorkingWithTime">WorkingWithTime</a> which is close but not exactly what I want. I assume I just want the datetime object represented in seconds so that I can do a normal int comparison. </p> <p>Please post lists of datetime best practices.</p>
57
2008-09-24T23:34:31Z
10,546,316
<p>Alternative:</p> <pre><code>if (datetime.now() - self.timestamp).total_seconds() &gt; 100: </code></pre> <p>Assuming self.timestamp is an datetime instance</p>
5
2012-05-11T06:14:38Z
[ "python", "datetime" ]
Request UAC elevation from within a Python script?
130,763
<p>I want my Python script to copy files on Vista. When I run it from a normal <code>cmd.exe</code> window, no errors are generated, yet the files are NOT copied. If I run <code>cmd.exe</code> "as administator" and then run my script, it works fine.</p> <p>This makes sense since User Account Control (UAC) normally prevents many file system actions.</p> <p>Is there a way I can, from within a Python script, invoke a UAC elevation request (those dialogs that say something like "such and such app needs admin access, is this OK?")</p> <p>If that's not possible, is there a way my script can at least detect that it is not elevated so it can fail gracefully?</p>
49
2008-09-25T00:22:26Z
131,092
<p>It seems there's no way to elevate the application privileges for a while for you to perform a particular task. Windows needs to know at the start of the program whether the application requires certain privileges, and will ask the user to confirm when the application performs any tasks that <em>need</em> those privileges. There are two ways to do this:</p> <ol> <li>Write a manifest file that tells Windows the application might require some privileges</li> <li>Run the application with elevated privileges from inside another program</li> </ol> <p>This <a href="http://www.codeproject.com/KB/vista-security/UAC__The_Definitive_Guide.aspx">two</a> <a href="http://msdn.microsoft.com/en-gb/magazine/cc163486.aspx">articles</a> explain in much more detail how this works.</p> <p>What I'd do, if you don't want to write a nasty ctypes wrapper for the CreateElevatedProcess API, is use the ShellExecuteEx trick explained in the Code Project article (Pywin32 comes with a wrapper for ShellExecute). How? Something like this:</p> <p>When your program starts, it checks if it has Administrator privileges, if it doesn't it runs itself using the ShellExecute trick and exits immediately, if it does, it performs the task at hand.</p> <p>As you describe your program as a "script", I suppose that's enough for your needs.</p> <p>Cheers.</p>
28
2008-09-25T02:01:34Z
[ "python", "windows", "windows-vista", "uac" ]
Request UAC elevation from within a Python script?
130,763
<p>I want my Python script to copy files on Vista. When I run it from a normal <code>cmd.exe</code> window, no errors are generated, yet the files are NOT copied. If I run <code>cmd.exe</code> "as administator" and then run my script, it works fine.</p> <p>This makes sense since User Account Control (UAC) normally prevents many file system actions.</p> <p>Is there a way I can, from within a Python script, invoke a UAC elevation request (those dialogs that say something like "such and such app needs admin access, is this OK?")</p> <p>If that's not possible, is there a way my script can at least detect that it is not elevated so it can fail gracefully?</p>
49
2008-09-25T00:22:26Z
138,970
<p>If your script always requires an Administrator's privileges then: </p> <pre><code>runas /user:Administrator "python your_script.py" </code></pre>
0
2008-09-26T11:54:18Z
[ "python", "windows", "windows-vista", "uac" ]
Request UAC elevation from within a Python script?
130,763
<p>I want my Python script to copy files on Vista. When I run it from a normal <code>cmd.exe</code> window, no errors are generated, yet the files are NOT copied. If I run <code>cmd.exe</code> "as administator" and then run my script, it works fine.</p> <p>This makes sense since User Account Control (UAC) normally prevents many file system actions.</p> <p>Is there a way I can, from within a Python script, invoke a UAC elevation request (those dialogs that say something like "such and such app needs admin access, is this OK?")</p> <p>If that's not possible, is there a way my script can at least detect that it is not elevated so it can fail gracefully?</p>
49
2008-09-25T00:22:26Z
3,787,689
<p>This may not completely answer your question but you could also try using the Elevate Command Powertoy in order to run the script with elevated UAC privileges.</p> <p><a href="http://technet.microsoft.com/en-us/magazine/2008.06.elevation.aspx" rel="nofollow">http://technet.microsoft.com/en-us/magazine/2008.06.elevation.aspx</a></p> <p>I think if you use it it would look like 'elevate python yourscript.py'</p>
2
2010-09-24T13:43:33Z
[ "python", "windows", "windows-vista", "uac" ]
Request UAC elevation from within a Python script?
130,763
<p>I want my Python script to copy files on Vista. When I run it from a normal <code>cmd.exe</code> window, no errors are generated, yet the files are NOT copied. If I run <code>cmd.exe</code> "as administator" and then run my script, it works fine.</p> <p>This makes sense since User Account Control (UAC) normally prevents many file system actions.</p> <p>Is there a way I can, from within a Python script, invoke a UAC elevation request (those dialogs that say something like "such and such app needs admin access, is this OK?")</p> <p>If that's not possible, is there a way my script can at least detect that it is not elevated so it can fail gracefully?</p>
49
2008-09-25T00:22:26Z
11,746,382
<p>It took me a little while to get dguaraglia's answer working, so in the interest of saving others time, here's what I did to implement this idea:</p> <pre><code>import os import sys import win32com.shell.shell as shell ASADMIN = 'asadmin' if sys.argv[-1] != ASADMIN: script = os.path.abspath(sys.argv[0]) params = ' '.join([script] + sys.argv[1:] + [ASADMIN]) shell.ShellExecuteEx(lpVerb='runas', lpFile=sys.executable, lpParameters=params) sys.exit(0) </code></pre>
49
2012-07-31T18:09:35Z
[ "python", "windows", "windows-vista", "uac" ]
Request UAC elevation from within a Python script?
130,763
<p>I want my Python script to copy files on Vista. When I run it from a normal <code>cmd.exe</code> window, no errors are generated, yet the files are NOT copied. If I run <code>cmd.exe</code> "as administator" and then run my script, it works fine.</p> <p>This makes sense since User Account Control (UAC) normally prevents many file system actions.</p> <p>Is there a way I can, from within a Python script, invoke a UAC elevation request (those dialogs that say something like "such and such app needs admin access, is this OK?")</p> <p>If that's not possible, is there a way my script can at least detect that it is not elevated so it can fail gracefully?</p>
49
2008-09-25T00:22:26Z
22,821,704
<p>You can make a shortcut somewhere and as the target use: python yourscript.py then under properties and advanced select run as administrator. </p> <p>When the user executes the shortcut it will ask them to elevate the application.</p>
1
2014-04-02T19:56:40Z
[ "python", "windows", "windows-vista", "uac" ]
Request UAC elevation from within a Python script?
130,763
<p>I want my Python script to copy files on Vista. When I run it from a normal <code>cmd.exe</code> window, no errors are generated, yet the files are NOT copied. If I run <code>cmd.exe</code> "as administator" and then run my script, it works fine.</p> <p>This makes sense since User Account Control (UAC) normally prevents many file system actions.</p> <p>Is there a way I can, from within a Python script, invoke a UAC elevation request (those dialogs that say something like "such and such app needs admin access, is this OK?")</p> <p>If that's not possible, is there a way my script can at least detect that it is not elevated so it can fail gracefully?</p>
49
2008-09-25T00:22:26Z
32,230,199
<p>Recognizing this question was asked years ago, I think a more elegant solution is offered on <a href="https://github.com/frmdstryr/pywinutils" rel="nofollow">github</a> by frmdstryr using his module pyminutils: </p> <p>Excerpt:</p> <pre><code>import pythoncom from win32com.shell import shell,shellcon def copy(src,dst,flags=shellcon.FOF_NOCONFIRMATION): """ Copy files using the built in Windows File copy dialog Requires absolute paths. Does NOT create root destination folder if it doesn't exist. Overwrites and is recursive by default @see http://msdn.microsoft.com/en-us/library/bb775799(v=vs.85).aspx for flags available """ # @see IFileOperation pfo = pythoncom.CoCreateInstance(shell.CLSID_FileOperation,None,pythoncom.CLSCTX_ALL,shell.IID_IFileOperation) # Respond with Yes to All for any dialog # @see http://msdn.microsoft.com/en-us/library/bb775799(v=vs.85).aspx pfo.SetOperationFlags(flags) # Set the destionation folder dst = shell.SHCreateItemFromParsingName(dst,None,shell.IID_IShellItem) if type(src) not in (tuple,list): src = (src,) for f in src: item = shell.SHCreateItemFromParsingName(f,None,shell.IID_IShellItem) pfo.CopyItem(item,dst) # Schedule an operation to be performed # @see http://msdn.microsoft.com/en-us/library/bb775780(v=vs.85).aspx success = pfo.PerformOperations() # @see sdn.microsoft.com/en-us/library/bb775769(v=vs.85).aspx aborted = pfo.GetAnyOperationsAborted() return success is None and not aborted </code></pre> <p>This utilizes the COM interface and automatically indicates that admin privileges are needed with the familiar dialog prompt that you would see if you were copying into a directory where admin privileges are required and also provides the typical file progress dialog during the copy operation.</p>
2
2015-08-26T15:03:36Z
[ "python", "windows", "windows-vista", "uac" ]
Request UAC elevation from within a Python script?
130,763
<p>I want my Python script to copy files on Vista. When I run it from a normal <code>cmd.exe</code> window, no errors are generated, yet the files are NOT copied. If I run <code>cmd.exe</code> "as administator" and then run my script, it works fine.</p> <p>This makes sense since User Account Control (UAC) normally prevents many file system actions.</p> <p>Is there a way I can, from within a Python script, invoke a UAC elevation request (those dialogs that say something like "such and such app needs admin access, is this OK?")</p> <p>If that's not possible, is there a way my script can at least detect that it is not elevated so it can fail gracefully?</p>
49
2008-09-25T00:22:26Z
34,216,774
<p>A variation on Jorenko's work above allows the elevated process to use the same console (but see my comment below):</p> <pre><code>def spawn_as_administrator(): """ Spawn ourself with administrator rights and wait for new process to exit Make the new process use the same console as the old one. Raise Exception() if we could not get a handle for the new re-run the process Raise pywintypes.error() if we could not re-spawn Return the exit code of the new process, or return None if already running the second admin process. """ #pylint: disable=no-name-in-module,import-error import win32event, win32api, win32process import win32com.shell.shell as shell if '--admin' in sys.argv: return None script = os.path.abspath(sys.argv[0]) params = ' '.join([script] + sys.argv[1:] + ['--admin']) SEE_MASK_NO_CONSOLE = 0x00008000 SEE_MASK_NOCLOSE_PROCESS = 0x00000040 process = shell.ShellExecuteEx(lpVerb='runas', lpFile=sys.executable, lpParameters=params, fMask=SEE_MASK_NO_CONSOLE|SEE_MASK_NOCLOSE_PROCESS) hProcess = process['hProcess'] if not hProcess: raise Exception("Could not identify administrator process to install drivers") # It is necessary to wait for the elevated process or else # stdin lines are shared between 2 processes: they get one line each INFINITE = -1 win32event.WaitForSingleObject(hProcess, INFINITE) exitcode = win32process.GetExitCodeProcess(hProcess) win32api.CloseHandle(hProcess) return exitcode </code></pre>
1
2015-12-11T05:34:25Z
[ "python", "windows", "windows-vista", "uac" ]
Style - When to serialize a Django model Instance: signals vs model's save method
131,327
<p>I plan to serialize a Django model to XML when it's saved or updated. (The XML's going to be imported into a flash movie). Is it better to listen for a post_save() or pre_save() signal and then perform the serialization, or to just handle it in the model's save() methon</p>
1
2008-09-25T03:25:52Z
131,383
<p>Post save. That way the new data (the reason for performing the serialization) is already in the database. It'll make for a much cleaner bit of code that simply takes from the database and doesn't have to worry about adding an extra value.</p> <p>The other way that comes to mind is to maintain the xml file in parallel to the database. That is to say, in your save() add the data to the database, and to the xml file. This would have a much less overhead if you're dealing with huge tables.</p>
0
2008-09-25T03:43:34Z
[ "python", "django" ]
Style - When to serialize a Django model Instance: signals vs model's save method
131,327
<p>I plan to serialize a Django model to XML when it's saved or updated. (The XML's going to be imported into a flash movie). Is it better to listen for a post_save() or pre_save() signal and then perform the serialization, or to just handle it in the model's save() methon</p>
1
2008-09-25T03:25:52Z
136,399
<p>If it's core functionality for saving the model you'll want it as part of the save method. However, if you already have a functioning model and you want to extend it for other purposes then signals are your best bet since they allow for properly decoupled modules.</p> <p>A good example might be that you want to add event logging to your site, so you simply listen for the signals that signify an event rather than modifying the original site code.</p> <p>post_save() is usually best because it means the model has been successfully saved, using pre_save() doesn't guarantee that the save will be successful so shouldn't be used for anything that would depend on the save being completed.</p>
2
2008-09-25T21:49:44Z
[ "python", "django" ]
Do I have to cause an ValueError in Python
131,449
<p>I have this code:</p> <pre><code>chars = #some list try: indx = chars.index(chars) except ValueError: #doSomething else: #doSomethingElse </code></pre> <p>I want to be able to do this because I don't like knowfully causing Exceptions:</p> <pre><code>chars = #some list indx = chars.index(chars) if indx == -1: #doSomething else: #doSomethingElse </code></pre> <p>Is there a way I can do this?</p>
3
2008-09-25T04:14:34Z
131,452
<pre><code>if element in mylist: index = mylist.index(element) # ... do something else: # ... do something else </code></pre>
7
2008-09-25T04:16:25Z
[ "python", "exception", "list" ]
Do I have to cause an ValueError in Python
131,449
<p>I have this code:</p> <pre><code>chars = #some list try: indx = chars.index(chars) except ValueError: #doSomething else: #doSomethingElse </code></pre> <p>I want to be able to do this because I don't like knowfully causing Exceptions:</p> <pre><code>chars = #some list indx = chars.index(chars) if indx == -1: #doSomething else: #doSomethingElse </code></pre> <p>Is there a way I can do this?</p>
3
2008-09-25T04:14:34Z
131,522
<p>Note that the latter approach is going against the generally accepted "pythonic" philosophy of <a href="http://en.wikipedia.org/wiki/Python_syntax_and_semantics#Exceptions" rel="nofollow">EAFP, or "It is Easier to Ask for Forgiveness than Permission."</a>, while the former follows it.</p>
9
2008-09-25T04:47:35Z
[ "python", "exception", "list" ]
Do I have to cause an ValueError in Python
131,449
<p>I have this code:</p> <pre><code>chars = #some list try: indx = chars.index(chars) except ValueError: #doSomething else: #doSomethingElse </code></pre> <p>I want to be able to do this because I don't like knowfully causing Exceptions:</p> <pre><code>chars = #some list indx = chars.index(chars) if indx == -1: #doSomething else: #doSomethingElse </code></pre> <p>Is there a way I can do this?</p>
3
2008-09-25T04:14:34Z
131,930
<p>For the specific case where your list is a sequence of single-character strings you can get what you want by changing the list to be searched to a string in advance (eg. ''.join(chars)).</p> <p>You can then use the .find() method, which does work as you want. However, there's no corresponding method for lists or tuples.</p> <p>Another possible option is to use a dictionary instead. eg.</p> <pre><code>d = dict((x, loc) for (loc,x) in enumerate(chars)) ... index = d.get(chars_to_find, -1) # Second argument is default if not found. </code></pre> <p>This may also perform better if you're doing a lot of searches on the list. If it's just a single search on a throwaway list though, its not worth doing.</p>
0
2008-09-25T07:27:39Z
[ "python", "exception", "list" ]
Showing the stack trace from a running Python application
132,058
<p>I have this Python application that gets stuck from time to time and I can't find out where.</p> <p>Is there any way to signal Python interpreter to show you the exact code that's running? </p> <p>Some kind of on-the-fly stacktrace?</p> <p><strong><em>Related questions:</em></strong></p> <ul> <li><a href="http://stackoverflow.com/questions/1156023/print-current-call-stack-from-a-method-in-python-code">Print current call stack from a method in Python code</a></li> <li><a href="http://stackoverflow.com/questions/6849138/check-what-a-running-process-is-doing-print-stack-trace-of-an-uninstrumented-py">Check what a running process is doing: print stack trace of an uninstrumented Python program</a></li> </ul>
250
2008-09-25T08:06:06Z
132,108
<p><em>python -dv yourscript.py</em></p> <p>That will make the interpreter to run in debug mode and to give you a trace of what the interpreter is doing.</p> <p>If you want to interactively debug the code you should run it like this:</p> <p><em>python -m pdb yourscript.py</em></p> <p>That tells the python interpreter to run your script with the module "pdb" which is the python debugger, if you run it like that the interpreter will be executed in interactive mode, much like GDB</p>
10
2008-09-25T08:24:24Z
[ "python", "debugging", "stack-trace", "traceback" ]
Showing the stack trace from a running Python application
132,058
<p>I have this Python application that gets stuck from time to time and I can't find out where.</p> <p>Is there any way to signal Python interpreter to show you the exact code that's running? </p> <p>Some kind of on-the-fly stacktrace?</p> <p><strong><em>Related questions:</em></strong></p> <ul> <li><a href="http://stackoverflow.com/questions/1156023/print-current-call-stack-from-a-method-in-python-code">Print current call stack from a method in Python code</a></li> <li><a href="http://stackoverflow.com/questions/6849138/check-what-a-running-process-is-doing-print-stack-trace-of-an-uninstrumented-py">Check what a running process is doing: print stack trace of an uninstrumented Python program</a></li> </ul>
250
2008-09-25T08:06:06Z
132,114
<p>The <a href="http://www.python.org/doc/2.5.2/lib/module-traceback.html"><strong>traceback</strong></a> module has some nice functions, among them: print_stack:</p> <pre><code>import traceback traceback.print_stack() </code></pre>
24
2008-09-25T08:27:16Z
[ "python", "debugging", "stack-trace", "traceback" ]
Showing the stack trace from a running Python application
132,058
<p>I have this Python application that gets stuck from time to time and I can't find out where.</p> <p>Is there any way to signal Python interpreter to show you the exact code that's running? </p> <p>Some kind of on-the-fly stacktrace?</p> <p><strong><em>Related questions:</em></strong></p> <ul> <li><a href="http://stackoverflow.com/questions/1156023/print-current-call-stack-from-a-method-in-python-code">Print current call stack from a method in Python code</a></li> <li><a href="http://stackoverflow.com/questions/6849138/check-what-a-running-process-is-doing-print-stack-trace-of-an-uninstrumented-py">Check what a running process is doing: print stack trace of an uninstrumented Python program</a></li> </ul>
250
2008-09-25T08:06:06Z
132,123
<pre><code>&gt;&gt;&gt; import traceback &gt;&gt;&gt; def x(): &gt;&gt;&gt; print traceback.extract_stack() &gt;&gt;&gt; x() [('&lt;stdin&gt;', 1, '&lt;module&gt;', None), ('&lt;stdin&gt;', 2, 'x', None)] </code></pre> <p>You can also nicely format the stack trace, see the <a href="http://docs.python.org/lib/module-traceback.html">docs</a>.</p> <p><strong>Edit</strong>: To simulate Java's behavior, as suggested by @<a href="#132260">Douglas Leeder</a>, add this:</p> <pre><code>import signal import traceback signal.signal(signal.SIGUSR1, lambda sig, stack: traceback.print_stack(stack)) </code></pre> <p>to the startup code in your application. Then you can print the stack by sending <code>SIGUSR1</code> to the running Python process.</p>
31
2008-09-25T08:29:32Z
[ "python", "debugging", "stack-trace", "traceback" ]
Showing the stack trace from a running Python application
132,058
<p>I have this Python application that gets stuck from time to time and I can't find out where.</p> <p>Is there any way to signal Python interpreter to show you the exact code that's running? </p> <p>Some kind of on-the-fly stacktrace?</p> <p><strong><em>Related questions:</em></strong></p> <ul> <li><a href="http://stackoverflow.com/questions/1156023/print-current-call-stack-from-a-method-in-python-code">Print current call stack from a method in Python code</a></li> <li><a href="http://stackoverflow.com/questions/6849138/check-what-a-running-process-is-doing-print-stack-trace-of-an-uninstrumented-py">Check what a running process is doing: print stack trace of an uninstrumented Python program</a></li> </ul>
250
2008-09-25T08:06:06Z
132,260
<p>I don't know of anything similar to <a href="http://java.sun.com/developer/onlineTraining/Programming/JDCBook/stack.html" rel="nofollow">java's response to SIGQUIT</a>, so you might have to build it in to your application. Maybe you could make a server in another thread that can get a stacktrace on response to a message of some kind?</p>
0
2008-09-25T09:06:39Z
[ "python", "debugging", "stack-trace", "traceback" ]
Showing the stack trace from a running Python application
132,058
<p>I have this Python application that gets stuck from time to time and I can't find out where.</p> <p>Is there any way to signal Python interpreter to show you the exact code that's running? </p> <p>Some kind of on-the-fly stacktrace?</p> <p><strong><em>Related questions:</em></strong></p> <ul> <li><a href="http://stackoverflow.com/questions/1156023/print-current-call-stack-from-a-method-in-python-code">Print current call stack from a method in Python code</a></li> <li><a href="http://stackoverflow.com/questions/6849138/check-what-a-running-process-is-doing-print-stack-trace-of-an-uninstrumented-py">Check what a running process is doing: print stack trace of an uninstrumented Python program</a></li> </ul>
250
2008-09-25T08:06:06Z
132,268
<p>There is no way to hook into a running python process and get reasonable results. What I do if processes lock up is hooking strace in and trying to figure out what exactly is happening.</p> <p>Unfortunately often strace is the observer that "fixes" race conditions so that the output is useless there too.</p>
1
2008-09-25T09:09:54Z
[ "python", "debugging", "stack-trace", "traceback" ]
Showing the stack trace from a running Python application
132,058
<p>I have this Python application that gets stuck from time to time and I can't find out where.</p> <p>Is there any way to signal Python interpreter to show you the exact code that's running? </p> <p>Some kind of on-the-fly stacktrace?</p> <p><strong><em>Related questions:</em></strong></p> <ul> <li><a href="http://stackoverflow.com/questions/1156023/print-current-call-stack-from-a-method-in-python-code">Print current call stack from a method in Python code</a></li> <li><a href="http://stackoverflow.com/questions/6849138/check-what-a-running-process-is-doing-print-stack-trace-of-an-uninstrumented-py">Check what a running process is doing: print stack trace of an uninstrumented Python program</a></li> </ul>
250
2008-09-25T08:06:06Z
133,384
<p>I have module I use for situations like this - where a process will be running for a long time but gets stuck sometimes for unknown and irreproducible reasons. Its a bit hacky, and only works on unix (requires signals):</p> <pre><code>import code, traceback, signal def debug(sig, frame): """Interrupt running process, and provide a python prompt for interactive debugging.""" d={'_frame':frame} # Allow access to frame object. d.update(frame.f_globals) # Unless shadowed by global d.update(frame.f_locals) i = code.InteractiveConsole(d) message = "Signal received : entering python shell.\nTraceback:\n" message += ''.join(traceback.format_stack(frame)) i.interact(message) def listen(): signal.signal(signal.SIGUSR1, debug) # Register handler </code></pre> <p>To use, just call the listen() function at some point when your program starts up (You could even stick it in site.py to have all python programs use it), and let it run. At any point, send the process a SIGUSR1 signal, using kill, or in python:</p> <pre><code> os.kill(pid, signal.SIGUSR1) </code></pre> <p>This will cause the program to break to a python console at the point it is currently at, showing you the stack trace, and letting you manipulate the variables. Use control-d (EOF) to continue running (though note that you will probably interrupt any I/O etc at the point you signal, so it isn't fully non-intrusive.</p> <p>I've another script that does the same thing, except it communicates with the running process through a pipe (to allow for debugging backgrounded processes etc). Its a bit large to post here, but I've added it as a <a href="http://code.activestate.com/recipes/576515/">python cookbook recipe</a>.</p>
251
2008-09-25T13:38:45Z
[ "python", "debugging", "stack-trace", "traceback" ]
Showing the stack trace from a running Python application
132,058
<p>I have this Python application that gets stuck from time to time and I can't find out where.</p> <p>Is there any way to signal Python interpreter to show you the exact code that's running? </p> <p>Some kind of on-the-fly stacktrace?</p> <p><strong><em>Related questions:</em></strong></p> <ul> <li><a href="http://stackoverflow.com/questions/1156023/print-current-call-stack-from-a-method-in-python-code">Print current call stack from a method in Python code</a></li> <li><a href="http://stackoverflow.com/questions/6849138/check-what-a-running-process-is-doing-print-stack-trace-of-an-uninstrumented-py">Check what a running process is doing: print stack trace of an uninstrumented Python program</a></li> </ul>
250
2008-09-25T08:06:06Z
147,114
<p>The suggestion to install a signal handler is a good one, and I use it a lot. For example, <a href="http://bazaar-vcs.org/">bzr</a> by default installs a SIGQUIT handler that invokes <code>pdb.set_trace()</code> to immediately drop you into a <a href="http://docs.python.org/lib/module-pdb.html">pdb</a> prompt. (See the <a href="https://bazaar.launchpad.net/~bzr-pqm/bzr/bzr.dev/view/head:/bzrlib/breakin.py">bzrlib.breakin</a> module's source for the exact details.) With pdb you can not only get the current stack trace but also inspect variables, etc. </p> <p>However, sometimes I need to debug a process that I didn't have the foresight to install the signal handler in. On linux, you can attach gdb to the process and get a python stack trace with some gdb macros. Put <a href="http://svn.python.org/projects/python/trunk/Misc/gdbinit">http://svn.python.org/projects/python/trunk/Misc/gdbinit</a> in <code>~/.gdbinit</code>, then:</p> <ul> <li>Attach gdb: <code>gdb -p</code> <em><code>PID</code></em></li> <li>Get the python stack trace: <code>pystack</code></li> </ul> <p>It's not totally reliable unfortunately, but it works most of the time.</p> <p>Finally, attaching <code>strace</code> can often give you a good idea what a process is doing.</p>
118
2008-09-29T00:44:13Z
[ "python", "debugging", "stack-trace", "traceback" ]
Showing the stack trace from a running Python application
132,058
<p>I have this Python application that gets stuck from time to time and I can't find out where.</p> <p>Is there any way to signal Python interpreter to show you the exact code that's running? </p> <p>Some kind of on-the-fly stacktrace?</p> <p><strong><em>Related questions:</em></strong></p> <ul> <li><a href="http://stackoverflow.com/questions/1156023/print-current-call-stack-from-a-method-in-python-code">Print current call stack from a method in Python code</a></li> <li><a href="http://stackoverflow.com/questions/6849138/check-what-a-running-process-is-doing-print-stack-trace-of-an-uninstrumented-py">Check what a running process is doing: print stack trace of an uninstrumented Python program</a></li> </ul>
250
2008-09-25T08:06:06Z
490,172
<p>It's worth looking at <a href="http://bashdb.sourceforge.net/pydb/" rel="nofollow">Pydb</a>, "an expanded version of the Python debugger loosely based on the gdb command set". It includes signal managers which can take care of starting the debugger when a specified signal is sent.</p> <p>A 2006 Summer of Code project looked at adding remote-debugging features to pydb in a module called <a href="http://svn.python.org/projects/sandbox/trunk/pdb/" rel="nofollow">mpdb</a>. </p>
3
2009-01-29T01:28:29Z
[ "python", "debugging", "stack-trace", "traceback" ]
Showing the stack trace from a running Python application
132,058
<p>I have this Python application that gets stuck from time to time and I can't find out where.</p> <p>Is there any way to signal Python interpreter to show you the exact code that's running? </p> <p>Some kind of on-the-fly stacktrace?</p> <p><strong><em>Related questions:</em></strong></p> <ul> <li><a href="http://stackoverflow.com/questions/1156023/print-current-call-stack-from-a-method-in-python-code">Print current call stack from a method in Python code</a></li> <li><a href="http://stackoverflow.com/questions/6849138/check-what-a-running-process-is-doing-print-stack-trace-of-an-uninstrumented-py">Check what a running process is doing: print stack trace of an uninstrumented Python program</a></li> </ul>
250
2008-09-25T08:06:06Z
618,748
<p>What really helped me here is <a href="http://stackoverflow.com/questions/132058/getting-stack-trace-from-a-running-python-application/147114#147114">spiv's tip</a> (which I would vote up and comment on if I had the reputation points) for getting a stack trace out of an <em>unprepared</em> Python process. Except it didn't work until I <a href="http://lists.osafoundation.org/pipermail/chandler-dev/2007-January/007519.html">modified the gdbinit script</a>. So:</p> <ul> <li><p>download <a href="http://svn.python.org/projects/python/trunk/Misc/gdbinit">http://svn.python.org/projects/python/trunk/Misc/gdbinit</a> and put it in <code>~/.gdbinit</code></p></li> <li><p><del>edit it, changing <code>PyEval_EvalFrame</code> to <code>PyEval_EvalFrameEx</code></del> [edit: no longer needed; the linked file already has this change as of 2010-01-14]</p></li> <li><p>Attach gdb: <code>gdb -p PID</code></p></li> <li><p>Get the python stack trace: <code>pystack</code></p></li> </ul>
17
2009-03-06T12:49:11Z
[ "python", "debugging", "stack-trace", "traceback" ]
Showing the stack trace from a running Python application
132,058
<p>I have this Python application that gets stuck from time to time and I can't find out where.</p> <p>Is there any way to signal Python interpreter to show you the exact code that's running? </p> <p>Some kind of on-the-fly stacktrace?</p> <p><strong><em>Related questions:</em></strong></p> <ul> <li><a href="http://stackoverflow.com/questions/1156023/print-current-call-stack-from-a-method-in-python-code">Print current call stack from a method in Python code</a></li> <li><a href="http://stackoverflow.com/questions/6849138/check-what-a-running-process-is-doing-print-stack-trace-of-an-uninstrumented-py">Check what a running process is doing: print stack trace of an uninstrumented Python program</a></li> </ul>
250
2008-09-25T08:06:06Z
1,431,341
<p>use the inspect module.</p> <blockquote> <blockquote> <blockquote> <p>import inspect help(inspect.stack) Help on function stack in module inspect:</p> </blockquote> </blockquote> </blockquote> <p>stack(context=1) Return a list of records for the stack above the caller's frame.</p> <p>I find it very helpful indeed.</p>
0
2009-09-16T06:44:42Z
[ "python", "debugging", "stack-trace", "traceback" ]
Showing the stack trace from a running Python application
132,058
<p>I have this Python application that gets stuck from time to time and I can't find out where.</p> <p>Is there any way to signal Python interpreter to show you the exact code that's running? </p> <p>Some kind of on-the-fly stacktrace?</p> <p><strong><em>Related questions:</em></strong></p> <ul> <li><a href="http://stackoverflow.com/questions/1156023/print-current-call-stack-from-a-method-in-python-code">Print current call stack from a method in Python code</a></li> <li><a href="http://stackoverflow.com/questions/6849138/check-what-a-running-process-is-doing-print-stack-trace-of-an-uninstrumented-py">Check what a running process is doing: print stack trace of an uninstrumented Python program</a></li> </ul>
250
2008-09-25T08:06:06Z
2,569,696
<p>I am almost always dealing with multiple threads and main thread is generally not doing much, so what is most interesting is to dump all the stacks (which is more like the Java's dump). Here is an implementation based on <a href="http://bzimmer.ziclix.com/2008/12/17/python-thread-dumps/">this blog</a>:</p> <pre><code>import threading, sys, traceback def dumpstacks(signal, frame): id2name = dict([(th.ident, th.name) for th in threading.enumerate()]) code = [] for threadId, stack in sys._current_frames().items(): code.append("\n# Thread: %s(%d)" % (id2name.get(threadId,""), threadId)) for filename, lineno, name, line in traceback.extract_stack(stack): code.append('File: "%s", line %d, in %s' % (filename, lineno, name)) if line: code.append(" %s" % (line.strip())) print "\n".join(code) import signal signal.signal(signal.SIGQUIT, dumpstacks) </code></pre>
56
2010-04-02T23:23:47Z
[ "python", "debugging", "stack-trace", "traceback" ]
Showing the stack trace from a running Python application
132,058
<p>I have this Python application that gets stuck from time to time and I can't find out where.</p> <p>Is there any way to signal Python interpreter to show you the exact code that's running? </p> <p>Some kind of on-the-fly stacktrace?</p> <p><strong><em>Related questions:</em></strong></p> <ul> <li><a href="http://stackoverflow.com/questions/1156023/print-current-call-stack-from-a-method-in-python-code">Print current call stack from a method in Python code</a></li> <li><a href="http://stackoverflow.com/questions/6849138/check-what-a-running-process-is-doing-print-stack-trace-of-an-uninstrumented-py">Check what a running process is doing: print stack trace of an uninstrumented Python program</a></li> </ul>
250
2008-09-25T08:06:06Z
5,503,185
<p>I would add this as a comment to <a href="http://stackoverflow.com/questions/132058/getting-stack-trace-from-a-running-python-application/2569696#2569696">haridsv's response</a>, but I lack the reputation to do so:</p> <p>Some of us are still stuck on a version of Python older than 2.6 (required for Thread.ident), so I got the code working in Python 2.5 (though without the thread name being displayed) as such:</p> <pre><code>import traceback import sys def dumpstacks(signal, frame): code = [] for threadId, stack in sys._current_frames().items(): code.append("\n# Thread: %d" % (threadId)) for filename, lineno, name, line in traceback.extract_stack(stack): code.append('File: "%s", line %d, in %s' % (filename, lineno, name)) if line: code.append(" %s" % (line.strip())) print "\n".join(code) import signal signal.signal(signal.SIGQUIT, dumpstacks) </code></pre>
9
2011-03-31T16:30:51Z
[ "python", "debugging", "stack-trace", "traceback" ]
Showing the stack trace from a running Python application
132,058
<p>I have this Python application that gets stuck from time to time and I can't find out where.</p> <p>Is there any way to signal Python interpreter to show you the exact code that's running? </p> <p>Some kind of on-the-fly stacktrace?</p> <p><strong><em>Related questions:</em></strong></p> <ul> <li><a href="http://stackoverflow.com/questions/1156023/print-current-call-stack-from-a-method-in-python-code">Print current call stack from a method in Python code</a></li> <li><a href="http://stackoverflow.com/questions/6849138/check-what-a-running-process-is-doing-print-stack-trace-of-an-uninstrumented-py">Check what a running process is doing: print stack trace of an uninstrumented Python program</a></li> </ul>
250
2008-09-25T08:06:06Z
7,224,091
<p>On Solaris, you can use pstack(1) No changes to the python code are necessary. eg.</p> <pre><code># pstack 16000 | grep : | head 16000: /usr/bin/python2.6 /usr/lib/pkg.depotd --cfg svc:/application/pkg/serv [ /usr/lib/python2.6/vendor-packages/cherrypy/process/wspbus.py:282 (_wait) ] [ /usr/lib/python2.6/vendor-packages/cherrypy/process/wspbus.py:295 (wait) ] [ /usr/lib/python2.6/vendor-packages/cherrypy/process/wspbus.py:242 (block) ] [ /usr/lib/python2.6/vendor-packages/cherrypy/_init_.py:249 (quickstart) ] [ /usr/lib/pkg.depotd:890 (&lt;module&gt;) ] [ /usr/lib/python2.6/threading.py:256 (wait) ] [ /usr/lib/python2.6/Queue.py:177 (get) ] [ /usr/lib/python2.6/vendor-packages/pkg/server/depot.py:2142 (run) ] [ /usr/lib/python2.6/threading.py:477 (run) etc. </code></pre>
6
2011-08-28T21:30:38Z
[ "python", "debugging", "stack-trace", "traceback" ]
Showing the stack trace from a running Python application
132,058
<p>I have this Python application that gets stuck from time to time and I can't find out where.</p> <p>Is there any way to signal Python interpreter to show you the exact code that's running? </p> <p>Some kind of on-the-fly stacktrace?</p> <p><strong><em>Related questions:</em></strong></p> <ul> <li><a href="http://stackoverflow.com/questions/1156023/print-current-call-stack-from-a-method-in-python-code">Print current call stack from a method in Python code</a></li> <li><a href="http://stackoverflow.com/questions/6849138/check-what-a-running-process-is-doing-print-stack-trace-of-an-uninstrumented-py">Check what a running process is doing: print stack trace of an uninstrumented Python program</a></li> </ul>
250
2008-09-25T08:06:06Z
9,019,164
<p>Take a look at the <a href="http://docs.python.org/3.3/whatsnew/3.3.html#faulthandler" rel="nofollow"><code>faulthandler</code></a> module, new in Python 3.3. A <a href="https://pypi.python.org/pypi/faulthandler/" rel="nofollow"><code>faulthandler</code> backport</a> for use in Python 2 is available on PyPI.</p>
7
2012-01-26T13:57:38Z
[ "python", "debugging", "stack-trace", "traceback" ]
Showing the stack trace from a running Python application
132,058
<p>I have this Python application that gets stuck from time to time and I can't find out where.</p> <p>Is there any way to signal Python interpreter to show you the exact code that's running? </p> <p>Some kind of on-the-fly stacktrace?</p> <p><strong><em>Related questions:</em></strong></p> <ul> <li><a href="http://stackoverflow.com/questions/1156023/print-current-call-stack-from-a-method-in-python-code">Print current call stack from a method in Python code</a></li> <li><a href="http://stackoverflow.com/questions/6849138/check-what-a-running-process-is-doing-print-stack-trace-of-an-uninstrumented-py">Check what a running process is doing: print stack trace of an uninstrumented Python program</a></li> </ul>
250
2008-09-25T08:06:06Z
10,047,855
<p>I hacked together some tool which attaches into a running Python process and injects some code to get a Python shell.</p> <p>See here: <a href="https://github.com/albertz/pydbattach" rel="nofollow">https://github.com/albertz/pydbattach</a></p>
3
2012-04-06T18:49:30Z
[ "python", "debugging", "stack-trace", "traceback" ]
Showing the stack trace from a running Python application
132,058
<p>I have this Python application that gets stuck from time to time and I can't find out where.</p> <p>Is there any way to signal Python interpreter to show you the exact code that's running? </p> <p>Some kind of on-the-fly stacktrace?</p> <p><strong><em>Related questions:</em></strong></p> <ul> <li><a href="http://stackoverflow.com/questions/1156023/print-current-call-stack-from-a-method-in-python-code">Print current call stack from a method in Python code</a></li> <li><a href="http://stackoverflow.com/questions/6849138/check-what-a-running-process-is-doing-print-stack-trace-of-an-uninstrumented-py">Check what a running process is doing: print stack trace of an uninstrumented Python program</a></li> </ul>
250
2008-09-25T08:06:06Z
10,165,776
<p>I was looking for a while for a solution to debug my threads and I found it here thanks to haridsv. I use slightly simplified version employing the traceback.print_stack():</p> <pre><code>import sys, traceback, signal import threading import os def dumpstacks(signal, frame): id2name = dict((th.ident, th.name) for th in threading.enumerate()) for threadId, stack in sys._current_frames().items(): print(id2name[threadId]) traceback.print_stack(f=stack) signal.signal(signal.SIGQUIT, dumpstacks) os.killpg(os.getpgid(0), signal.SIGQUIT) </code></pre> <p>For my needs I also filter threads by name.</p>
3
2012-04-15T20:28:10Z
[ "python", "debugging", "stack-trace", "traceback" ]
Showing the stack trace from a running Python application
132,058
<p>I have this Python application that gets stuck from time to time and I can't find out where.</p> <p>Is there any way to signal Python interpreter to show you the exact code that's running? </p> <p>Some kind of on-the-fly stacktrace?</p> <p><strong><em>Related questions:</em></strong></p> <ul> <li><a href="http://stackoverflow.com/questions/1156023/print-current-call-stack-from-a-method-in-python-code">Print current call stack from a method in Python code</a></li> <li><a href="http://stackoverflow.com/questions/6849138/check-what-a-running-process-is-doing-print-stack-trace-of-an-uninstrumented-py">Check what a running process is doing: print stack trace of an uninstrumented Python program</a></li> </ul>
250
2008-09-25T08:06:06Z
16,246,063
<p>You can try the <a href="http://docs.python.org/dev/library/faulthandler.html">faulthandler module</a>. Install it using <code>pip install faulthandler</code> and add:</p> <pre><code>import faulthandler, signal faulthandler.register(signal.SIGUSR1) </code></pre> <p>at the beginning of your program. Then send SIGUSR1 to your process (ex: <code>kill -USR1 42</code>) to display the Python traceback of all threads to the standard output. <a href="http://docs.python.org/dev/library/faulthandler.html">Read the documentation</a> for more options (ex: log into a file) and other ways to display the traceback.</p> <p>The module is now part of Python 3.3. For Python 2, see <a href="http://faulthandler.readthedocs.org/">http://faulthandler.readthedocs.org/</a></p>
14
2013-04-26T22:18:58Z
[ "python", "debugging", "stack-trace", "traceback" ]
Showing the stack trace from a running Python application
132,058
<p>I have this Python application that gets stuck from time to time and I can't find out where.</p> <p>Is there any way to signal Python interpreter to show you the exact code that's running? </p> <p>Some kind of on-the-fly stacktrace?</p> <p><strong><em>Related questions:</em></strong></p> <ul> <li><a href="http://stackoverflow.com/questions/1156023/print-current-call-stack-from-a-method-in-python-code">Print current call stack from a method in Python code</a></li> <li><a href="http://stackoverflow.com/questions/6849138/check-what-a-running-process-is-doing-print-stack-trace-of-an-uninstrumented-py">Check what a running process is doing: print stack trace of an uninstrumented Python program</a></li> </ul>
250
2008-09-25T08:06:06Z
16,247,213
<p>You can use <a href="https://pypi.python.org/pypi/pudb" rel="nofollow">PuDB</a>, a Python debugger with a curses interface to do this. Just add </p> <pre><code>from pudb import set_interrupt_handler; set_interrupt_handler() </code></pre> <p>to your code and use Ctrl-C when you want to break. You can continue with <code>c</code> and break again multiple times if you miss it and want to try again. </p>
1
2013-04-27T00:54:57Z
[ "python", "debugging", "stack-trace", "traceback" ]
Showing the stack trace from a running Python application
132,058
<p>I have this Python application that gets stuck from time to time and I can't find out where.</p> <p>Is there any way to signal Python interpreter to show you the exact code that's running? </p> <p>Some kind of on-the-fly stacktrace?</p> <p><strong><em>Related questions:</em></strong></p> <ul> <li><a href="http://stackoverflow.com/questions/1156023/print-current-call-stack-from-a-method-in-python-code">Print current call stack from a method in Python code</a></li> <li><a href="http://stackoverflow.com/questions/6849138/check-what-a-running-process-is-doing-print-stack-trace-of-an-uninstrumented-py">Check what a running process is doing: print stack trace of an uninstrumented Python program</a></li> </ul>
250
2008-09-25T08:06:06Z
17,270,641
<p>If you're on a Linux system, use the awesomeness of <code>gdb</code> with Python debug extensions (can be in <code>python-dbg</code> or <code>python-debuginfo</code> package). It also helps with multithreaded applications, GUI applications and C modules.</p> <p>Run your program with:</p> <pre><code>$ gdb -ex r --args python &lt;programname&gt;.py [arguments] </code></pre> <p>This instructs <code>gdb</code> to prepare <code>python &lt;programname&gt;.py &lt;arguments&gt;</code> and <code>r</code>un it.</p> <p>Now when you program hangs, switch into <code>gdb</code> console, press <kbd>Ctr+C</kbd> and execute:</p> <pre><code>(gdb) thread apply all py-list </code></pre> <p>See <a href="https://code.google.com/p/spyderlib/wiki/HowToDebugDeadlock">example session</a> and more info <a href="http://wiki.python.org/moin/DebuggingWithGdb">here</a> and <a href="http://fedoraproject.org/wiki/Features/EasierPythonDebugging">here</a>.</p>
5
2013-06-24T08:03:31Z
[ "python", "debugging", "stack-trace", "traceback" ]
Showing the stack trace from a running Python application
132,058
<p>I have this Python application that gets stuck from time to time and I can't find out where.</p> <p>Is there any way to signal Python interpreter to show you the exact code that's running? </p> <p>Some kind of on-the-fly stacktrace?</p> <p><strong><em>Related questions:</em></strong></p> <ul> <li><a href="http://stackoverflow.com/questions/1156023/print-current-call-stack-from-a-method-in-python-code">Print current call stack from a method in Python code</a></li> <li><a href="http://stackoverflow.com/questions/6849138/check-what-a-running-process-is-doing-print-stack-trace-of-an-uninstrumented-py">Check what a running process is doing: print stack trace of an uninstrumented Python program</a></li> </ul>
250
2008-09-25T08:06:06Z
23,405,280
<p><a href="https://github.com/google/pyringe" rel="nofollow">pyringe</a> is a debugger that can interact with running python processes, print stack traces, variables, etc. without any a priori setup.</p> <p>While I've often used the signal handler solution in the past, it can still often be difficult to reproduce the issue in certain environments.</p>
2
2014-05-01T09:40:07Z
[ "python", "debugging", "stack-trace", "traceback" ]
Showing the stack trace from a running Python application
132,058
<p>I have this Python application that gets stuck from time to time and I can't find out where.</p> <p>Is there any way to signal Python interpreter to show you the exact code that's running? </p> <p>Some kind of on-the-fly stacktrace?</p> <p><strong><em>Related questions:</em></strong></p> <ul> <li><a href="http://stackoverflow.com/questions/1156023/print-current-call-stack-from-a-method-in-python-code">Print current call stack from a method in Python code</a></li> <li><a href="http://stackoverflow.com/questions/6849138/check-what-a-running-process-is-doing-print-stack-trace-of-an-uninstrumented-py">Check what a running process is doing: print stack trace of an uninstrumented Python program</a></li> </ul>
250
2008-09-25T08:06:06Z
27,465,699
<p>In Python 3, pdb will automatically install a signal handler the first time you use c(ont(inue)) in the debugger. Pressing Control-C afterwards will drop you right back in there. In Python 2, here's a one-liner which should work even in relatively old versions (tested in 2.7 but I checked Python source back to 2.4 and it looked okay):</p> <pre><code>import pdb, signal signal.signal(signal.SIGINT, lambda sig, frame: pdb.Pdb().set_trace(frame)) </code></pre> <p>pdb is worth learning if you spend any amount of time debugging Python. The interface is a bit obtuse but should be familiar to anyone who has used similar tools, such as gdb.</p>
0
2014-12-14T02:16:25Z
[ "python", "debugging", "stack-trace", "traceback" ]
Showing the stack trace from a running Python application
132,058
<p>I have this Python application that gets stuck from time to time and I can't find out where.</p> <p>Is there any way to signal Python interpreter to show you the exact code that's running? </p> <p>Some kind of on-the-fly stacktrace?</p> <p><strong><em>Related questions:</em></strong></p> <ul> <li><a href="http://stackoverflow.com/questions/1156023/print-current-call-stack-from-a-method-in-python-code">Print current call stack from a method in Python code</a></li> <li><a href="http://stackoverflow.com/questions/6849138/check-what-a-running-process-is-doing-print-stack-trace-of-an-uninstrumented-py">Check what a running process is doing: print stack trace of an uninstrumented Python program</a></li> </ul>
250
2008-09-25T08:06:06Z
29,881,630
<p>Getting a stack trace of an <em>unprepared</em> python program, running in a stock python <em>without debugging symbols</em> can be done with <a href="http://pyrasite.readthedocs.org/">pyrasite</a>. Worked like a charm for me in on Ubuntu Trusty:</p> <pre><code>$ sudo pip install pyrasite $ echo 0 | sudo tee /proc/sys/kernel/yama/ptrace_scope $ sudo pyrasite 16262 dump_stacks.py # dumps stacks to stdout/stderr of the python program </code></pre> <p>(Hat tip to @Albert, whose answer contained a pointer to this, among other tools.)</p>
16
2015-04-26T18:22:20Z
[ "python", "debugging", "stack-trace", "traceback" ]
Showing the stack trace from a running Python application
132,058
<p>I have this Python application that gets stuck from time to time and I can't find out where.</p> <p>Is there any way to signal Python interpreter to show you the exact code that's running? </p> <p>Some kind of on-the-fly stacktrace?</p> <p><strong><em>Related questions:</em></strong></p> <ul> <li><a href="http://stackoverflow.com/questions/1156023/print-current-call-stack-from-a-method-in-python-code">Print current call stack from a method in Python code</a></li> <li><a href="http://stackoverflow.com/questions/6849138/check-what-a-running-process-is-doing-print-stack-trace-of-an-uninstrumented-py">Check what a running process is doing: print stack trace of an uninstrumented Python program</a></li> </ul>
250
2008-09-25T08:06:06Z
29,911,672
<p>In case you need to do this with uWSGI, it has <a href="http://uwsgi-docs.readthedocs.org/en/latest/Tracebacker.html" rel="nofollow">Python Tracebacker</a> built-in and it's just matter of enabling it in the configuration (number is attached to the name for each worker):</p> <pre><code>py-tracebacker=/var/run/uwsgi/pytrace </code></pre> <p>Once you have done this, you can print backtrace simply by connecting to the socket:</p> <pre><code>uwsgi --connect-and-read /var/run/uwsgi/pytrace1 </code></pre>
0
2015-04-28T06:15:05Z
[ "python", "debugging", "stack-trace", "traceback" ]
Translate algorithmic C to Python
132,411
<p>I would like to translate some C code to Python code or bytecode. The C code in question is what i'd call purely algorithmic: platform independent, no I/O, just algorithms and in-memory data structures.</p> <p>An example would be a regular expression library. Translation tool would process library source code and produce a functionally equivalent Python module that can be run in a <strong>sandboxed</strong> environment.</p> <p>What specific approaches, tools and techniques can you recommend?</p> <p><hr /></p> <p><em>Note: Python C extension or ctypes is <strong>not an option</strong> because the environment is sandboxed.</em></p> <p><em>Another note</em>: looks like there is a <a href="http://www.axiomsol.com/" rel="nofollow">C-to-Java-bytecode compiler</a>, they even compiled libjpeg to Java. Is Java bytecode+VM too different from CPython bytecode+VM?</p>
8
2008-09-25T09:56:43Z
132,425
<p>Why not keeping the C code and <a href="http://www.python.org/doc/ext/intro.html" rel="nofollow">creating a Python C module</a> which can be imported into a running Python environment?</p>
0
2008-09-25T10:00:14Z
[ "java", "python", "c", "sandbox", "code-translation" ]
Translate algorithmic C to Python
132,411
<p>I would like to translate some C code to Python code or bytecode. The C code in question is what i'd call purely algorithmic: platform independent, no I/O, just algorithms and in-memory data structures.</p> <p>An example would be a regular expression library. Translation tool would process library source code and produce a functionally equivalent Python module that can be run in a <strong>sandboxed</strong> environment.</p> <p>What specific approaches, tools and techniques can you recommend?</p> <p><hr /></p> <p><em>Note: Python C extension or ctypes is <strong>not an option</strong> because the environment is sandboxed.</em></p> <p><em>Another note</em>: looks like there is a <a href="http://www.axiomsol.com/" rel="nofollow">C-to-Java-bytecode compiler</a>, they even compiled libjpeg to Java. Is Java bytecode+VM too different from CPython bytecode+VM?</p>
8
2008-09-25T09:56:43Z
132,438
<p>First, i'd consider wrapping the existing C library with Pythonic goodness to provide an API in the form of a python module. I'd look at swig, ctypes, pyrex, and whatever else is out there these days. The C library itself would stay there unchanged. Saves work. </p> <p>But if i really had to write original Python code based on the C, there's no tool i'd use, just my brain. C allows too many funny tricks with pointers, clever things with macros, etc that i'd never trust an automated tool even if someone pointed one out to me. </p> <p>I mentioned Pyrex - this is a language similar to C but also Python oriented. I haven't done much with it, but it could be easier than writing pure python, given that you're starting with C as a guide.</p> <p>Converting from more constrained, tamer languages such as IDL (the data languages scientists like to use, not the other IDL) is hard, requiring manual and mental effort. C? Forget it, not until the UFO people give us their fancy software tools that are a thousand years ahead of our state of the art!</p>
0
2008-09-25T10:07:47Z
[ "java", "python", "c", "sandbox", "code-translation" ]
Translate algorithmic C to Python
132,411
<p>I would like to translate some C code to Python code or bytecode. The C code in question is what i'd call purely algorithmic: platform independent, no I/O, just algorithms and in-memory data structures.</p> <p>An example would be a regular expression library. Translation tool would process library source code and produce a functionally equivalent Python module that can be run in a <strong>sandboxed</strong> environment.</p> <p>What specific approaches, tools and techniques can you recommend?</p> <p><hr /></p> <p><em>Note: Python C extension or ctypes is <strong>not an option</strong> because the environment is sandboxed.</em></p> <p><em>Another note</em>: looks like there is a <a href="http://www.axiomsol.com/" rel="nofollow">C-to-Java-bytecode compiler</a>, they even compiled libjpeg to Java. Is Java bytecode+VM too different from CPython bytecode+VM?</p>
8
2008-09-25T09:56:43Z
132,459
<p>There is frankly no way to mechanically and meaningfully translate C to Python without suffering an insane performance penalty. As we all know Python isn't anywhere near C speed (with current compilers and interpreters) but worse than that is that what C is good at (bit-fiddling, integer math, tricks with blocks of memory) Python is very slow at, and what Python is good at you can't express in C directly. A direct translation would therefore be extra inefficient, to the point of absurdity.</p> <p>The much, much better approach in general is indeed to keep the C the C, and wrap it in a Python extension module (using <a href="http://www.swig.org">SWIG</a>, <a href="http://www.cosc.canterbury.ac.nz/greg.ewing/python/Pyrex/">Pyrex</a>, <a href="http://cython.org">Cython</a> or <a href="http://docs.python.org/ext">writing a wrapper manually</a>) or call the C library directly using <a href="http://docs.python.org/lib/module-ctypes.html">ctypes</a>. All the benefits (and downsides) of C for what's already C or you add later, and all the convenience (and downsides) of Python for any code in Python.</p> <p>That won't satisfy your 'sandboxing' needs, but you should realize that you cannot sandbox Python particularly well anyway; it takes a lot of effort and modification of CPython, and if you forget one little hole somewhere your jail is broken. If you want to sandbox Python you should start by sandboxing the entire process, and then C extensions can get sandboxed too.</p>
12
2008-09-25T10:12:54Z
[ "java", "python", "c", "sandbox", "code-translation" ]
Translate algorithmic C to Python
132,411
<p>I would like to translate some C code to Python code or bytecode. The C code in question is what i'd call purely algorithmic: platform independent, no I/O, just algorithms and in-memory data structures.</p> <p>An example would be a regular expression library. Translation tool would process library source code and produce a functionally equivalent Python module that can be run in a <strong>sandboxed</strong> environment.</p> <p>What specific approaches, tools and techniques can you recommend?</p> <p><hr /></p> <p><em>Note: Python C extension or ctypes is <strong>not an option</strong> because the environment is sandboxed.</em></p> <p><em>Another note</em>: looks like there is a <a href="http://www.axiomsol.com/" rel="nofollow">C-to-Java-bytecode compiler</a>, they even compiled libjpeg to Java. Is Java bytecode+VM too different from CPython bytecode+VM?</p>
8
2008-09-25T09:56:43Z
132,470
<p>Any automatic translation is going to suffer for not using the power of Python. C-type procedural code would run very slowly if translated directly into Python, you would need to profile and replace whole sections with more Python-optimized code.</p>
0
2008-09-25T10:16:49Z
[ "java", "python", "c", "sandbox", "code-translation" ]
Translate algorithmic C to Python
132,411
<p>I would like to translate some C code to Python code or bytecode. The C code in question is what i'd call purely algorithmic: platform independent, no I/O, just algorithms and in-memory data structures.</p> <p>An example would be a regular expression library. Translation tool would process library source code and produce a functionally equivalent Python module that can be run in a <strong>sandboxed</strong> environment.</p> <p>What specific approaches, tools and techniques can you recommend?</p> <p><hr /></p> <p><em>Note: Python C extension or ctypes is <strong>not an option</strong> because the environment is sandboxed.</em></p> <p><em>Another note</em>: looks like there is a <a href="http://www.axiomsol.com/" rel="nofollow">C-to-Java-bytecode compiler</a>, they even compiled libjpeg to Java. Is Java bytecode+VM too different from CPython bytecode+VM?</p>
8
2008-09-25T09:56:43Z
132,493
<p>The fastest way (in terms of programmer effort, not efficiency) would probably involve using an existing compiler to compile C to something simple (for example LLVM) and either:</p> <ul> <li>interpret that in Python (exorbitant performance penalty)</li> <li>translate that to Python (huge performance penalty)</li> <li>translate that to Python bytecode (big performance penalty)</li> </ul> <p>Translating C to Python directly is possible (and probably yields faster code than the above approaches), but you'd be essentially writing a C compiler backend, which is a huge task.</p> <p>Edit, afterthought: A perhaps even more quick-and-dirty way of doing that is to take the parse tree for the C code, transform that to a Python data structure and interpret that in Python.</p>
3
2008-09-25T10:25:45Z
[ "java", "python", "c", "sandbox", "code-translation" ]
Translate algorithmic C to Python
132,411
<p>I would like to translate some C code to Python code or bytecode. The C code in question is what i'd call purely algorithmic: platform independent, no I/O, just algorithms and in-memory data structures.</p> <p>An example would be a regular expression library. Translation tool would process library source code and produce a functionally equivalent Python module that can be run in a <strong>sandboxed</strong> environment.</p> <p>What specific approaches, tools and techniques can you recommend?</p> <p><hr /></p> <p><em>Note: Python C extension or ctypes is <strong>not an option</strong> because the environment is sandboxed.</em></p> <p><em>Another note</em>: looks like there is a <a href="http://www.axiomsol.com/" rel="nofollow">C-to-Java-bytecode compiler</a>, they even compiled libjpeg to Java. Is Java bytecode+VM too different from CPython bytecode+VM?</p>
8
2008-09-25T09:56:43Z
135,209
<p>You can always compile the C code, and load in the libraries using ctypes in python.</p>
-1
2008-09-25T18:52:54Z
[ "java", "python", "c", "sandbox", "code-translation" ]
Translate algorithmic C to Python
132,411
<p>I would like to translate some C code to Python code or bytecode. The C code in question is what i'd call purely algorithmic: platform independent, no I/O, just algorithms and in-memory data structures.</p> <p>An example would be a regular expression library. Translation tool would process library source code and produce a functionally equivalent Python module that can be run in a <strong>sandboxed</strong> environment.</p> <p>What specific approaches, tools and techniques can you recommend?</p> <p><hr /></p> <p><em>Note: Python C extension or ctypes is <strong>not an option</strong> because the environment is sandboxed.</em></p> <p><em>Another note</em>: looks like there is a <a href="http://www.axiomsol.com/" rel="nofollow">C-to-Java-bytecode compiler</a>, they even compiled libjpeg to Java. Is Java bytecode+VM too different from CPython bytecode+VM?</p>
8
2008-09-25T09:56:43Z
135,837
<p>I'd personnaly use a tool to extract an uml sheme from the C code, then use it to generate python code.</p> <p>From this squeleton, I's start to get rid of the uncessary C-style structures and then I'd fill the methods with python code.</p> <p>I think it would be the safer and yet most efficient way.</p>
0
2008-09-25T20:29:33Z
[ "java", "python", "c", "sandbox", "code-translation" ]
Translate algorithmic C to Python
132,411
<p>I would like to translate some C code to Python code or bytecode. The C code in question is what i'd call purely algorithmic: platform independent, no I/O, just algorithms and in-memory data structures.</p> <p>An example would be a regular expression library. Translation tool would process library source code and produce a functionally equivalent Python module that can be run in a <strong>sandboxed</strong> environment.</p> <p>What specific approaches, tools and techniques can you recommend?</p> <p><hr /></p> <p><em>Note: Python C extension or ctypes is <strong>not an option</strong> because the environment is sandboxed.</em></p> <p><em>Another note</em>: looks like there is a <a href="http://www.axiomsol.com/" rel="nofollow">C-to-Java-bytecode compiler</a>, they even compiled libjpeg to Java. Is Java bytecode+VM too different from CPython bytecode+VM?</p>
8
2008-09-25T09:56:43Z
782,839
<p>Write a C interpreter in pure Python? ;-)</p>
1
2009-04-23T17:51:26Z
[ "java", "python", "c", "sandbox", "code-translation" ]
Translate algorithmic C to Python
132,411
<p>I would like to translate some C code to Python code or bytecode. The C code in question is what i'd call purely algorithmic: platform independent, no I/O, just algorithms and in-memory data structures.</p> <p>An example would be a regular expression library. Translation tool would process library source code and produce a functionally equivalent Python module that can be run in a <strong>sandboxed</strong> environment.</p> <p>What specific approaches, tools and techniques can you recommend?</p> <p><hr /></p> <p><em>Note: Python C extension or ctypes is <strong>not an option</strong> because the environment is sandboxed.</em></p> <p><em>Another note</em>: looks like there is a <a href="http://www.axiomsol.com/" rel="nofollow">C-to-Java-bytecode compiler</a>, they even compiled libjpeg to Java. Is Java bytecode+VM too different from CPython bytecode+VM?</p>
8
2008-09-25T09:56:43Z
6,857,972
<p>use indent(1) and ctopy(1)... for extra credit test speeds on pypy... for bonus credit use pyastra to generate assembly code.</p> <p>Regardless of language you will always have to sacrifice storing outputs of various constructs and functions between run-time space (CPU) or memory-space (RAM).</p> <p>Check the great language shootout if you want to see what I'm talking about either way this is too much comp sci snobbery... </p> <p>Here is an example, want to use floating point math without using floating point numbers?</p> <pre><code>x * 1,000,000 = a y * 1,000,000 = b a {function} b = result result / 1,000,000 = z </code></pre> <p>Don't get bogged down, get primal, use caveman math if you have to.</p>
4
2011-07-28T11:09:45Z
[ "java", "python", "c", "sandbox", "code-translation" ]
Regex to remove conditional comments
132,488
<p>I want a regex which can match conditional comments in a HTML source page so I can remove only those. I want to preserve the regular comments.</p> <p>I would also like to avoid using the .*? notation if possible. </p> <p>The text is </p> <pre><code>foo &lt;!--[if IE]&gt; &lt;style type="text/css"&gt; ul.menu ul li{ font-size: 10px; font-weight:normal; padding-top:0px; } &lt;/style&gt; &lt;![endif]--&gt; bar </code></pre> <p>and I want to remove everything in <code>&lt;!--[if IE]&gt;</code> and <code>&lt;![endif]--&gt;</code></p> <p><strong>EDIT:</strong> It is because of BeautifulSoup I want to remove these tags. BeautifulSoup fails to parse and gives an incomplete source</p> <p><strong>EDIT2:</strong> [if IE] isn't the only condition. There are lots more and I don't have any list of all possible combinations.</p> <p><strong>EDIT3:</strong> Vinko Vrsalovic's solution works, but the actual problem why beautifulsoup failed was because of a rogue comment within the conditional comment. Like</p> <pre><code>&lt;!--[if lt IE 7.]&gt; &lt;script defer type="text/javascript" src="pngfix_253168.js"&gt;&lt;/script&gt;&lt;!--png fix for IE--&gt; &lt;![endif]--&gt; </code></pre> <p>Notice the <code>&lt;!--png fix for IE--&gt;</code> comment?</p> <p>Though my problem was solve, I would love to get a regex solution for this.</p>
5
2008-09-25T10:23:33Z
132,499
<p>Don't use a regular expression for this. You will get confused about comments containing opening tags and what not, and do the wrong thing. HTML isn't regular, and trying to modify it with a single regular expression will fail.</p> <p>Use a HTML parser for this. BeautifulSoup is a good, easy, flexible and sturdy one that is able to handle real-world (meaning hopelessly broken) HTML. With it you can just look up all comment nodes, examine their content (you can use a regular expression for <em>that</em>, if you wish) and remove them if they need to be removed.</p>
0
2008-09-25T10:27:06Z
[ "python", "regex" ]
Regex to remove conditional comments
132,488
<p>I want a regex which can match conditional comments in a HTML source page so I can remove only those. I want to preserve the regular comments.</p> <p>I would also like to avoid using the .*? notation if possible. </p> <p>The text is </p> <pre><code>foo &lt;!--[if IE]&gt; &lt;style type="text/css"&gt; ul.menu ul li{ font-size: 10px; font-weight:normal; padding-top:0px; } &lt;/style&gt; &lt;![endif]--&gt; bar </code></pre> <p>and I want to remove everything in <code>&lt;!--[if IE]&gt;</code> and <code>&lt;![endif]--&gt;</code></p> <p><strong>EDIT:</strong> It is because of BeautifulSoup I want to remove these tags. BeautifulSoup fails to parse and gives an incomplete source</p> <p><strong>EDIT2:</strong> [if IE] isn't the only condition. There are lots more and I don't have any list of all possible combinations.</p> <p><strong>EDIT3:</strong> Vinko Vrsalovic's solution works, but the actual problem why beautifulsoup failed was because of a rogue comment within the conditional comment. Like</p> <pre><code>&lt;!--[if lt IE 7.]&gt; &lt;script defer type="text/javascript" src="pngfix_253168.js"&gt;&lt;/script&gt;&lt;!--png fix for IE--&gt; &lt;![endif]--&gt; </code></pre> <p>Notice the <code>&lt;!--png fix for IE--&gt;</code> comment?</p> <p>Though my problem was solve, I would love to get a regex solution for this.</p>
5
2008-09-25T10:23:33Z
132,519
<p>@<a href="#132503" rel="nofollow">Benoit </a></p> <p>Small Correction (with multiline turned on): </p> <pre><code> "&lt;!--\[if IE\]&gt;.*?&lt;!\[endif\]--&gt;" </code></pre>
1
2008-09-25T10:31:59Z
[ "python", "regex" ]
Regex to remove conditional comments
132,488
<p>I want a regex which can match conditional comments in a HTML source page so I can remove only those. I want to preserve the regular comments.</p> <p>I would also like to avoid using the .*? notation if possible. </p> <p>The text is </p> <pre><code>foo &lt;!--[if IE]&gt; &lt;style type="text/css"&gt; ul.menu ul li{ font-size: 10px; font-weight:normal; padding-top:0px; } &lt;/style&gt; &lt;![endif]--&gt; bar </code></pre> <p>and I want to remove everything in <code>&lt;!--[if IE]&gt;</code> and <code>&lt;![endif]--&gt;</code></p> <p><strong>EDIT:</strong> It is because of BeautifulSoup I want to remove these tags. BeautifulSoup fails to parse and gives an incomplete source</p> <p><strong>EDIT2:</strong> [if IE] isn't the only condition. There are lots more and I don't have any list of all possible combinations.</p> <p><strong>EDIT3:</strong> Vinko Vrsalovic's solution works, but the actual problem why beautifulsoup failed was because of a rogue comment within the conditional comment. Like</p> <pre><code>&lt;!--[if lt IE 7.]&gt; &lt;script defer type="text/javascript" src="pngfix_253168.js"&gt;&lt;/script&gt;&lt;!--png fix for IE--&gt; &lt;![endif]--&gt; </code></pre> <p>Notice the <code>&lt;!--png fix for IE--&gt;</code> comment?</p> <p>Though my problem was solve, I would love to get a regex solution for this.</p>
5
2008-09-25T10:23:33Z
132,521
<p>This works in Visual Studio 2005, where there is no line span option:</p> <p><code>\&lt;!--\[if IE\]\&gt;{.|\n}*\&lt;!\[endif\]--\&gt;</code></p>
0
2008-09-25T10:32:39Z
[ "python", "regex" ]
Regex to remove conditional comments
132,488
<p>I want a regex which can match conditional comments in a HTML source page so I can remove only those. I want to preserve the regular comments.</p> <p>I would also like to avoid using the .*? notation if possible. </p> <p>The text is </p> <pre><code>foo &lt;!--[if IE]&gt; &lt;style type="text/css"&gt; ul.menu ul li{ font-size: 10px; font-weight:normal; padding-top:0px; } &lt;/style&gt; &lt;![endif]--&gt; bar </code></pre> <p>and I want to remove everything in <code>&lt;!--[if IE]&gt;</code> and <code>&lt;![endif]--&gt;</code></p> <p><strong>EDIT:</strong> It is because of BeautifulSoup I want to remove these tags. BeautifulSoup fails to parse and gives an incomplete source</p> <p><strong>EDIT2:</strong> [if IE] isn't the only condition. There are lots more and I don't have any list of all possible combinations.</p> <p><strong>EDIT3:</strong> Vinko Vrsalovic's solution works, but the actual problem why beautifulsoup failed was because of a rogue comment within the conditional comment. Like</p> <pre><code>&lt;!--[if lt IE 7.]&gt; &lt;script defer type="text/javascript" src="pngfix_253168.js"&gt;&lt;/script&gt;&lt;!--png fix for IE--&gt; &lt;![endif]--&gt; </code></pre> <p>Notice the <code>&lt;!--png fix for IE--&gt;</code> comment?</p> <p>Though my problem was solve, I would love to get a regex solution for this.</p>
5
2008-09-25T10:23:33Z
132,532
<pre><code>&gt;&gt;&gt; from BeautifulSoup import BeautifulSoup, Comment &gt;&gt;&gt; html = '&lt;html&gt;&lt;!--[if IE]&gt; bloo blee&lt;![endif]--&gt;&lt;/html&gt;' &gt;&gt;&gt; soup = BeautifulSoup(html) &gt;&gt;&gt; comments = soup.findAll(text=lambda text:isinstance(text, Comment) and text.find('if') != -1) #This is one line, of course &gt;&gt;&gt; [comment.extract() for comment in comments] [u'[if IE]&gt; bloo blee&lt;![endif]'] &gt;&gt;&gt; print soup.prettify() &lt;html&gt; &lt;/html&gt; &gt;&gt;&gt; </code></pre> <p>If your data gets BeautifulSoup confused, you can <a href="http://www.crummy.com/software/BeautifulSoup/documentation.html#Sanitizing%20Bad%20Data%20with%20Regexps" rel="nofollow">fix</a> it before hand or <a href="http://www.crummy.com/software/BeautifulSoup/documentation.html#Customizing%20the%20Parser" rel="nofollow">customize</a> the parser, among other solutions.</p> <p>EDIT: Per your comment, you just modify the lambda passed to findAll as you need (I modified it)</p>
4
2008-09-25T10:34:45Z
[ "python", "regex" ]
Regex to remove conditional comments
132,488
<p>I want a regex which can match conditional comments in a HTML source page so I can remove only those. I want to preserve the regular comments.</p> <p>I would also like to avoid using the .*? notation if possible. </p> <p>The text is </p> <pre><code>foo &lt;!--[if IE]&gt; &lt;style type="text/css"&gt; ul.menu ul li{ font-size: 10px; font-weight:normal; padding-top:0px; } &lt;/style&gt; &lt;![endif]--&gt; bar </code></pre> <p>and I want to remove everything in <code>&lt;!--[if IE]&gt;</code> and <code>&lt;![endif]--&gt;</code></p> <p><strong>EDIT:</strong> It is because of BeautifulSoup I want to remove these tags. BeautifulSoup fails to parse and gives an incomplete source</p> <p><strong>EDIT2:</strong> [if IE] isn't the only condition. There are lots more and I don't have any list of all possible combinations.</p> <p><strong>EDIT3:</strong> Vinko Vrsalovic's solution works, but the actual problem why beautifulsoup failed was because of a rogue comment within the conditional comment. Like</p> <pre><code>&lt;!--[if lt IE 7.]&gt; &lt;script defer type="text/javascript" src="pngfix_253168.js"&gt;&lt;/script&gt;&lt;!--png fix for IE--&gt; &lt;![endif]--&gt; </code></pre> <p>Notice the <code>&lt;!--png fix for IE--&gt;</code> comment?</p> <p>Though my problem was solve, I would love to get a regex solution for this.</p>
5
2008-09-25T10:23:33Z
132,561
<p>Here's what you'll need:</p> <pre><code>&lt;!(|--)\[[^\]]+\]&gt;.+?&lt;!\[endif\](|--)&gt; </code></pre> <p>It will filter out all sorts of conditional comments including:</p> <pre><code>&lt;!--[if anything]&gt; ... &lt;[endif]--&gt; </code></pre> <p>and</p> <pre><code>&lt;![if ! IE 6]&gt; ... &lt;![endif]&gt; </code></pre> <p><hr></p> <blockquote> <p><strong>EDIT3</strong>: Vinko Vrsalovic's solution works, but the actual problem why beautifulsoup failed was because of a rogue comment within the conditional comment. Like</p> <p>Notice the comment?</p> <p>Though my problem was solve, I would love to get a regex solution for this.</p> </blockquote> <p>How about this:</p> <pre><code>(&lt;!(|--)\[[^\]]+\]&gt;.*?)(&lt;!--.+?--&gt;)(.*?&lt;!\[endif\](|--)&gt;) </code></pre> <p>Do a replace on that regular expression leaving \1\4 (or $1$4) as the replacement.<br /> <em>I know it has .</em>? and .+? in it, see my comment on this post._</p>
1
2008-09-25T10:46:16Z
[ "python", "regex" ]
Regex to remove conditional comments
132,488
<p>I want a regex which can match conditional comments in a HTML source page so I can remove only those. I want to preserve the regular comments.</p> <p>I would also like to avoid using the .*? notation if possible. </p> <p>The text is </p> <pre><code>foo &lt;!--[if IE]&gt; &lt;style type="text/css"&gt; ul.menu ul li{ font-size: 10px; font-weight:normal; padding-top:0px; } &lt;/style&gt; &lt;![endif]--&gt; bar </code></pre> <p>and I want to remove everything in <code>&lt;!--[if IE]&gt;</code> and <code>&lt;![endif]--&gt;</code></p> <p><strong>EDIT:</strong> It is because of BeautifulSoup I want to remove these tags. BeautifulSoup fails to parse and gives an incomplete source</p> <p><strong>EDIT2:</strong> [if IE] isn't the only condition. There are lots more and I don't have any list of all possible combinations.</p> <p><strong>EDIT3:</strong> Vinko Vrsalovic's solution works, but the actual problem why beautifulsoup failed was because of a rogue comment within the conditional comment. Like</p> <pre><code>&lt;!--[if lt IE 7.]&gt; &lt;script defer type="text/javascript" src="pngfix_253168.js"&gt;&lt;/script&gt;&lt;!--png fix for IE--&gt; &lt;![endif]--&gt; </code></pre> <p>Notice the <code>&lt;!--png fix for IE--&gt;</code> comment?</p> <p>Though my problem was solve, I would love to get a regex solution for this.</p>
5
2008-09-25T10:23:33Z
135,916
<p>I'd simply go with :</p> <pre><code>import re html = """fjlk&lt;wb&gt;dsqfjqdsmlkf fdsijfmldsqjfl fjdslmfkqsjf&lt;---- fdjslmjkqfs---&gt;&lt;!--[if lt IE 7.]&gt;\ &lt;script defer type="text/javascript" src="pngfix_253168.js"&gt;&lt;/script&gt;&lt;!--png fix for IE--&gt;\ &lt;![endif]--&gt;fjlk&lt;wb&gt;dsqfjqdsmlkf fdsijfmldsqjfl fjdslmfkqsjf&lt;---- fdjslmjkqfs---&gt;""" # here the black magic occurs (whithout '.') clean_html = ''.join(re.split(r'&lt;!--\[[^¤]+?endif]--&gt;', html)) print clean_html 'fjlk&lt;wb&gt;dsqfjqdsmlkf fdsijfmldsqjfl fjdslmfkqsjf&lt;---- fdjslmjkqfs---&gt;fjlk&lt;wb&gt;dsqfjqdsmlkf fdsijfmldsqjfl fjdslmfkqsjf&lt;---- fdjslmjkqfs---&gt;' </code></pre> <p>N.B : [^¤] will match any char that is not '¤'. This is really useful since it's lightning fast and this char can be found on any keyboard. But the trick is it's really hard to type (no one will type it by mistake) and nobody uses it : it's a generical money devise char.</p> <p>If you don't feel like using ¤, however, you can use chr(7) to generate the "system bell" char, wich is unprintable and can't be found in a web page ;-)</p>
1
2008-09-25T20:42:26Z
[ "python", "regex" ]
Regex to remove conditional comments
132,488
<p>I want a regex which can match conditional comments in a HTML source page so I can remove only those. I want to preserve the regular comments.</p> <p>I would also like to avoid using the .*? notation if possible. </p> <p>The text is </p> <pre><code>foo &lt;!--[if IE]&gt; &lt;style type="text/css"&gt; ul.menu ul li{ font-size: 10px; font-weight:normal; padding-top:0px; } &lt;/style&gt; &lt;![endif]--&gt; bar </code></pre> <p>and I want to remove everything in <code>&lt;!--[if IE]&gt;</code> and <code>&lt;![endif]--&gt;</code></p> <p><strong>EDIT:</strong> It is because of BeautifulSoup I want to remove these tags. BeautifulSoup fails to parse and gives an incomplete source</p> <p><strong>EDIT2:</strong> [if IE] isn't the only condition. There are lots more and I don't have any list of all possible combinations.</p> <p><strong>EDIT3:</strong> Vinko Vrsalovic's solution works, but the actual problem why beautifulsoup failed was because of a rogue comment within the conditional comment. Like</p> <pre><code>&lt;!--[if lt IE 7.]&gt; &lt;script defer type="text/javascript" src="pngfix_253168.js"&gt;&lt;/script&gt;&lt;!--png fix for IE--&gt; &lt;![endif]--&gt; </code></pre> <p>Notice the <code>&lt;!--png fix for IE--&gt;</code> comment?</p> <p>Though my problem was solve, I would love to get a regex solution for this.</p>
5
2008-09-25T10:23:33Z
137,831
<p>As I see it, you only need to worry about <em>downlevel-hidden</em> comments (the ones that start with <code>&lt;!--</code>), and you don't need to match anything beyond the word <code>if</code> and the space following it. This should do what you want:</p> <pre><code>"&lt;!--\[if\s(?:[^&lt;]+|&lt;(?!!\[endif\]--&gt;))*&lt;!\[endif\]--&gt;" </code></pre> <p>That mess in the middle is to satisfy your desire not to use <code>.*?</code>, but I don't really think it's worth the effort. The <code>.*?</code> approach should work fine if you compile the regex with the Re.S flag set or wrap it in <code>(?s:...)</code>. For example:</p> <pre><code>"(?s:&lt;!--\[if\s.*?&lt;!\[endif\]--&gt;)" </code></pre>
1
2008-09-26T04:51:12Z
[ "python", "regex" ]
Is there a difference between `==` and `is` in Python?
132,988
<p>My <a href="http://en.wiktionary.org/wiki/Google-fu">Google-fu</a> has failed me.</p> <p>In Python, are the following two tests for equality equivalent (ha!)?</p> <pre><code>n = 5 # Test one. if n == 5: print 'Yay!' # Test two. if n is 5: print 'Yay!' </code></pre> <p>Does this hold true for objects where you would be comparing instances (a <code>list</code> say)?</p> <p>Okay, so this kind of answers my question:</p> <pre><code>L = [] L.append(1) if L == [1]: print 'Yay!' # Holds true, but... if L is [1]: print 'Yay!' # Doesn't. </code></pre> <p>So <code>==</code> tests value where <code>is</code> tests to see if they are the same object?</p>
299
2008-09-25T12:27:09Z
133,017
<p>== determines if the values are equivalent, while "is" determines if they are the exact same object. </p>
13
2008-09-25T12:31:12Z
[ "python", "reference", "semantics" ]
Is there a difference between `==` and `is` in Python?
132,988
<p>My <a href="http://en.wiktionary.org/wiki/Google-fu">Google-fu</a> has failed me.</p> <p>In Python, are the following two tests for equality equivalent (ha!)?</p> <pre><code>n = 5 # Test one. if n == 5: print 'Yay!' # Test two. if n is 5: print 'Yay!' </code></pre> <p>Does this hold true for objects where you would be comparing instances (a <code>list</code> say)?</p> <p>Okay, so this kind of answers my question:</p> <pre><code>L = [] L.append(1) if L == [1]: print 'Yay!' # Holds true, but... if L is [1]: print 'Yay!' # Doesn't. </code></pre> <p>So <code>==</code> tests value where <code>is</code> tests to see if they are the same object?</p>
299
2008-09-25T12:27:09Z
133,022
<p><a href="https://docs.python.org/library/stdtypes.html#comparisons" rel="nofollow">https://docs.python.org/library/stdtypes.html#comparisons</a></p> <p><code>is</code> tests for identity <code>==</code> tests for equality</p> <p>Each (small) integer value is mapped to a single value, so every 3 is identical and equal. This is an implementation detail, not part of the language spec though</p>
5
2008-09-25T12:31:57Z
[ "python", "reference", "semantics" ]
Is there a difference between `==` and `is` in Python?
132,988
<p>My <a href="http://en.wiktionary.org/wiki/Google-fu">Google-fu</a> has failed me.</p> <p>In Python, are the following two tests for equality equivalent (ha!)?</p> <pre><code>n = 5 # Test one. if n == 5: print 'Yay!' # Test two. if n is 5: print 'Yay!' </code></pre> <p>Does this hold true for objects where you would be comparing instances (a <code>list</code> say)?</p> <p>Okay, so this kind of answers my question:</p> <pre><code>L = [] L.append(1) if L == [1]: print 'Yay!' # Holds true, but... if L is [1]: print 'Yay!' # Doesn't. </code></pre> <p>So <code>==</code> tests value where <code>is</code> tests to see if they are the same object?</p>
299
2008-09-25T12:27:09Z
133,024
<p><code>is</code> will return <code>True</code> if two variables point to the same object, <code>==</code> if the objects referred to by the variables are equal.</p> <pre><code>&gt;&gt;&gt; a = [1, 2, 3] &gt;&gt;&gt; b = a &gt;&gt;&gt; b is a True &gt;&gt;&gt; b == a True &gt;&gt;&gt; b = a[:] &gt;&gt;&gt; b is a False &gt;&gt;&gt; b == a True </code></pre> <p>In your case, the second test only works because Python caches small integer objects, which is an implementation detail. For larger integers, this does not work:</p> <pre><code>&gt;&gt;&gt; 1000 is 10**3 False &gt;&gt;&gt; 1000 == 10**3 True </code></pre> <p>The same holds true for string literals:</p> <pre><code>&gt;&gt;&gt; "a" is "a" True &gt;&gt;&gt; "aa" is "a" * 2 True &gt;&gt;&gt; x = "a" &gt;&gt;&gt; "aa" is x * 2 False &gt;&gt;&gt; "aa" is intern(x*2) True </code></pre> <p>Please see <a href="http://stackoverflow.com/questions/26595/is-there-any-difference-between-foo-is-none-and-foo-none">this question</a> as well.</p>
439
2008-09-25T12:32:37Z
[ "python", "reference", "semantics" ]
Is there a difference between `==` and `is` in Python?
132,988
<p>My <a href="http://en.wiktionary.org/wiki/Google-fu">Google-fu</a> has failed me.</p> <p>In Python, are the following two tests for equality equivalent (ha!)?</p> <pre><code>n = 5 # Test one. if n == 5: print 'Yay!' # Test two. if n is 5: print 'Yay!' </code></pre> <p>Does this hold true for objects where you would be comparing instances (a <code>list</code> say)?</p> <p>Okay, so this kind of answers my question:</p> <pre><code>L = [] L.append(1) if L == [1]: print 'Yay!' # Holds true, but... if L is [1]: print 'Yay!' # Doesn't. </code></pre> <p>So <code>==</code> tests value where <code>is</code> tests to see if they are the same object?</p>
299
2008-09-25T12:27:09Z
133,035
<p>Your answer is correct. The <code>is</code> operator compares the identity of two objects. The <code>==</code> operator compares the values of two objects.</p> <p>An object's identity never changes once it has been created; you may think of it as the object's address in memory.</p> <p>You can control comparison behaviour of object values by defining a <code>__cmp__</code> method or a <a href="https://docs.python.org/reference/datamodel.html#basic-customization" rel="nofollow">rich comparison</a> method like <code>__eq__</code>.</p>
5
2008-09-25T12:34:18Z
[ "python", "reference", "semantics" ]
Is there a difference between `==` and `is` in Python?
132,988
<p>My <a href="http://en.wiktionary.org/wiki/Google-fu">Google-fu</a> has failed me.</p> <p>In Python, are the following two tests for equality equivalent (ha!)?</p> <pre><code>n = 5 # Test one. if n == 5: print 'Yay!' # Test two. if n is 5: print 'Yay!' </code></pre> <p>Does this hold true for objects where you would be comparing instances (a <code>list</code> say)?</p> <p>Okay, so this kind of answers my question:</p> <pre><code>L = [] L.append(1) if L == [1]: print 'Yay!' # Holds true, but... if L is [1]: print 'Yay!' # Doesn't. </code></pre> <p>So <code>==</code> tests value where <code>is</code> tests to see if they are the same object?</p>
299
2008-09-25T12:27:09Z
134,631
<p>They are <b>completely different</b>. <code>is</code> checks for object identity, while <code>==</code> checks for equality (a notion that depends on the two operands' types).</p> <p>It is only a lucky coincidence that "<code>is</code>" seems to work correctly with small integers (e.g. 5 == 4+1). That is because CPython optimizes the storage of integers in the range (-5 to 256) by making them singletons: <a href="https://docs.python.org/2/c-api/int.html#c.PyInt_FromLong" rel="nofollow">https://docs.python.org/2/c-api/int.html#c.PyInt_FromLong</a></p>
8
2008-09-25T17:15:38Z
[ "python", "reference", "semantics" ]
Is there a difference between `==` and `is` in Python?
132,988
<p>My <a href="http://en.wiktionary.org/wiki/Google-fu">Google-fu</a> has failed me.</p> <p>In Python, are the following two tests for equality equivalent (ha!)?</p> <pre><code>n = 5 # Test one. if n == 5: print 'Yay!' # Test two. if n is 5: print 'Yay!' </code></pre> <p>Does this hold true for objects where you would be comparing instances (a <code>list</code> say)?</p> <p>Okay, so this kind of answers my question:</p> <pre><code>L = [] L.append(1) if L == [1]: print 'Yay!' # Holds true, but... if L is [1]: print 'Yay!' # Doesn't. </code></pre> <p>So <code>==</code> tests value where <code>is</code> tests to see if they are the same object?</p>
299
2008-09-25T12:27:09Z
134,659
<p>Note that this is why <code>if foo is None:</code> is the preferred null comparison for python. All null objects are really pointers to the same value, which python sets aside to mean "None"</p> <p><code>if x is True:</code> and <code>if x is False:</code> also work in a similar manner. False and True are two special objects, all true boolean values are True and all false boolean values are False </p>
21
2008-09-25T17:19:05Z
[ "python", "reference", "semantics" ]
Is there a difference between `==` and `is` in Python?
132,988
<p>My <a href="http://en.wiktionary.org/wiki/Google-fu">Google-fu</a> has failed me.</p> <p>In Python, are the following two tests for equality equivalent (ha!)?</p> <pre><code>n = 5 # Test one. if n == 5: print 'Yay!' # Test two. if n is 5: print 'Yay!' </code></pre> <p>Does this hold true for objects where you would be comparing instances (a <code>list</code> say)?</p> <p>Okay, so this kind of answers my question:</p> <pre><code>L = [] L.append(1) if L == [1]: print 'Yay!' # Holds true, but... if L is [1]: print 'Yay!' # Doesn't. </code></pre> <p>So <code>==</code> tests value where <code>is</code> tests to see if they are the same object?</p>
299
2008-09-25T12:27:09Z
1,085,652
<p>Have a look at Stack Overflow question <em><a href="http://stackoverflow.com/questions/306313">Python's “is” operator behaves unexpectedly with integers</a></em>.</p> <p>What it mostly boils down to is that "<code>is</code>" checks to see if they are the same object, not just equal to each other (the numbers below 256 are a special case).</p>
4
2009-07-06T06:20:00Z
[ "python", "reference", "semantics" ]
Is there a difference between `==` and `is` in Python?
132,988
<p>My <a href="http://en.wiktionary.org/wiki/Google-fu">Google-fu</a> has failed me.</p> <p>In Python, are the following two tests for equality equivalent (ha!)?</p> <pre><code>n = 5 # Test one. if n == 5: print 'Yay!' # Test two. if n is 5: print 'Yay!' </code></pre> <p>Does this hold true for objects where you would be comparing instances (a <code>list</code> say)?</p> <p>Okay, so this kind of answers my question:</p> <pre><code>L = [] L.append(1) if L == [1]: print 'Yay!' # Holds true, but... if L is [1]: print 'Yay!' # Doesn't. </code></pre> <p>So <code>==</code> tests value where <code>is</code> tests to see if they are the same object?</p>
299
2008-09-25T12:27:09Z
1,085,656
<p>There is a simple rule of thumb to tell you when to use <code>==</code> or <code>is</code>.</p> <ul> <li><code>==</code> is for <em>value equality</em>. Use it when you would like to know if two objects have the same value.</li> <li><code>is</code> is for <em>reference equality</em>. Use it when you would like to know if two references refer to the same object.</li> </ul> <p>In general, when you are comparing something to a simple type, you are usually checking for <em>value equality</em>, so you should use <code>==</code>. For example, the intention of your example is probably to check whether x has a value equal to 2 (<code>==</code>), not whether <code>x</code> is literally referring to the same object as 2.</p> <hr> <p>Something else to note: because of the way the CPython reference implementation works, you'll get unexpected and inconsistent results if you mistakenly use <code>is</code> to compare for reference equality on integers:</p> <pre><code>&gt;&gt;&gt; a = 500 &gt;&gt;&gt; b = 500 &gt;&gt;&gt; a == b True &gt;&gt;&gt; a is b False </code></pre> <p>That's pretty much what we expected: <code>a</code> and <code>b</code> have the same value, but are distinct entities. But what about this?</p> <pre><code>&gt;&gt;&gt; c = 200 &gt;&gt;&gt; d = 200 &gt;&gt;&gt; c == d True &gt;&gt;&gt; c is d True </code></pre> <p>This is inconsistent with the earlier result. What's going on here? It turns out the reference implementation of Python caches integer objects in the range -5..256 as singleton instances for performance reasons. Here's an example demonstrating this:</p> <pre><code>&gt;&gt;&gt; for i in range(250, 260): a = i; print "%i: %s" % (i, a is int(str(i))); ... 250: True 251: True 252: True 253: True 254: True 255: True 256: True 257: False 258: False 259: False </code></pre> <p>This is another obvious reason not to use <code>is</code>: the behavior is left up to implementations when you're erroneously using it for value equality.</p>
131
2009-07-06T06:22:52Z
[ "python", "reference", "semantics" ]
Is there a difference between `==` and `is` in Python?
132,988
<p>My <a href="http://en.wiktionary.org/wiki/Google-fu">Google-fu</a> has failed me.</p> <p>In Python, are the following two tests for equality equivalent (ha!)?</p> <pre><code>n = 5 # Test one. if n == 5: print 'Yay!' # Test two. if n is 5: print 'Yay!' </code></pre> <p>Does this hold true for objects where you would be comparing instances (a <code>list</code> say)?</p> <p>Okay, so this kind of answers my question:</p> <pre><code>L = [] L.append(1) if L == [1]: print 'Yay!' # Holds true, but... if L is [1]: print 'Yay!' # Doesn't. </code></pre> <p>So <code>==</code> tests value where <code>is</code> tests to see if they are the same object?</p>
299
2008-09-25T12:27:09Z
1,086,066
<p>As John Feminella said, most of the time you will use == and != because your objective is to compare values. I'd just like to categorise what you would do the rest of the time:</p> <p>There is one and only one instance of NoneType i.e. None is a singleton. Consequently <code>foo == None</code> and <code>foo is None</code> mean the same. However the <code>is</code> test is faster and the Pythonic convention is to use <code>foo is None</code>.</p> <p>If you are doing some introspection or mucking about with garbage collection or checking whether your custom-built string interning gadget is working or suchlike, then you probably have a use-case for <code>foo</code> is <code>bar</code>.</p> <p>True and False are also (now) singletons, but there is no use-case for <code>foo == True</code> and no use case for <code>foo is True</code>. </p>
2
2009-07-06T08:50:52Z
[ "python", "reference", "semantics" ]
Is there a difference between `==` and `is` in Python?
132,988
<p>My <a href="http://en.wiktionary.org/wiki/Google-fu">Google-fu</a> has failed me.</p> <p>In Python, are the following two tests for equality equivalent (ha!)?</p> <pre><code>n = 5 # Test one. if n == 5: print 'Yay!' # Test two. if n is 5: print 'Yay!' </code></pre> <p>Does this hold true for objects where you would be comparing instances (a <code>list</code> say)?</p> <p>Okay, so this kind of answers my question:</p> <pre><code>L = [] L.append(1) if L == [1]: print 'Yay!' # Holds true, but... if L is [1]: print 'Yay!' # Doesn't. </code></pre> <p>So <code>==</code> tests value where <code>is</code> tests to see if they are the same object?</p>
299
2008-09-25T12:27:09Z
31,578,945
<p>While all these answers that rely on the implementation of objection pointer comparison vs value comparison are likely correct, there is a deeper syntactical reason for using <code>is</code> to determine if a variable value is <code>None</code> (in boolean logic often represented as <code>NULL</code>). </p> <p>In relational database and other logic systems, <code>NULL</code> implies that the actual value is "unknown". Thus the logical expression <code>xx == NULL</code> must always evaluate to <code>NULL</code> itself, as it is impossible to ever know if <code>xx</code>, whatever value it may have, is the same as the unknown value. In programming languages that adhere more strictly to the rules of boolean logic, <code>xx == NULL</code> (or Pythonically <code>xx == None</code>) correctly evaluates to <code>NULL</code>, and alternative means must be provided to determine if a variable value is <code>NULL</code>. Python is an outlier in this regard, due to the unitary nature of the object reference to <code>None</code>. But for clarity and logical correctness, using the Python <code>is</code> comparison operator seems to me much sounder practice.</p>
-2
2015-07-23T05:37:21Z
[ "python", "reference", "semantics" ]
Is there a difference between `==` and `is` in Python?
132,988
<p>My <a href="http://en.wiktionary.org/wiki/Google-fu">Google-fu</a> has failed me.</p> <p>In Python, are the following two tests for equality equivalent (ha!)?</p> <pre><code>n = 5 # Test one. if n == 5: print 'Yay!' # Test two. if n is 5: print 'Yay!' </code></pre> <p>Does this hold true for objects where you would be comparing instances (a <code>list</code> say)?</p> <p>Okay, so this kind of answers my question:</p> <pre><code>L = [] L.append(1) if L == [1]: print 'Yay!' # Holds true, but... if L is [1]: print 'Yay!' # Doesn't. </code></pre> <p>So <code>==</code> tests value where <code>is</code> tests to see if they are the same object?</p>
299
2008-09-25T12:27:09Z
37,155,123
<p>Actually I wanted to add this as a comment but could not beautify it easily hence adding as an answer, please do not consider this as an answer. </p> <p>This is what I did to understand --</p> <blockquote> <p>execute following one by one and understand output on every step</p> </blockquote> <pre><code>a = [1,2] b = [1,2,3] b.pop() id(a) id(b) a is b a == b </code></pre>
0
2016-05-11T06:52:25Z
[ "python", "reference", "semantics" ]
Is there a difference between `==` and `is` in Python?
132,988
<p>My <a href="http://en.wiktionary.org/wiki/Google-fu">Google-fu</a> has failed me.</p> <p>In Python, are the following two tests for equality equivalent (ha!)?</p> <pre><code>n = 5 # Test one. if n == 5: print 'Yay!' # Test two. if n is 5: print 'Yay!' </code></pre> <p>Does this hold true for objects where you would be comparing instances (a <code>list</code> say)?</p> <p>Okay, so this kind of answers my question:</p> <pre><code>L = [] L.append(1) if L == [1]: print 'Yay!' # Holds true, but... if L is [1]: print 'Yay!' # Doesn't. </code></pre> <p>So <code>==</code> tests value where <code>is</code> tests to see if they are the same object?</p>
299
2008-09-25T12:27:09Z
39,048,422
<p>"==" compares values</p> <p>"is" compares underlying objects</p> <pre><code># this pgm is to show you the diff b/n == and is # a==b and a is b # == compares values # is compares references i.e compares wether two variables refer to same object(memory) a=10 b=10 print(a==b) # returns True as a,b have same value 10 print(a is b) # returns True, # we usually falsey assume that a =10 a new object . b=10 a new obj created # but actually when b=10 ,nothing but b is pointed to 10 until value of a or b is changed from 10 a=[1] b=[1] print(a==b) #returns True as a,b have a list element 1 print(a is b) #returns False because here two different objs are created when initiated with lists </code></pre>
0
2016-08-19T22:19:54Z
[ "python", "reference", "semantics" ]
Concurrent Access to RRD (RRDTool)
133,774
<p>I am using RRDTool (<a href="http://oss.oetiker.ch/rrdtool/" rel="nofollow">http://oss.oetiker.ch/rrdtool/</a>) as a graphing back-end for storing performance metrics. This is done via the RRDTool CLI from a Python script.</p> <p>My problem is that the script is multithreaded and each thread updates the RRD at a pretty rapid pace. Sometimes an update fails because one thread is accessing the RRD file while another one tries to access it also.</p> <p>I was under the impression that this is OK to try since RRDTool uses its own locking mechanism, but I guess that isn't true.</p> <p>Does anyone have a good approach for concurrent access to an RRD?</p> <p>I can think of a few ways to go:</p> <ol> <li><p>have 1 thread create a queue and only feed the RRD from a single thread.</p></li> <li><p>create my own locking mechanism inside the Python script. (how would I do this?)</p></li> </ol> <p>got anything better or have you run into this issue before?</p>
2
2008-09-25T14:40:55Z
134,023
<p>An exclusive lock ought to be enough for this problem : </p> <ul> <li><a href="http://docs.python.org/lib/lock-objects.html" rel="nofollow">Python doc page</a></li> <li><a href="http://effbot.org/zone/thread-synchronization.htm" rel="nofollow">Use example</a></li> </ul> <p>Define your lock object at the main level, not at the thread level, and you're done.</p> <p>Edit in Response to comment :</p> <p>if you define your lock (<code>lock = new Lock()</code>) at the thread level, you will have one lock object per running thread, and you really want a single lock for the file rrdtool updates, so this definition must be at the main level.</p>
1
2008-09-25T15:32:22Z
[ "python", "rrdtool" ]
Concurrent Access to RRD (RRDTool)
133,774
<p>I am using RRDTool (<a href="http://oss.oetiker.ch/rrdtool/" rel="nofollow">http://oss.oetiker.ch/rrdtool/</a>) as a graphing back-end for storing performance metrics. This is done via the RRDTool CLI from a Python script.</p> <p>My problem is that the script is multithreaded and each thread updates the RRD at a pretty rapid pace. Sometimes an update fails because one thread is accessing the RRD file while another one tries to access it also.</p> <p>I was under the impression that this is OK to try since RRDTool uses its own locking mechanism, but I guess that isn't true.</p> <p>Does anyone have a good approach for concurrent access to an RRD?</p> <p>I can think of a few ways to go:</p> <ol> <li><p>have 1 thread create a queue and only feed the RRD from a single thread.</p></li> <li><p>create my own locking mechanism inside the Python script. (how would I do this?)</p></li> </ol> <p>got anything better or have you run into this issue before?</p>
2
2008-09-25T14:40:55Z
2,199,281
<p>You could also try using rrdcached to do the updates. Then all write updates will be serialised through rrdcached. When you want to read the RRD to generate graphs you tell the daemon to flush it and the on-disk RRD will then represent the latest state.</p> <p>All the RRD tools will do this transparently if pointed at the cached daemon via an environment variable.</p>
2
2010-02-04T11:37:12Z
[ "python", "rrdtool" ]
Concurrent Access to RRD (RRDTool)
133,774
<p>I am using RRDTool (<a href="http://oss.oetiker.ch/rrdtool/" rel="nofollow">http://oss.oetiker.ch/rrdtool/</a>) as a graphing back-end for storing performance metrics. This is done via the RRDTool CLI from a Python script.</p> <p>My problem is that the script is multithreaded and each thread updates the RRD at a pretty rapid pace. Sometimes an update fails because one thread is accessing the RRD file while another one tries to access it also.</p> <p>I was under the impression that this is OK to try since RRDTool uses its own locking mechanism, but I guess that isn't true.</p> <p>Does anyone have a good approach for concurrent access to an RRD?</p> <p>I can think of a few ways to go:</p> <ol> <li><p>have 1 thread create a queue and only feed the RRD from a single thread.</p></li> <li><p>create my own locking mechanism inside the Python script. (how would I do this?)</p></li> </ol> <p>got anything better or have you run into this issue before?</p>
2
2008-09-25T14:40:55Z
3,308,401
<p><a href="http://www.mail-archive.com/[email protected]/msg13015.html" rel="nofollow">This thread</a> in rrd-users list may be useful. The author of rrdtool states that its file locking handles concurrent reads and writes.</p>
1
2010-07-22T11:40:09Z
[ "python", "rrdtool" ]
Concurrent Access to RRD (RRDTool)
133,774
<p>I am using RRDTool (<a href="http://oss.oetiker.ch/rrdtool/" rel="nofollow">http://oss.oetiker.ch/rrdtool/</a>) as a graphing back-end for storing performance metrics. This is done via the RRDTool CLI from a Python script.</p> <p>My problem is that the script is multithreaded and each thread updates the RRD at a pretty rapid pace. Sometimes an update fails because one thread is accessing the RRD file while another one tries to access it also.</p> <p>I was under the impression that this is OK to try since RRDTool uses its own locking mechanism, but I guess that isn't true.</p> <p>Does anyone have a good approach for concurrent access to an RRD?</p> <p>I can think of a few ways to go:</p> <ol> <li><p>have 1 thread create a queue and only feed the RRD from a single thread.</p></li> <li><p>create my own locking mechanism inside the Python script. (how would I do this?)</p></li> </ol> <p>got anything better or have you run into this issue before?</p>
2
2008-09-25T14:40:55Z
26,704,889
<p>I would suggest using <code>rrdcached</code>, which will also improve the performance of your data collector. The latest versions of <code>rrdtool</code> (1.4.x) have greatly improved the functionality and performance of <code>rrdcached</code>; you can tune the caching behaviour according to your data to optimise, too.</p> <p>We make heavy use of rrdcached here with several hundred updates per second over a large number of RRD files.</p>
0
2014-11-02T21:54:03Z
[ "python", "rrdtool" ]
Running subversion under apache and mod_python
133,860
<p>My Apache server runs on some non-default (not-root) account. When it tries to run a python script which in turn executes a subversion check-out command, 'svn checkout' fails with the following error message:</p> <pre><code>svn: Can't open file '/root/.subversion/servers': Permission denied </code></pre> <p>At the same time running that python script with subversion checkout command inside from command line under the same user account goes on perfectly well.</p> <p>Apache server 2.2.6 with mod_python 3.2.8 runs on Fedora Core 6 machine.</p> <p>Can anybody help me out? Thanks a lot.</p>
6
2008-09-25T15:05:26Z
133,963
<p>Try granting the Apache user (the user that the apache service is running under) r+w permissions on that file.</p>
0
2008-09-25T15:24:06Z
[ "python", "svn", "apache" ]
Running subversion under apache and mod_python
133,860
<p>My Apache server runs on some non-default (not-root) account. When it tries to run a python script which in turn executes a subversion check-out command, 'svn checkout' fails with the following error message:</p> <pre><code>svn: Can't open file '/root/.subversion/servers': Permission denied </code></pre> <p>At the same time running that python script with subversion checkout command inside from command line under the same user account goes on perfectly well.</p> <p>Apache server 2.2.6 with mod_python 3.2.8 runs on Fedora Core 6 machine.</p> <p>Can anybody help me out? Thanks a lot.</p>
6
2008-09-25T15:05:26Z
133,983
<p>It sounds like the environment you apache process is running under is a little unusual. For whatever reason, svn seems to think the user configuration files it needs are in /root. You can avoid having svn use the root versions of the files by specifying on the command line which config directory to use, like so:</p> <pre><code>svn --config-dir /home/myuser/.subversion checkout http://example.com/path </code></pre> <p>While not fixing your enviornment, it will at least allow you to have your script run properly...</p>
5
2008-09-25T15:26:22Z
[ "python", "svn", "apache" ]
Running subversion under apache and mod_python
133,860
<p>My Apache server runs on some non-default (not-root) account. When it tries to run a python script which in turn executes a subversion check-out command, 'svn checkout' fails with the following error message:</p> <pre><code>svn: Can't open file '/root/.subversion/servers': Permission denied </code></pre> <p>At the same time running that python script with subversion checkout command inside from command line under the same user account goes on perfectly well.</p> <p>Apache server 2.2.6 with mod_python 3.2.8 runs on Fedora Core 6 machine.</p> <p>Can anybody help me out? Thanks a lot.</p>
6
2008-09-25T15:05:26Z
134,007
<p>Doesn't Apache's error log give you a clue?</p> <p>Maybe it has to do with SELinux. Check /var/log/audit/audit.log and adjust your SELinux configuration accordingly, if the audit.log file indicates that it's SELinux which denies Apache access.</p>
0
2008-09-25T15:30:10Z
[ "python", "svn", "apache" ]
Running subversion under apache and mod_python
133,860
<p>My Apache server runs on some non-default (not-root) account. When it tries to run a python script which in turn executes a subversion check-out command, 'svn checkout' fails with the following error message:</p> <pre><code>svn: Can't open file '/root/.subversion/servers': Permission denied </code></pre> <p>At the same time running that python script with subversion checkout command inside from command line under the same user account goes on perfectly well.</p> <p>Apache server 2.2.6 with mod_python 3.2.8 runs on Fedora Core 6 machine.</p> <p>Can anybody help me out? Thanks a lot.</p>
6
2008-09-25T15:05:26Z
138,587
<p>The Permission Denied error is showing that the script is running with root credentials, because it's looking in root's home dir for files.</p> <p>I suggest you change the hook script to something that does:</p> <pre><code>id &gt; /tmp/id </code></pre> <p>so that you can check the results of that to make sure what the uid/gid and euid/egid are. You will probably find it's not actually running as the user you think it is.</p> <p>My first guess, like Troels, was also SELinux, but that would only be my guess if you are absolutely sure the script through Apache is running with exactly the same user/group as your manual test.</p>
0
2008-09-26T10:06:52Z
[ "python", "svn", "apache" ]
Running subversion under apache and mod_python
133,860
<p>My Apache server runs on some non-default (not-root) account. When it tries to run a python script which in turn executes a subversion check-out command, 'svn checkout' fails with the following error message:</p> <pre><code>svn: Can't open file '/root/.subversion/servers': Permission denied </code></pre> <p>At the same time running that python script with subversion checkout command inside from command line under the same user account goes on perfectly well.</p> <p>Apache server 2.2.6 with mod_python 3.2.8 runs on Fedora Core 6 machine.</p> <p>Can anybody help me out? Thanks a lot.</p>
6
2008-09-25T15:05:26Z
145,501
<p>Well, thanks to all who answered the question. Anyway, I think I solved the mistery. </p> <p>SELinux is completely disabled on the machine, so the problem is definitely in 'svn co' not being able to found config_dir for the user account it runs under.</p> <p>Apache / mod_python doesn't read in shell environment of the user account which apache is running on. Thus for examle no $HOME is seen by mod_python when apache is running under some real user ( not nobody ) </p> <p>Now 'svn co' has a flag --config-dir which points to configuration directory to read params from. By default it is $HOME/.subversion, i.e. it corresponds to the user account home directory. Apparently when no $HOME exists mod_python goes to root home dir ( /root) and tries to fiddle with .subversion content over there - which is obviously fails miserably.</p> <p>putting </p> <p>SetEnv HOME /home/qa </p> <p>into the /etc/httpd/conf/httpd.conf doesn't solve the problem because of SetEnv having nothing to do with shell environment - it only sets apache related environment</p> <p>Likewise PythonOption - sets only mod_python related variables which can be read with req.get_options() after that</p> <p>Running 'svn co --config-dir /home/ ...' definitely gives a workaround for running from within mod_python, but gets in the way of those who will try to run the script from command line.</p> <p>So the proposed ( and working) solution is to set HOME environment variable prior to starting appache.</p> <p>For example in /etc/init.d/httpd script </p> <pre><code> QAHOME=/home/qa ... HOME=$QAHOME LANG=$HTTPD_LANG daemon $httpd $OPTIONS </code></pre>
0
2008-09-28T08:53:26Z
[ "python", "svn", "apache" ]
Running subversion under apache and mod_python
133,860
<p>My Apache server runs on some non-default (not-root) account. When it tries to run a python script which in turn executes a subversion check-out command, 'svn checkout' fails with the following error message:</p> <pre><code>svn: Can't open file '/root/.subversion/servers': Permission denied </code></pre> <p>At the same time running that python script with subversion checkout command inside from command line under the same user account goes on perfectly well.</p> <p>Apache server 2.2.6 with mod_python 3.2.8 runs on Fedora Core 6 machine.</p> <p>Can anybody help me out? Thanks a lot.</p>
6
2008-09-25T15:05:26Z
3,105,538
<p>What is happening is apache is being started with the environment variables of root, so it thinks that it should find its config files in /root/. This is NOT the case. what happens is if you do sudo apache2ctl start, it pulls your $HOME variable from the sudo $HOME=/root/</p> <p>I have just found a solution to this problem myself (although with mod_perl, but same thing)</p> <p>run this command (if its apache 1, remove the 2):</p> <pre><code>sudo /etc/init.d/apache2 stop sudo /etc/init.d/apache2 start </code></pre> <p>When /etc/init.d/apache2 starts apache, it sets all the proper environment variables that apache should be running under.</p>
0
2010-06-23T21:02:18Z
[ "python", "svn", "apache" ]
Efficiently match multiple regexes in Python
133,886
<p>Lexical analyzers are quite easy to write when you have regexes. Today I wanted to write a simple general analyzer in Python, and came up with:</p> <pre><code>import re import sys class Token(object): """ A simple Token structure. Contains the token type, value and position. """ def __init__(self, type, val, pos): self.type = type self.val = val self.pos = pos def __str__(self): return '%s(%s) at %s' % (self.type, self.val, self.pos) class LexerError(Exception): """ Lexer error exception. pos: Position in the input line where the error occurred. """ def __init__(self, pos): self.pos = pos class Lexer(object): """ A simple regex-based lexer/tokenizer. See below for an example of usage. """ def __init__(self, rules, skip_whitespace=True): """ Create a lexer. rules: A list of rules. Each rule is a `regex, type` pair, where `regex` is the regular expression used to recognize the token and `type` is the type of the token to return when it's recognized. skip_whitespace: If True, whitespace (\s+) will be skipped and not reported by the lexer. Otherwise, you have to specify your rules for whitespace, or it will be flagged as an error. """ self.rules = [] for regex, type in rules: self.rules.append((re.compile(regex), type)) self.skip_whitespace = skip_whitespace self.re_ws_skip = re.compile('\S') def input(self, buf): """ Initialize the lexer with a buffer as input. """ self.buf = buf self.pos = 0 def token(self): """ Return the next token (a Token object) found in the input buffer. None is returned if the end of the buffer was reached. In case of a lexing error (the current chunk of the buffer matches no rule), a LexerError is raised with the position of the error. """ if self.pos &gt;= len(self.buf): return None else: if self.skip_whitespace: m = self.re_ws_skip.search(self.buf[self.pos:]) if m: self.pos += m.start() else: return None for token_regex, token_type in self.rules: m = token_regex.match(self.buf[self.pos:]) if m: value = self.buf[self.pos + m.start():self.pos + m.end()] tok = Token(token_type, value, self.pos) self.pos += m.end() return tok # if we're here, no rule matched raise LexerError(self.pos) def tokens(self): """ Returns an iterator to the tokens found in the buffer. """ while 1: tok = self.token() if tok is None: break yield tok if __name__ == '__main__': rules = [ ('\d+', 'NUMBER'), ('[a-zA-Z_]\w+', 'IDENTIFIER'), ('\+', 'PLUS'), ('\-', 'MINUS'), ('\*', 'MULTIPLY'), ('\/', 'DIVIDE'), ('\(', 'LP'), ('\)', 'RP'), ('=', 'EQUALS'), ] lx = Lexer(rules, skip_whitespace=True) lx.input('erw = _abc + 12*(R4-623902) ') try: for tok in lx.tokens(): print tok except LexerError, err: print 'LexerError at position', err.pos </code></pre> <p>It works just fine, but I'm a bit worried that it's too inefficient. Are there any regex tricks that will allow me to write it in a more efficient / elegant way ? </p> <p>Specifically, is there a way to avoid looping over all the regex rules linearly to find one that fits?</p>
13
2008-09-25T15:10:05Z
134,065
<p><code>re.match</code> is anchored. You can give it a position argument:</p> <pre><code>pos = 0 end = len(text) while pos &lt; end: match = regexp.match(text, pos) # do something with your match pos = match.end() </code></pre> <p>Have a look for pygments which ships a shitload of lexers for syntax highlighting purposes with different implementations, most based on regular expressions.</p>
3
2008-09-25T15:38:49Z
[ "python", "regex", "lexical-analysis" ]
Efficiently match multiple regexes in Python
133,886
<p>Lexical analyzers are quite easy to write when you have regexes. Today I wanted to write a simple general analyzer in Python, and came up with:</p> <pre><code>import re import sys class Token(object): """ A simple Token structure. Contains the token type, value and position. """ def __init__(self, type, val, pos): self.type = type self.val = val self.pos = pos def __str__(self): return '%s(%s) at %s' % (self.type, self.val, self.pos) class LexerError(Exception): """ Lexer error exception. pos: Position in the input line where the error occurred. """ def __init__(self, pos): self.pos = pos class Lexer(object): """ A simple regex-based lexer/tokenizer. See below for an example of usage. """ def __init__(self, rules, skip_whitespace=True): """ Create a lexer. rules: A list of rules. Each rule is a `regex, type` pair, where `regex` is the regular expression used to recognize the token and `type` is the type of the token to return when it's recognized. skip_whitespace: If True, whitespace (\s+) will be skipped and not reported by the lexer. Otherwise, you have to specify your rules for whitespace, or it will be flagged as an error. """ self.rules = [] for regex, type in rules: self.rules.append((re.compile(regex), type)) self.skip_whitespace = skip_whitespace self.re_ws_skip = re.compile('\S') def input(self, buf): """ Initialize the lexer with a buffer as input. """ self.buf = buf self.pos = 0 def token(self): """ Return the next token (a Token object) found in the input buffer. None is returned if the end of the buffer was reached. In case of a lexing error (the current chunk of the buffer matches no rule), a LexerError is raised with the position of the error. """ if self.pos &gt;= len(self.buf): return None else: if self.skip_whitespace: m = self.re_ws_skip.search(self.buf[self.pos:]) if m: self.pos += m.start() else: return None for token_regex, token_type in self.rules: m = token_regex.match(self.buf[self.pos:]) if m: value = self.buf[self.pos + m.start():self.pos + m.end()] tok = Token(token_type, value, self.pos) self.pos += m.end() return tok # if we're here, no rule matched raise LexerError(self.pos) def tokens(self): """ Returns an iterator to the tokens found in the buffer. """ while 1: tok = self.token() if tok is None: break yield tok if __name__ == '__main__': rules = [ ('\d+', 'NUMBER'), ('[a-zA-Z_]\w+', 'IDENTIFIER'), ('\+', 'PLUS'), ('\-', 'MINUS'), ('\*', 'MULTIPLY'), ('\/', 'DIVIDE'), ('\(', 'LP'), ('\)', 'RP'), ('=', 'EQUALS'), ] lx = Lexer(rules, skip_whitespace=True) lx.input('erw = _abc + 12*(R4-623902) ') try: for tok in lx.tokens(): print tok except LexerError, err: print 'LexerError at position', err.pos </code></pre> <p>It works just fine, but I'm a bit worried that it's too inefficient. Are there any regex tricks that will allow me to write it in a more efficient / elegant way ? </p> <p>Specifically, is there a way to avoid looping over all the regex rules linearly to find one that fits?</p>
13
2008-09-25T15:10:05Z
134,081
<p>This isn't exactly a direct answer to your question, but you might want to look at <a href="http://www.antlr.org" rel="nofollow">ANTLR</a>. According to <a href="http://www.antlr.org/wiki/display/ANTLR3/Code+Generation+Targets" rel="nofollow">this</a> document the python code generation target should be up to date.</p> <p>As to your regexes, there are really two ways to go about speeding it up if you're sticking to regexes. The first would be to order your regexes in the order of the probability of finding them in a default text. You could figure adding a simple profiler to the code that collected token counts for each token type and running the lexer on a body of work. The other solution would be to bucket sort your regexes (since your key space, being a character, is relatively small) and then use a array or dictionary to perform the needed regexes after performing a single discrimination on the first character.</p> <p>However, I think that if you're going to go this route, you should really try something like <a href="http://www.antlr.org" rel="nofollow">ANTLR</a> which will be easier to maintain, faster, and less likely to have bugs.</p>
1
2008-09-25T15:40:47Z
[ "python", "regex", "lexical-analysis" ]
Efficiently match multiple regexes in Python
133,886
<p>Lexical analyzers are quite easy to write when you have regexes. Today I wanted to write a simple general analyzer in Python, and came up with:</p> <pre><code>import re import sys class Token(object): """ A simple Token structure. Contains the token type, value and position. """ def __init__(self, type, val, pos): self.type = type self.val = val self.pos = pos def __str__(self): return '%s(%s) at %s' % (self.type, self.val, self.pos) class LexerError(Exception): """ Lexer error exception. pos: Position in the input line where the error occurred. """ def __init__(self, pos): self.pos = pos class Lexer(object): """ A simple regex-based lexer/tokenizer. See below for an example of usage. """ def __init__(self, rules, skip_whitespace=True): """ Create a lexer. rules: A list of rules. Each rule is a `regex, type` pair, where `regex` is the regular expression used to recognize the token and `type` is the type of the token to return when it's recognized. skip_whitespace: If True, whitespace (\s+) will be skipped and not reported by the lexer. Otherwise, you have to specify your rules for whitespace, or it will be flagged as an error. """ self.rules = [] for regex, type in rules: self.rules.append((re.compile(regex), type)) self.skip_whitespace = skip_whitespace self.re_ws_skip = re.compile('\S') def input(self, buf): """ Initialize the lexer with a buffer as input. """ self.buf = buf self.pos = 0 def token(self): """ Return the next token (a Token object) found in the input buffer. None is returned if the end of the buffer was reached. In case of a lexing error (the current chunk of the buffer matches no rule), a LexerError is raised with the position of the error. """ if self.pos &gt;= len(self.buf): return None else: if self.skip_whitespace: m = self.re_ws_skip.search(self.buf[self.pos:]) if m: self.pos += m.start() else: return None for token_regex, token_type in self.rules: m = token_regex.match(self.buf[self.pos:]) if m: value = self.buf[self.pos + m.start():self.pos + m.end()] tok = Token(token_type, value, self.pos) self.pos += m.end() return tok # if we're here, no rule matched raise LexerError(self.pos) def tokens(self): """ Returns an iterator to the tokens found in the buffer. """ while 1: tok = self.token() if tok is None: break yield tok if __name__ == '__main__': rules = [ ('\d+', 'NUMBER'), ('[a-zA-Z_]\w+', 'IDENTIFIER'), ('\+', 'PLUS'), ('\-', 'MINUS'), ('\*', 'MULTIPLY'), ('\/', 'DIVIDE'), ('\(', 'LP'), ('\)', 'RP'), ('=', 'EQUALS'), ] lx = Lexer(rules, skip_whitespace=True) lx.input('erw = _abc + 12*(R4-623902) ') try: for tok in lx.tokens(): print tok except LexerError, err: print 'LexerError at position', err.pos </code></pre> <p>It works just fine, but I'm a bit worried that it's too inefficient. Are there any regex tricks that will allow me to write it in a more efficient / elegant way ? </p> <p>Specifically, is there a way to avoid looping over all the regex rules linearly to find one that fits?</p>
13
2008-09-25T15:10:05Z
134,168
<p>You can merge all your regexes into one using the "|" operator and let the regex library do the work of discerning between tokens. Some care should be taken to ensure the preference of tokens (for example to avoid matching a keyword as an identifier).</p>
7
2008-09-25T15:54:53Z
[ "python", "regex", "lexical-analysis" ]
Efficiently match multiple regexes in Python
133,886
<p>Lexical analyzers are quite easy to write when you have regexes. Today I wanted to write a simple general analyzer in Python, and came up with:</p> <pre><code>import re import sys class Token(object): """ A simple Token structure. Contains the token type, value and position. """ def __init__(self, type, val, pos): self.type = type self.val = val self.pos = pos def __str__(self): return '%s(%s) at %s' % (self.type, self.val, self.pos) class LexerError(Exception): """ Lexer error exception. pos: Position in the input line where the error occurred. """ def __init__(self, pos): self.pos = pos class Lexer(object): """ A simple regex-based lexer/tokenizer. See below for an example of usage. """ def __init__(self, rules, skip_whitespace=True): """ Create a lexer. rules: A list of rules. Each rule is a `regex, type` pair, where `regex` is the regular expression used to recognize the token and `type` is the type of the token to return when it's recognized. skip_whitespace: If True, whitespace (\s+) will be skipped and not reported by the lexer. Otherwise, you have to specify your rules for whitespace, or it will be flagged as an error. """ self.rules = [] for regex, type in rules: self.rules.append((re.compile(regex), type)) self.skip_whitespace = skip_whitespace self.re_ws_skip = re.compile('\S') def input(self, buf): """ Initialize the lexer with a buffer as input. """ self.buf = buf self.pos = 0 def token(self): """ Return the next token (a Token object) found in the input buffer. None is returned if the end of the buffer was reached. In case of a lexing error (the current chunk of the buffer matches no rule), a LexerError is raised with the position of the error. """ if self.pos &gt;= len(self.buf): return None else: if self.skip_whitespace: m = self.re_ws_skip.search(self.buf[self.pos:]) if m: self.pos += m.start() else: return None for token_regex, token_type in self.rules: m = token_regex.match(self.buf[self.pos:]) if m: value = self.buf[self.pos + m.start():self.pos + m.end()] tok = Token(token_type, value, self.pos) self.pos += m.end() return tok # if we're here, no rule matched raise LexerError(self.pos) def tokens(self): """ Returns an iterator to the tokens found in the buffer. """ while 1: tok = self.token() if tok is None: break yield tok if __name__ == '__main__': rules = [ ('\d+', 'NUMBER'), ('[a-zA-Z_]\w+', 'IDENTIFIER'), ('\+', 'PLUS'), ('\-', 'MINUS'), ('\*', 'MULTIPLY'), ('\/', 'DIVIDE'), ('\(', 'LP'), ('\)', 'RP'), ('=', 'EQUALS'), ] lx = Lexer(rules, skip_whitespace=True) lx.input('erw = _abc + 12*(R4-623902) ') try: for tok in lx.tokens(): print tok except LexerError, err: print 'LexerError at position', err.pos </code></pre> <p>It works just fine, but I'm a bit worried that it's too inefficient. Are there any regex tricks that will allow me to write it in a more efficient / elegant way ? </p> <p>Specifically, is there a way to avoid looping over all the regex rules linearly to find one that fits?</p>
13
2008-09-25T15:10:05Z
135,421
<p>It's possible that combining the token regexes will work, but you'd have to benchmark it. Something like:</p> <pre><code>x = re.compile('(?P&lt;NUMBER&gt;[0-9]+)|(?P&lt;VAR&gt;[a-z]+)') a = x.match('9999').groupdict() # =&gt; {'VAR': None, 'NUMBER': '9999'} if a: token = [a for a in a.items() if a[1] != None][0] </code></pre> <p>The filter is where you'll have to do some benchmarking...</p> <p><strong>Update:</strong> I tested this, and it seems as though if you combine all the tokens as stated and write a function like:</p> <pre><code>def find_token(lst): for tok in lst: if tok[1] != None: return tok raise Exception </code></pre> <p>You'll get roughly the same speed (maybe a teensy faster) for this. I believe the speedup must be in the number of calls to match, but the loop for token discrimination is still there, which of course kills it.</p>
3
2008-09-25T19:24:13Z
[ "python", "regex", "lexical-analysis" ]
Efficiently match multiple regexes in Python
133,886
<p>Lexical analyzers are quite easy to write when you have regexes. Today I wanted to write a simple general analyzer in Python, and came up with:</p> <pre><code>import re import sys class Token(object): """ A simple Token structure. Contains the token type, value and position. """ def __init__(self, type, val, pos): self.type = type self.val = val self.pos = pos def __str__(self): return '%s(%s) at %s' % (self.type, self.val, self.pos) class LexerError(Exception): """ Lexer error exception. pos: Position in the input line where the error occurred. """ def __init__(self, pos): self.pos = pos class Lexer(object): """ A simple regex-based lexer/tokenizer. See below for an example of usage. """ def __init__(self, rules, skip_whitespace=True): """ Create a lexer. rules: A list of rules. Each rule is a `regex, type` pair, where `regex` is the regular expression used to recognize the token and `type` is the type of the token to return when it's recognized. skip_whitespace: If True, whitespace (\s+) will be skipped and not reported by the lexer. Otherwise, you have to specify your rules for whitespace, or it will be flagged as an error. """ self.rules = [] for regex, type in rules: self.rules.append((re.compile(regex), type)) self.skip_whitespace = skip_whitespace self.re_ws_skip = re.compile('\S') def input(self, buf): """ Initialize the lexer with a buffer as input. """ self.buf = buf self.pos = 0 def token(self): """ Return the next token (a Token object) found in the input buffer. None is returned if the end of the buffer was reached. In case of a lexing error (the current chunk of the buffer matches no rule), a LexerError is raised with the position of the error. """ if self.pos &gt;= len(self.buf): return None else: if self.skip_whitespace: m = self.re_ws_skip.search(self.buf[self.pos:]) if m: self.pos += m.start() else: return None for token_regex, token_type in self.rules: m = token_regex.match(self.buf[self.pos:]) if m: value = self.buf[self.pos + m.start():self.pos + m.end()] tok = Token(token_type, value, self.pos) self.pos += m.end() return tok # if we're here, no rule matched raise LexerError(self.pos) def tokens(self): """ Returns an iterator to the tokens found in the buffer. """ while 1: tok = self.token() if tok is None: break yield tok if __name__ == '__main__': rules = [ ('\d+', 'NUMBER'), ('[a-zA-Z_]\w+', 'IDENTIFIER'), ('\+', 'PLUS'), ('\-', 'MINUS'), ('\*', 'MULTIPLY'), ('\/', 'DIVIDE'), ('\(', 'LP'), ('\)', 'RP'), ('=', 'EQUALS'), ] lx = Lexer(rules, skip_whitespace=True) lx.input('erw = _abc + 12*(R4-623902) ') try: for tok in lx.tokens(): print tok except LexerError, err: print 'LexerError at position', err.pos </code></pre> <p>It works just fine, but I'm a bit worried that it's too inefficient. Are there any regex tricks that will allow me to write it in a more efficient / elegant way ? </p> <p>Specifically, is there a way to avoid looping over all the regex rules linearly to find one that fits?</p>
13
2008-09-25T15:10:05Z
953,837
<p>these are not so simple, but may be worth looking at...</p> <p>python module <strong>pyparsing</strong> (pyparsing.wikispaces.com) allows specifying grammar - then using it to parse text. Douglas, thanks for the post about <strong>ANTLR</strong> I haven't heard of it. Also there's <strong>PLY</strong> - python2 and python3 compatible implementation of lex/yacc.</p> <p>I've written an ad-hoc regex-based parser myself first, but later realized that I might benefit from using some mature parsing tool and learning concepts of context independent grammar, etc.</p> <p>The advantage of using grammar for parsing is that you can easily modify the rules and formalize quite complex syntax for whatever you are parsing.</p>
0
2009-06-05T01:04:16Z
[ "python", "regex", "lexical-analysis" ]
Efficiently match multiple regexes in Python
133,886
<p>Lexical analyzers are quite easy to write when you have regexes. Today I wanted to write a simple general analyzer in Python, and came up with:</p> <pre><code>import re import sys class Token(object): """ A simple Token structure. Contains the token type, value and position. """ def __init__(self, type, val, pos): self.type = type self.val = val self.pos = pos def __str__(self): return '%s(%s) at %s' % (self.type, self.val, self.pos) class LexerError(Exception): """ Lexer error exception. pos: Position in the input line where the error occurred. """ def __init__(self, pos): self.pos = pos class Lexer(object): """ A simple regex-based lexer/tokenizer. See below for an example of usage. """ def __init__(self, rules, skip_whitespace=True): """ Create a lexer. rules: A list of rules. Each rule is a `regex, type` pair, where `regex` is the regular expression used to recognize the token and `type` is the type of the token to return when it's recognized. skip_whitespace: If True, whitespace (\s+) will be skipped and not reported by the lexer. Otherwise, you have to specify your rules for whitespace, or it will be flagged as an error. """ self.rules = [] for regex, type in rules: self.rules.append((re.compile(regex), type)) self.skip_whitespace = skip_whitespace self.re_ws_skip = re.compile('\S') def input(self, buf): """ Initialize the lexer with a buffer as input. """ self.buf = buf self.pos = 0 def token(self): """ Return the next token (a Token object) found in the input buffer. None is returned if the end of the buffer was reached. In case of a lexing error (the current chunk of the buffer matches no rule), a LexerError is raised with the position of the error. """ if self.pos &gt;= len(self.buf): return None else: if self.skip_whitespace: m = self.re_ws_skip.search(self.buf[self.pos:]) if m: self.pos += m.start() else: return None for token_regex, token_type in self.rules: m = token_regex.match(self.buf[self.pos:]) if m: value = self.buf[self.pos + m.start():self.pos + m.end()] tok = Token(token_type, value, self.pos) self.pos += m.end() return tok # if we're here, no rule matched raise LexerError(self.pos) def tokens(self): """ Returns an iterator to the tokens found in the buffer. """ while 1: tok = self.token() if tok is None: break yield tok if __name__ == '__main__': rules = [ ('\d+', 'NUMBER'), ('[a-zA-Z_]\w+', 'IDENTIFIER'), ('\+', 'PLUS'), ('\-', 'MINUS'), ('\*', 'MULTIPLY'), ('\/', 'DIVIDE'), ('\(', 'LP'), ('\)', 'RP'), ('=', 'EQUALS'), ] lx = Lexer(rules, skip_whitespace=True) lx.input('erw = _abc + 12*(R4-623902) ') try: for tok in lx.tokens(): print tok except LexerError, err: print 'LexerError at position', err.pos </code></pre> <p>It works just fine, but I'm a bit worried that it's too inefficient. Are there any regex tricks that will allow me to write it in a more efficient / elegant way ? </p> <p>Specifically, is there a way to avoid looping over all the regex rules linearly to find one that fits?</p>
13
2008-09-25T15:10:05Z
4,136,323
<p>I suggest using the re.Scanner class, it's not documented in the standard library, but it's well worth using. Here's an example:</p> <pre><code>import re scanner = re.Scanner([ (r"-?[0-9]+\.[0-9]+([eE]-?[0-9]+)?", lambda scanner, token: float(token)), (r"-?[0-9]+", lambda scanner, token: int(token)), (r" +", lambda scanner, token: None), ]) &gt;&gt;&gt; scanner.scan("0 -1 4.5 7.8e3")[0] [0, -1, 4.5, 7800.0] </code></pre>
11
2010-11-09T16:59:03Z
[ "python", "regex", "lexical-analysis" ]
Efficiently match multiple regexes in Python
133,886
<p>Lexical analyzers are quite easy to write when you have regexes. Today I wanted to write a simple general analyzer in Python, and came up with:</p> <pre><code>import re import sys class Token(object): """ A simple Token structure. Contains the token type, value and position. """ def __init__(self, type, val, pos): self.type = type self.val = val self.pos = pos def __str__(self): return '%s(%s) at %s' % (self.type, self.val, self.pos) class LexerError(Exception): """ Lexer error exception. pos: Position in the input line where the error occurred. """ def __init__(self, pos): self.pos = pos class Lexer(object): """ A simple regex-based lexer/tokenizer. See below for an example of usage. """ def __init__(self, rules, skip_whitespace=True): """ Create a lexer. rules: A list of rules. Each rule is a `regex, type` pair, where `regex` is the regular expression used to recognize the token and `type` is the type of the token to return when it's recognized. skip_whitespace: If True, whitespace (\s+) will be skipped and not reported by the lexer. Otherwise, you have to specify your rules for whitespace, or it will be flagged as an error. """ self.rules = [] for regex, type in rules: self.rules.append((re.compile(regex), type)) self.skip_whitespace = skip_whitespace self.re_ws_skip = re.compile('\S') def input(self, buf): """ Initialize the lexer with a buffer as input. """ self.buf = buf self.pos = 0 def token(self): """ Return the next token (a Token object) found in the input buffer. None is returned if the end of the buffer was reached. In case of a lexing error (the current chunk of the buffer matches no rule), a LexerError is raised with the position of the error. """ if self.pos &gt;= len(self.buf): return None else: if self.skip_whitespace: m = self.re_ws_skip.search(self.buf[self.pos:]) if m: self.pos += m.start() else: return None for token_regex, token_type in self.rules: m = token_regex.match(self.buf[self.pos:]) if m: value = self.buf[self.pos + m.start():self.pos + m.end()] tok = Token(token_type, value, self.pos) self.pos += m.end() return tok # if we're here, no rule matched raise LexerError(self.pos) def tokens(self): """ Returns an iterator to the tokens found in the buffer. """ while 1: tok = self.token() if tok is None: break yield tok if __name__ == '__main__': rules = [ ('\d+', 'NUMBER'), ('[a-zA-Z_]\w+', 'IDENTIFIER'), ('\+', 'PLUS'), ('\-', 'MINUS'), ('\*', 'MULTIPLY'), ('\/', 'DIVIDE'), ('\(', 'LP'), ('\)', 'RP'), ('=', 'EQUALS'), ] lx = Lexer(rules, skip_whitespace=True) lx.input('erw = _abc + 12*(R4-623902) ') try: for tok in lx.tokens(): print tok except LexerError, err: print 'LexerError at position', err.pos </code></pre> <p>It works just fine, but I'm a bit worried that it's too inefficient. Are there any regex tricks that will allow me to write it in a more efficient / elegant way ? </p> <p>Specifically, is there a way to avoid looping over all the regex rules linearly to find one that fits?</p>
13
2008-09-25T15:10:05Z
14,919,449
<p>I found <a href="http://docs.python.org/3/library/re.html#writing-a-tokenizer" rel="nofollow">this</a> in python document. It's just simple and elegant.</p> <pre><code>import collections import re Token = collections.namedtuple('Token', ['typ', 'value', 'line', 'column']) def tokenize(s): keywords = {'IF', 'THEN', 'ENDIF', 'FOR', 'NEXT', 'GOSUB', 'RETURN'} token_specification = [ ('NUMBER', r'\d+(\.\d*)?'), # Integer or decimal number ('ASSIGN', r':='), # Assignment operator ('END', r';'), # Statement terminator ('ID', r'[A-Za-z]+'), # Identifiers ('OP', r'[+*\/\-]'), # Arithmetic operators ('NEWLINE', r'\n'), # Line endings ('SKIP', r'[ \t]'), # Skip over spaces and tabs ] tok_regex = '|'.join('(?P&lt;%s&gt;%s)' % pair for pair in token_specification) get_token = re.compile(tok_regex).match line = 1 pos = line_start = 0 mo = get_token(s) while mo is not None: typ = mo.lastgroup if typ == 'NEWLINE': line_start = pos line += 1 elif typ != 'SKIP': val = mo.group(typ) if typ == 'ID' and val in keywords: typ = val yield Token(typ, val, line, mo.start()-line_start) pos = mo.end() mo = get_token(s, pos) if pos != len(s): raise RuntimeError('Unexpected character %r on line %d' %(s[pos], line)) statements = ''' IF quantity THEN total := total + price * quantity; tax := price * 0.05; ENDIF; ''' for token in tokenize(statements): print(token) </code></pre> <p>The trick here is the line:</p> <pre><code>tok_regex = '|'.join('(?P&lt;%s&gt;%s)' % pair for pair in token_specification) </code></pre> <p>Here <code>(?P&lt;ID&gt;PATTERN)</code> will mark the matched result with a name specified by <code>ID</code>.</p>
6
2013-02-17T08:51:33Z
[ "python", "regex", "lexical-analysis" ]
Run Pylons controller as separate app?
134,387
<p>I have a Pylons app where I would like to move some of the logic to a separate batch process. I've been running it under the main app for testing, but it is going to be doing a lot of work in the database, and I'd like it to be a separate process that will be running in the background constantly. The main pylons app will submit jobs into the database, and the new process will do the work requested in each job.</p> <p>How can I launch a controller as a stand alone script?</p> <p>I currently have:</p> <pre><code>from warehouse2.controllers import importServer importServer.runServer(60) </code></pre> <p>and in the controller file, but not part of the controller class:</p> <pre><code>def runServer(sleep_secs): try: imp = ImportserverController() while(True): imp.runImport() sleepFor(sleep_secs) except Exception, e: log.info("Unexpected error: %s" % sys.exc_info()[0]) log.info(e) </code></pre> <p>But starting ImportServer.py on the command line results in:</p> <pre><code>2008-09-25 12:31:12.687000 Could not locate a bind configured on mapper Mapper|I mportJob|n_imports, SQL expression or this Session </code></pre>
10
2008-09-25T16:34:14Z
135,290
<p>I'm redacting my response and upvoting the other answer by Ben Bangert, as it's the correct one. I answered and have since learned the correct way (mentioned below). If you really want to, check out the history of this answer to see the wrong (but working) solution I originally proposed.</p>
1
2008-09-25T19:04:57Z
[ "python", "pylons" ]
Run Pylons controller as separate app?
134,387
<p>I have a Pylons app where I would like to move some of the logic to a separate batch process. I've been running it under the main app for testing, but it is going to be doing a lot of work in the database, and I'd like it to be a separate process that will be running in the background constantly. The main pylons app will submit jobs into the database, and the new process will do the work requested in each job.</p> <p>How can I launch a controller as a stand alone script?</p> <p>I currently have:</p> <pre><code>from warehouse2.controllers import importServer importServer.runServer(60) </code></pre> <p>and in the controller file, but not part of the controller class:</p> <pre><code>def runServer(sleep_secs): try: imp = ImportserverController() while(True): imp.runImport() sleepFor(sleep_secs) except Exception, e: log.info("Unexpected error: %s" % sys.exc_info()[0]) log.info(e) </code></pre> <p>But starting ImportServer.py on the command line results in:</p> <pre><code>2008-09-25 12:31:12.687000 Could not locate a bind configured on mapper Mapper|I mportJob|n_imports, SQL expression or this Session </code></pre>
10
2008-09-25T16:34:14Z
784,421
<p>If you want to load parts of a Pylons app, such as the models from outside Pylons, load the Pylons app in the script first:</p> <pre><code>from paste.deploy import appconfig from pylons import config from YOURPROJ.config.environment import load_environment conf = appconfig('config:development.ini', relative_to='.') load_environment(conf.global_conf, conf.local_conf) </code></pre> <p>That will load the Pylons app, which sets up most of the state so that you can proceed to use the SQLAlchemy models and Session to work with the database.</p> <p>Note that if your code is using the pylons globals such as request/response/etc then that won't work since they require a request to be in progress to exist.</p>
11
2009-04-24T03:42:01Z
[ "python", "pylons" ]
Which is more preferable to use in Python: lambda functions or nested functions ('def')?
134,626
<p>I mostly use lambda functions but sometimes use nested functions that seem to provide the same behavior. </p> <p>Here are some trivial examples where they functionally do the same thing if either were found within another function:</p> <p><strong>Lambda function</strong></p> <pre><code>&gt;&gt;&gt; a = lambda x : 1 + x &gt;&gt;&gt; a(5) 6 </code></pre> <p><strong>Nested function</strong></p> <pre><code>&gt;&gt;&gt; def b(x): return 1 + x &gt;&gt;&gt; b(5) 6 </code></pre> <p>Is there advantages to using one over the other? (Performance? Readability? Limitations? Consistency? etc.) Does it even matter? If doesn't then does that violate the Pythonic principle: <a href="http://en.wikipedia.org/wiki/Python_(programming_language)#Philosophy">“There should be one—and preferably only one—obvious way to do it”</a>.</p>
58
2008-09-25T17:15:03Z
134,638
<p>If you need to assign the <code>lambda</code> to a name, use a <code>def</code> instead. <code>def</code>s are just syntactic sugar for an assignment, so the result is the same, and they are a lot more flexible and readable.</p> <p><code>lambda</code>s can be used for <em>use once, throw away</em> functions which won't have a name.</p> <p>However, this use case is very rare. You rarely need to pass around unnamed function objects.</p> <p>The builtins <code>map()</code> and <code>filter()</code> need function objects, but <strong>list comprehensions</strong> and <strong>generator expressions</strong> are generally more readable than those functions and can cover all use cases, without the need of lambdas. </p> <p>For the cases you really need a small function object, you should use the <code>operator</code> module functions, like <code>operator.add</code> instead of <code>lambda x, y: x + y</code></p> <p>If you still need some <code>lambda</code> not covered, you might consider writing a <code>def</code>, just to be more readable. If the function is more complex than the ones at <code>operator</code> module, a <code>def</code> is probably better. </p> <p>So, real world good <code>lambda</code> use cases are very rare.</p>
65
2008-09-25T17:16:31Z
[ "python", "syntax", "function", "lambda" ]
Which is more preferable to use in Python: lambda functions or nested functions ('def')?
134,626
<p>I mostly use lambda functions but sometimes use nested functions that seem to provide the same behavior. </p> <p>Here are some trivial examples where they functionally do the same thing if either were found within another function:</p> <p><strong>Lambda function</strong></p> <pre><code>&gt;&gt;&gt; a = lambda x : 1 + x &gt;&gt;&gt; a(5) 6 </code></pre> <p><strong>Nested function</strong></p> <pre><code>&gt;&gt;&gt; def b(x): return 1 + x &gt;&gt;&gt; b(5) 6 </code></pre> <p>Is there advantages to using one over the other? (Performance? Readability? Limitations? Consistency? etc.) Does it even matter? If doesn't then does that violate the Pythonic principle: <a href="http://en.wikipedia.org/wiki/Python_(programming_language)#Philosophy">“There should be one—and preferably only one—obvious way to do it”</a>.</p>
58
2008-09-25T17:15:03Z
134,664
<p>I agree with nosklo's advice: if you need to give the function a name, use <code>def</code>. I reserve <code>lambda</code> functions for cases where I'm just passing a brief snippet of code to another function, e.g.:</p> <pre><code>a = [ (1,2), (3,4), (5,6) ] b = map( lambda x: x[0]+x[1], a ) </code></pre>
6
2008-09-25T17:19:48Z
[ "python", "syntax", "function", "lambda" ]
Which is more preferable to use in Python: lambda functions or nested functions ('def')?
134,626
<p>I mostly use lambda functions but sometimes use nested functions that seem to provide the same behavior. </p> <p>Here are some trivial examples where they functionally do the same thing if either were found within another function:</p> <p><strong>Lambda function</strong></p> <pre><code>&gt;&gt;&gt; a = lambda x : 1 + x &gt;&gt;&gt; a(5) 6 </code></pre> <p><strong>Nested function</strong></p> <pre><code>&gt;&gt;&gt; def b(x): return 1 + x &gt;&gt;&gt; b(5) 6 </code></pre> <p>Is there advantages to using one over the other? (Performance? Readability? Limitations? Consistency? etc.) Does it even matter? If doesn't then does that violate the Pythonic principle: <a href="http://en.wikipedia.org/wiki/Python_(programming_language)#Philosophy">“There should be one—and preferably only one—obvious way to do it”</a>.</p>
58
2008-09-25T17:15:03Z
134,709
<p><a href="http://www.amk.ca/python/writing/gvr-interview">In this interview, </a> Guido van Rossum says he wishes he hadn't let 'lambda' into Python:</p> <blockquote> <p>"<strong>Q. What feature of Python are you least pleased with?</strong><br /><br /> Sometimes I've been too quick in accepting contributions, and later realized that it was a mistake. One example would be some of the functional programming features, such as lambda functions. lambda is a keyword that lets you create a small anonymous function; built-in functions such as map, filter, and reduce run a function over a sequence type, such as a list.<br /><br /> In practice, it didn't turn out that well. Python only has two scopes: local and global. This makes writing lambda functions painful, because you often want to access variables in the scope where the lambda was defined, but you can't because of the two scopes. There's a way around this, but it's something of a kludge. Often it seems much easier in Python to just use a for loop instead of messing around with lambda functions. map and friends work well only when there's already a built-in function that does what you want.</p> </blockquote> <p>IMHO, Iambdas can be convenient sometimes, but usually are convenient at the expense of readibility. Can you tell me what this does:</p> <pre><code>str(reduce(lambda x,y:x+y,map(lambda x:x**x,range(1,1001))))[-10:] </code></pre> <p>I wrote it, and it took me a minute to figure it out. This is from Project Euler - i won't say which problem because i hate spoilers, but it runs in 0.124 seconds :)</p>
13
2008-09-25T17:29:26Z
[ "python", "syntax", "function", "lambda" ]
Which is more preferable to use in Python: lambda functions or nested functions ('def')?
134,626
<p>I mostly use lambda functions but sometimes use nested functions that seem to provide the same behavior. </p> <p>Here are some trivial examples where they functionally do the same thing if either were found within another function:</p> <p><strong>Lambda function</strong></p> <pre><code>&gt;&gt;&gt; a = lambda x : 1 + x &gt;&gt;&gt; a(5) 6 </code></pre> <p><strong>Nested function</strong></p> <pre><code>&gt;&gt;&gt; def b(x): return 1 + x &gt;&gt;&gt; b(5) 6 </code></pre> <p>Is there advantages to using one over the other? (Performance? Readability? Limitations? Consistency? etc.) Does it even matter? If doesn't then does that violate the Pythonic principle: <a href="http://en.wikipedia.org/wiki/Python_(programming_language)#Philosophy">“There should be one—and preferably only one—obvious way to do it”</a>.</p>
58
2008-09-25T17:15:03Z
135,353
<p>The primary use of lambda has always been for simple callback functions, and for map, reduce, filter, which require a function as an argument. With list comprehensions becoming the norm, and the added allowed if as in:</p> <pre><code>x = [f for f in range(1, 40) if f % 2] </code></pre> <p>it's hard to imagine a real case for the use of lambda in daily use. As a result, I'd say, avoid lambda and create nested functions.</p>
3
2008-09-25T19:13:39Z
[ "python", "syntax", "function", "lambda" ]
Which is more preferable to use in Python: lambda functions or nested functions ('def')?
134,626
<p>I mostly use lambda functions but sometimes use nested functions that seem to provide the same behavior. </p> <p>Here are some trivial examples where they functionally do the same thing if either were found within another function:</p> <p><strong>Lambda function</strong></p> <pre><code>&gt;&gt;&gt; a = lambda x : 1 + x &gt;&gt;&gt; a(5) 6 </code></pre> <p><strong>Nested function</strong></p> <pre><code>&gt;&gt;&gt; def b(x): return 1 + x &gt;&gt;&gt; b(5) 6 </code></pre> <p>Is there advantages to using one over the other? (Performance? Readability? Limitations? Consistency? etc.) Does it even matter? If doesn't then does that violate the Pythonic principle: <a href="http://en.wikipedia.org/wiki/Python_(programming_language)#Philosophy">“There should be one—and preferably only one—obvious way to do it”</a>.</p>
58
2008-09-25T17:15:03Z
135,815
<p>I agree with nosklo. By the way, even with a <em>use once, throw away</em> function, most of the time you just want to use something from the operator module.</p> <p>E.G : </p> <p>You have a function with this signature : myFunction(data, callback function).</p> <p>You want to pass a function that add 2 elements.</p> <p>Using lambda :</p> <pre><code>myFunction(data, (lambda x, y : x + y)) </code></pre> <p>The pythonic way :</p> <pre><code>import operator myFunction(data, operator.add) </code></pre> <p>Or course this is a simple example, but there is a lot of stuff the operator module provides, including the items setters / getters for list and dict. Really cool.</p>
0
2008-09-25T20:26:14Z
[ "python", "syntax", "function", "lambda" ]
Which is more preferable to use in Python: lambda functions or nested functions ('def')?
134,626
<p>I mostly use lambda functions but sometimes use nested functions that seem to provide the same behavior. </p> <p>Here are some trivial examples where they functionally do the same thing if either were found within another function:</p> <p><strong>Lambda function</strong></p> <pre><code>&gt;&gt;&gt; a = lambda x : 1 + x &gt;&gt;&gt; a(5) 6 </code></pre> <p><strong>Nested function</strong></p> <pre><code>&gt;&gt;&gt; def b(x): return 1 + x &gt;&gt;&gt; b(5) 6 </code></pre> <p>Is there advantages to using one over the other? (Performance? Readability? Limitations? Consistency? etc.) Does it even matter? If doesn't then does that violate the Pythonic principle: <a href="http://en.wikipedia.org/wiki/Python_(programming_language)#Philosophy">“There should be one—and preferably only one—obvious way to do it”</a>.</p>
58
2008-09-25T17:15:03Z
138,625
<p>Practically speaking, to me there are two differences:</p> <p>The first is about what they do and what they return:</p> <ul> <li><p>def is a keyword that doesn't return anything and creates a 'name' in the local namespace.</p></li> <li><p>lambda is a keyword that returns a function object and does not create a 'name' in the local namespace.</p></li> </ul> <p>Hence, if you need to call a function that takes a function object, the only way to do that in one line of python code is with a lambda. There's no equivalent with def.</p> <p>In some frameworks this is actually quite common; for example, I use <a href="http://twistedmatrix.com/">Twisted</a> a lot, and so doing something like</p> <pre><code>d.addCallback(lambda result: setattr(self, _someVariable, result)) </code></pre> <p>is quite common, and more concise with lambdas.</p> <p>The second difference is about what the actual function is allowed to do.</p> <ul> <li>A function defined with 'def' can contain any python code</li> <li>A function defined with 'lambda' has to evaluate to an expression, and can thus not contain statements like print, import, raise, ... </li> </ul> <p>For example,</p> <pre><code>def p(x): print x </code></pre> <p>works as expected, while</p> <pre><code>lambda x: print x </code></pre> <p>is a SyntaxError.</p> <p>Of course, there are workarounds - substitute <code>print</code> with <code>sys.stdout.write</code>, or <code>import</code> with <code>__import__</code>. But usually you're better off going with a function in that case.</p>
22
2008-09-26T10:20:43Z
[ "python", "syntax", "function", "lambda" ]
Which is more preferable to use in Python: lambda functions or nested functions ('def')?
134,626
<p>I mostly use lambda functions but sometimes use nested functions that seem to provide the same behavior. </p> <p>Here are some trivial examples where they functionally do the same thing if either were found within another function:</p> <p><strong>Lambda function</strong></p> <pre><code>&gt;&gt;&gt; a = lambda x : 1 + x &gt;&gt;&gt; a(5) 6 </code></pre> <p><strong>Nested function</strong></p> <pre><code>&gt;&gt;&gt; def b(x): return 1 + x &gt;&gt;&gt; b(5) 6 </code></pre> <p>Is there advantages to using one over the other? (Performance? Readability? Limitations? Consistency? etc.) Does it even matter? If doesn't then does that violate the Pythonic principle: <a href="http://en.wikipedia.org/wiki/Python_(programming_language)#Philosophy">“There should be one—and preferably only one—obvious way to do it”</a>.</p>
58
2008-09-25T17:15:03Z
298,045
<p>If you are just going to assign the lambda to a variable in the local scope, you may as well use def because it is more readable and can be expanded more easily in the future:</p> <pre><code>fun = lambda a, b: a ** b # a pointless use of lambda map(fun, someList) </code></pre> <p>or</p> <pre><code>def fun(a, b): return a ** b # more readable map(fun, someList) </code></pre>
0
2008-11-18T07:19:32Z
[ "python", "syntax", "function", "lambda" ]