title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
Python - ConfigParser throwing comments
564,662
<p>Based on ConfigParser module how can I filter out and throw every comments from an ini file?</p> <pre><code>import ConfigParser config = ConfigParser.ConfigParser() config.read("sample.cfg") for section in config.sections(): print section for option in config.options(section): print option, "=", config.get(section, option) </code></pre> <p>eg. in the ini file below the above basic script prints out the further comments lines as well like:</p> <pre><code>something = 128 ; comment line1 ; further comments ; one more line comment </code></pre> <p>What I need is having only the section names and pure key-value pairs inside them without any comments. Does ConfigParser handles this somehow or should I use regexp...or? Cheers</p>
1
2009-02-19T10:27:21Z
4,665,661
<p>As the doc said: "(For backwards compatibility, only ; starts an inline comment, while # does not.)" So use ";" and not "#" for inline comments. It is working well for me.</p>
1
2011-01-12T05:37:27Z
[ "python", "configparser" ]
Python - ConfigParser throwing comments
564,662
<p>Based on ConfigParser module how can I filter out and throw every comments from an ini file?</p> <pre><code>import ConfigParser config = ConfigParser.ConfigParser() config.read("sample.cfg") for section in config.sections(): print section for option in config.options(section): print option, "=", config.get(section, option) </code></pre> <p>eg. in the ini file below the above basic script prints out the further comments lines as well like:</p> <pre><code>something = 128 ; comment line1 ; further comments ; one more line comment </code></pre> <p>What I need is having only the section names and pure key-value pairs inside them without any comments. Does ConfigParser handles this somehow or should I use regexp...or? Cheers</p>
1
2009-02-19T10:27:21Z
10,241,325
<p>Python 3 comes with a build-in solution: The class <a href="http://docs.python.org/py3k/library/configparser.html?highlight=rawconfigparser#rawconfigparser-objects" rel="nofollow">configparser.RawConfigParser</a> has constructor argument <code>inline_comment_prefixes</code>. Example:</p> <pre><code>class MyConfigParser(configparser.RawConfigParser): def __init__(self): configparser.RawConfigParser.__init__(self, inline_comment_prefixes=('#', ';')) </code></pre>
0
2012-04-20T06:30:42Z
[ "python", "configparser" ]
Is there a way to change effective process name in Python?
564,695
<p>Can I change effective process name of a Python script? I want to show a different name instead of the real name of the process when I get the system process list. In C I can set</p> <pre><code>strcpy(argv[0],"othername"); </code></pre> <p>But in Python </p> <pre><code>argv[0] = "othername" </code></pre> <p>doesn't seem to work. When i get process list (with <code>ps ax</code> in my linux box) the real name doesn't change. I prefer a portable solution (or else one solution for posix and another for windows environments), if it exists.</p> <p>Thanks in advance</p>
50
2009-02-19T10:37:12Z
564,709
<pre><code>In [1]: import sys In [2]: print sys.argv[0] C:\Python25\scripts\ipython.py In [3]: sys.argv[0] = 'foo' In [4]: print sys.argv[0] foo </code></pre> <p>Note the single '=' sign</p>
-5
2009-02-19T10:39:53Z
[ "python", "process", "arguments", "hide", "ps" ]
Is there a way to change effective process name in Python?
564,695
<p>Can I change effective process name of a Python script? I want to show a different name instead of the real name of the process when I get the system process list. In C I can set</p> <pre><code>strcpy(argv[0],"othername"); </code></pre> <p>But in Python </p> <pre><code>argv[0] = "othername" </code></pre> <p>doesn't seem to work. When i get process list (with <code>ps ax</code> in my linux box) the real name doesn't change. I prefer a portable solution (or else one solution for posix and another for windows environments), if it exists.</p> <p>Thanks in advance</p>
50
2009-02-19T10:37:12Z
564,878
<p>First, I'm not sure that simply settings <code>argv[0]</code> in a C program portably changes the name shown in <code>ps</code>. Maybe it does in some unixen, but my understanding is that it's not expected to.</p> <p>Second, since Windows is specifically non-POSIX compliant, only a few things are "portable" between POSIX and non-POSIX. Since you specifically say 'ps', I'll assume that POSIX is your priority and Windows may not work.</p> <p>More importantly, my understanding of changing <code>argv[0]</code> is that it requires a call to <code>exec</code> to make these changes. Specifically, the <code>exec</code> call has both a path to an executable and a separate <code>argv</code> list. Making your own call allows you to break the shell convention of putting the executable name in <code>argv[0]</code>.</p> <p>You have <a href="http://docs.python.org/library/os.html#process-management" rel="nofollow">OS library process management</a> which gives you direct access to the OS library for doing this. You should consider breaking your script into two parts -- a starter and the "real work". The starter establishes the run-time environment and exec's the real work with the desired parameters. </p> <p>In C, you're replacing your own process with another. In Python, you're replacing the old Python interpreter with a new one that has a different argv[0]. Hopefully, it won't balk at this. Some programs check argv[0] to decide what they're doing.</p> <p>You also have <a href="http://docs.python.org/library/subprocess.html#subprocess.Popen" rel="nofollow">subprocess.popen</a> that you can use to set your desired args and executable. In this case, however, the parent process should lingers around to collect the child when the child finishes. The parent may not be doing anything more than a <code>Popen.wait</code></p>
4
2009-02-19T11:31:25Z
[ "python", "process", "arguments", "hide", "ps" ]
Is there a way to change effective process name in Python?
564,695
<p>Can I change effective process name of a Python script? I want to show a different name instead of the real name of the process when I get the system process list. In C I can set</p> <pre><code>strcpy(argv[0],"othername"); </code></pre> <p>But in Python </p> <pre><code>argv[0] = "othername" </code></pre> <p>doesn't seem to work. When i get process list (with <code>ps ax</code> in my linux box) the real name doesn't change. I prefer a portable solution (or else one solution for posix and another for windows environments), if it exists.</p> <p>Thanks in advance</p>
50
2009-02-19T10:37:12Z
565,071
<p>Simply put, there's no portable way. You'll have to test for the system and use the preferred method for that system.</p> <p>Further, I'm confused about what you mean by process names on Windows.</p> <p>Do you mean a service name? I presume so, because nothing else really makes any sense (at least to my non-Windows using brain).</p> <p>If so, you need to use <a href="http://timgolden.me.uk/python/wmi" rel="nofollow">Tim Golden's WMI interface</a> and call the .Change method on the service... at least according to his <a href="http://timgolden.me.uk/python/wmi/tutorial.html" rel="nofollow">tutorial</a>.</p> <p>For Linux none of the methods I found worked except for <a href="http://code.google.com/p/procname/" rel="nofollow">this poorly packaged module</a> that sets argv[0] for you.</p> <p>I don't even know if this will work on BSD variants (which does have a setproctitle system call). I'm pretty sure argv[0] won't work on Solaris.</p>
9
2009-02-19T12:26:14Z
[ "python", "process", "arguments", "hide", "ps" ]
Is there a way to change effective process name in Python?
564,695
<p>Can I change effective process name of a Python script? I want to show a different name instead of the real name of the process when I get the system process list. In C I can set</p> <pre><code>strcpy(argv[0],"othername"); </code></pre> <p>But in Python </p> <pre><code>argv[0] = "othername" </code></pre> <p>doesn't seem to work. When i get process list (with <code>ps ax</code> in my linux box) the real name doesn't change. I prefer a portable solution (or else one solution for posix and another for windows environments), if it exists.</p> <p>Thanks in advance</p>
50
2009-02-19T10:37:12Z
923,034
<p>actually you need 2 things on linux: modify <code>argv[0]</code> from <code>C</code> (for <code>ps auxf</code> and friends) and call <code>prctl</code> with <code>PR_SET_NAME</code> flag.</p> <p>There is absolutely no way to do first piece from python itself. Although, you can just change process name by calling prctl.</p> <pre><code>def set_proc_name(newname): from ctypes import cdll, byref, create_string_buffer libc = cdll.LoadLibrary('libc.so.6') buff = create_string_buffer(len(newname)+1) buff.value = newname libc.prctl(15, byref(buff), 0, 0, 0) def get_proc_name(): from ctypes import cdll, byref, create_string_buffer libc = cdll.LoadLibrary('libc.so.6') buff = create_string_buffer(128) # 16 == PR_GET_NAME from &lt;linux/prctl.h&gt; libc.prctl(16, byref(buff), 0, 0, 0) return buff.value import sys # sys.argv[0] == 'python' # outputs 'python' get_proc_name() set_proc_name('testing yeah') # outputs 'testing yeah' get_proc_name() </code></pre> <p><code>ps auxf</code> will show just 'python' after that :(. But <code>top</code> and <code>ps -A</code> will show new 'testing yeah' process name :). Also <code>killall</code> and <code>pkill</code> will work with new name.</p> <p>btw, procname from googlecode also changes <code>argv[0]</code>, thus, even, changes <code>ps auxf</code> output.</p> <p><strong>UPDATE</strong>: The solution posted in this answer does not play nice sometimes on FreeBSD. I'm now using <a href="http://code.google.com/p/py-setproctitle/">py-setproctitle</a> stated <a href="http://stackoverflow.com/questions/564695/is-there-a-way-to-change-effective-process-name-in-python/1866700#1866700">in this answer</a> for a year or so on various linux and freebsd boxes. No fails so far! Everybody should too! :). It uses almost the same code as <a href="http://www.postgresql.org">PostgreSQL</a> <a href="http://git.postgresql.org/gitweb/?p=postgresql.git;a=blob;f=src/backend/utils/misc/ps_status.c;hb=HEAD">uses</a> in its main database and child processes.</p>
37
2009-05-28T20:39:05Z
[ "python", "process", "arguments", "hide", "ps" ]
Is there a way to change effective process name in Python?
564,695
<p>Can I change effective process name of a Python script? I want to show a different name instead of the real name of the process when I get the system process list. In C I can set</p> <pre><code>strcpy(argv[0],"othername"); </code></pre> <p>But in Python </p> <pre><code>argv[0] = "othername" </code></pre> <p>doesn't seem to work. When i get process list (with <code>ps ax</code> in my linux box) the real name doesn't change. I prefer a portable solution (or else one solution for posix and another for windows environments), if it exists.</p> <p>Thanks in advance</p>
50
2009-02-19T10:37:12Z
1,866,700
<p>I've recently written a Python module to change the process title in a portable way: check <a href="https://github.com/dvarrazzo/py-setproctitle">https://github.com/dvarrazzo/py-setproctitle</a></p> <p>It is a wrapper around the code used by PostgreSQL to perform the title change. It is currently tested against Linux and Mac OS X: Windows (with limited functionality) and BSD portings are on the way.</p> <p><strong>Edit:</strong> as of July 2010, the module works with BSD and with limited functionality on Windows, and has been ported to Python 3.x.</p>
62
2009-12-08T12:40:46Z
[ "python", "process", "arguments", "hide", "ps" ]
Is there a way to change effective process name in Python?
564,695
<p>Can I change effective process name of a Python script? I want to show a different name instead of the real name of the process when I get the system process list. In C I can set</p> <pre><code>strcpy(argv[0],"othername"); </code></pre> <p>But in Python </p> <pre><code>argv[0] = "othername" </code></pre> <p>doesn't seem to work. When i get process list (with <code>ps ax</code> in my linux box) the real name doesn't change. I prefer a portable solution (or else one solution for posix and another for windows environments), if it exists.</p> <p>Thanks in advance</p>
50
2009-02-19T10:37:12Z
2,006,607
<p>Have a look on <a href="http://code.google.com/p/py-setproctitle/" rel="nofollow">setproctitle</a> package</p> <p>This is quite a portable version and works on many platforms.</p>
3
2010-01-05T14:28:37Z
[ "python", "process", "arguments", "hide", "ps" ]
Is there a way to change effective process name in Python?
564,695
<p>Can I change effective process name of a Python script? I want to show a different name instead of the real name of the process when I get the system process list. In C I can set</p> <pre><code>strcpy(argv[0],"othername"); </code></pre> <p>But in Python </p> <pre><code>argv[0] = "othername" </code></pre> <p>doesn't seem to work. When i get process list (with <code>ps ax</code> in my linux box) the real name doesn't change. I prefer a portable solution (or else one solution for posix and another for windows environments), if it exists.</p> <p>Thanks in advance</p>
50
2009-02-19T10:37:12Z
4,923,260
<p>I have found <a href="http://packages.python.org/python-prctl/" rel="nofollow" title="python-prctl">python-prctl</a> to work very well under Linux. You will have to find something else for Windows.</p>
0
2011-02-07T15:45:35Z
[ "python", "process", "arguments", "hide", "ps" ]
Is there a way to change effective process name in Python?
564,695
<p>Can I change effective process name of a Python script? I want to show a different name instead of the real name of the process when I get the system process list. In C I can set</p> <pre><code>strcpy(argv[0],"othername"); </code></pre> <p>But in Python </p> <pre><code>argv[0] = "othername" </code></pre> <p>doesn't seem to work. When i get process list (with <code>ps ax</code> in my linux box) the real name doesn't change. I prefer a portable solution (or else one solution for posix and another for windows environments), if it exists.</p> <p>Thanks in advance</p>
50
2009-02-19T10:37:12Z
33,912,448
<p>My answer to similar question marked as <a href="http://stackoverflow.com/questions/2255444/changing-the-process-name-of-a-python-script/25338292#25338292">duplicate</a>:</p> <p>There is simplier (you don't need import any libs) but maybe not so elegant way. You have to do not use "env" inside the shebang line.</p> <p>In other words, this will be named as "python" in process list:</p> <pre><code>#!/usr/bin/env python </code></pre> <p>But this will be named with your scriptname:</p> <pre><code>#!/usr/bin/python </code></pre> <p>So you'll be able to find it with something like <code>pidof -x scriptname</code> or <code>ps -C scriptname</code></p>
1
2015-11-25T09:12:35Z
[ "python", "process", "arguments", "hide", "ps" ]
can my programs access more than 4GB of memory?
565,030
<p>if I run python on a 64bit machine with a 64bit operating system, will my programs be able to access the full range of memory? I.e. Could I build a list with 10billion entries, assuming I had enough RAM? If not, are there other programming languages that would allow this?</p>
5
2009-02-19T12:14:31Z
565,041
<p>The language python itself has no such restrictions, but perhaps your operating system or your python runtime (pypy, cpython, jython) could have such restrictions.</p> <p>What combination of python runtime and OS do you want to use?</p>
3
2009-02-19T12:17:45Z
[ "python", "64bit" ]
can my programs access more than 4GB of memory?
565,030
<p>if I run python on a 64bit machine with a 64bit operating system, will my programs be able to access the full range of memory? I.e. Could I build a list with 10billion entries, assuming I had enough RAM? If not, are there other programming languages that would allow this?</p>
5
2009-02-19T12:14:31Z
565,085
<p>You'll need to be sure that Python has been built as a 64 bit application. For example, on Win64 you'll be able to run the 32bit build of Python.exe but it won't get the benefits of the 64 bit environment as Windows will run it in a 32bit sandbox.</p>
6
2009-02-19T12:31:24Z
[ "python", "64bit" ]
Setting values to the output of a formset in Django
565,034
<p>This question is somewhat linked to a question I asked previously:</p> <p><a href="http://stackoverflow.com/questions/477183/generating-and-submitting-a-dynamic-number-of-objects-in-a-form-with-django">http://stackoverflow.com/questions/477183/generating-and-submitting-a-dynamic-number-of-objects-in-a-form-with-django</a></p> <p>I'm wondering, if I've got separate default values for each form within a formset, am I able to pre-populate the fields? For instance, a form requiring extra customer information to be pre-populated with the users names? In cases like adding an email field to an already existing table, and updating many of them at once.</p> <p>Does Django provide an easy way to do this?</p>
0
2009-02-19T12:15:44Z
565,967
<p>Pass in a list of dicts which contain the default values you want to set for each form:</p> <p><a href="http://docs.djangoproject.com/en/dev/topics/forms/formsets/#using-initial-data-with-a-formset" rel="nofollow">http://docs.djangoproject.com/en/dev/topics/forms/formsets/#using-initial-data-with-a-formset</a></p>
1
2009-02-19T15:57:05Z
[ "python", "django", "django-forms", "formset" ]
Using jep.invoke() method
565,060
<p>I need to call a function from a python script and pass in parameters into it. I have a test python script which I can call and run from java using Jepp - this then adds the person. </p> <p>Eg Test.py</p> <pre><code>import Finding from Finding import * f = Finding() f.addFinding("John", "Doe", 27) </code></pre> <p>Within my Finding class I have <code>addFinding(firstname, lastName, age)</code></p> <p>However, I wish to be able to do this from within java. Should I be using the <code>jep.invoke()</code> method. Does anyone have a hello world example of such a thing being done or forward me to some good examples? </p> <p>Does anyone have any suggestions please? </p> <p>Thanks in advance</p>
0
2009-02-19T12:24:00Z
565,185
<p>Easier way to run python code in java is to use <a href="http://www.jython.org/" rel="nofollow">jython</a>.</p> <p><strong>EDIT:</strong> Found an <a href="http://wiki.python.org/jython/JythonMonthly/Articles/September2006/1" rel="nofollow">article with examples</a> in the jython website.</p>
0
2009-02-19T12:50:19Z
[ "java", "python" ]
Parsing HTML generated from Legacy ASP Application to create ASP.NET 2.0 Pages
565,264
<p>One of my friends is working on having a good solution to generate aspx pages, out of html pages generated from a legacy asp application.</p> <p>The idea is to run the legacy app, capture html output, clean the html using some tool (say HtmlTidy) and parse it/transform it to aspx, (using Xslt or a custom tool) so that existing html elements, divs, images, styles etc gets converted neatly to an aspx page (too much ;) ).</p> <p>Any existing tools/scripts/utilities to do the same?</p>
0
2009-02-19T13:19:03Z
565,698
<p>Here's what you do.</p> <ol> <li><p>Define what the legacy app is supposed to do. Write down the scenarios of getting pages, posting forms, navigating, etc.</p></li> <li><p>Write unit test-like scripts for the various scenarios.</p></li> <li><p>Use the Python <a href="http://docs.python.org/library/httplib.html" rel="nofollow">HTTP client library</a> to exercise the legacy app in your various scripts.</p></li> <li><p>If your scripts work, you (a) actually understand the legacy app, (b) can make it do the various things it's supposed to do, and (c) you can reliably capture the HTML response pages.</p></li> <li><p>Update your scripts to capture the HTML responses.</p></li> </ol> <p>You have the pages. Now you can think about what you need for your ASPX pages.</p> <ul> <li><p>Edit the HTML by hand to make it into ASPX.</p></li> <li><p>Write something that uses <a href="http://www.crummy.com/software/BeautifulSoup/" rel="nofollow">Beautiful Soup</a> to massage the HTML into a form suitable for ASPX. This might be some replacement of text or tags with <code>&lt;asp:...</code> tags.</p></li> <li><p>Create some other, more useful data structure out of the HTML -- one that reflects the structure and meaning of the pages, not just the HTML tags. Generate the ASPX pages from that more useful structure.</p></li> </ul>
2
2009-02-19T15:02:40Z
[ "c#", ".net", "python", "html" ]
Parsing HTML generated from Legacy ASP Application to create ASP.NET 2.0 Pages
565,264
<p>One of my friends is working on having a good solution to generate aspx pages, out of html pages generated from a legacy asp application.</p> <p>The idea is to run the legacy app, capture html output, clean the html using some tool (say HtmlTidy) and parse it/transform it to aspx, (using Xslt or a custom tool) so that existing html elements, divs, images, styles etc gets converted neatly to an aspx page (too much ;) ).</p> <p>Any existing tools/scripts/utilities to do the same?</p>
0
2009-02-19T13:19:03Z
568,228
<p>Just found HTML agility pack to be useful enough, as they understand C# better than python. </p>
0
2009-02-20T03:56:13Z
[ "c#", ".net", "python", "html" ]
Parsing HTML generated from Legacy ASP Application to create ASP.NET 2.0 Pages
565,264
<p>One of my friends is working on having a good solution to generate aspx pages, out of html pages generated from a legacy asp application.</p> <p>The idea is to run the legacy app, capture html output, clean the html using some tool (say HtmlTidy) and parse it/transform it to aspx, (using Xslt or a custom tool) so that existing html elements, divs, images, styles etc gets converted neatly to an aspx page (too much ;) ).</p> <p>Any existing tools/scripts/utilities to do the same?</p>
0
2009-02-19T13:19:03Z
1,664,516
<p>I know this is an old question, but in a similar situation (50k+ legacy ASP pages that need to display in a .NET framework), I did the following.</p> <ol> <li><p>Created a rewrite engine (HttpModule) which catches all incoming requests and looks for anything that is from the old site.</p></li> <li><p>(in a separate class - keep things organized!) use WebClient or HttpRequest, etc to open a connection to the old server and download the rendered HTML.</p></li> <li><p>Use the HTML agility toolkit (<strong>very</strong> slick) to extract the content that I'm interested in - in our case, this is always inside if a div with the class "bdy".</p></li> <li><p>Throw this into a cache - a SQL table in this example.</p></li> </ol> <p>Each hit checks the cache and either a)retrieves the page and builds the cache entry, or b) just gets the page from the cache.</p> <ol> <li>An aspx page built specifically for displaying legacy content receives the rewrite request and displays the relevant content from the legacy page inside of an asp literal control.</li> </ol> <p>The cache is there for performance - since the first request for a given page has a minimum of two hits - one from the browser to the new server, one from the new server to the old server - I store cachable data on the new server so that subsequent requests don't have to go back to the old server. We also cache images, css, scripts, etc.</p> <p>It gets messy when you have to handle forms, cookies, etc, but these can all be stored in your cache and passed through to the old server with each request if necessary. I also store content expiration dates and other headers that I get back from the legacy server and am sure to pass those back to the browser when rendering the cached page. Just remember to take as content-agnostic an approach as possible. You're effectively building an in-page web proxy that lets IIS render old ASP the way it wants, and manipulating the output. </p> <p>Works very well - I have all of the old pages working seamlessly within our ASP.NET app. This saved us a solid year of development time that would have been required if we had to touch every legacy asp page.</p> <p>Good luck!</p>
0
2009-11-03T00:13:31Z
[ "c#", ".net", "python", "html" ]
How can I anonymise XML data for selected tags?
565,823
<p>My question is as follows:</p> <p>I have to read a big XML file, 50 MB; and anonymise some tags/fields that relate to private issues, like name surname address, email, phone number, etc...</p> <p>I know exactly which tags in XML are to be anonymised.</p> <pre><code> s|&lt;a&gt;alpha&lt;/a&gt;|MD5ed(alpha)|e; s|&lt;h&gt;beta&lt;/h&gt;|MD5ed(beta)|e; </code></pre> <p>where <code>alpha</code> and <code>beta</code> refer to any characters within, which will also be hashed, using probably an algorithm like <a href="http://en.wikipedia.org/wiki/MD5" rel="nofollow">MD5</a>.</p> <p>I will only convert the tag value, not the tags themselves.</p> <p>I hope, I am clear enough about my problem. How do I achieve this?</p>
2
2009-02-19T15:25:47Z
565,873
<p>Bottom line: don't parse XML using regex.</p> <p>Use your language's DOM parsing libraries instead, and if you know the elements you need to anonymize, grab them using XPath and hash their contents by setting their innerText/innerHTML properties (or whatever your language calls them).</p>
4
2009-02-19T15:35:02Z
[ "python", "xml", "perl", "anonymize" ]
How can I anonymise XML data for selected tags?
565,823
<p>My question is as follows:</p> <p>I have to read a big XML file, 50 MB; and anonymise some tags/fields that relate to private issues, like name surname address, email, phone number, etc...</p> <p>I know exactly which tags in XML are to be anonymised.</p> <pre><code> s|&lt;a&gt;alpha&lt;/a&gt;|MD5ed(alpha)|e; s|&lt;h&gt;beta&lt;/h&gt;|MD5ed(beta)|e; </code></pre> <p>where <code>alpha</code> and <code>beta</code> refer to any characters within, which will also be hashed, using probably an algorithm like <a href="http://en.wikipedia.org/wiki/MD5" rel="nofollow">MD5</a>.</p> <p>I will only convert the tag value, not the tags themselves.</p> <p>I hope, I am clear enough about my problem. How do I achieve this?</p>
2
2009-02-19T15:25:47Z
565,930
<p>You have to do something like the following in Python.</p> <pre><code>import xml.etree.ElementTree as xml # or lxml or whatever import hashlib theDoc= xml.parse( "sample.xml" ) for alphaTag in theDoc.findall( "xpath/to/tag" ): print alphaTag, alphaTag.text alphaTag.text = hashlib.md5(alphaTag.text).hexdigest() xml.dump(theDoc) </code></pre>
6
2009-02-19T15:47:59Z
[ "python", "xml", "perl", "anonymize" ]
How can I anonymise XML data for selected tags?
565,823
<p>My question is as follows:</p> <p>I have to read a big XML file, 50 MB; and anonymise some tags/fields that relate to private issues, like name surname address, email, phone number, etc...</p> <p>I know exactly which tags in XML are to be anonymised.</p> <pre><code> s|&lt;a&gt;alpha&lt;/a&gt;|MD5ed(alpha)|e; s|&lt;h&gt;beta&lt;/h&gt;|MD5ed(beta)|e; </code></pre> <p>where <code>alpha</code> and <code>beta</code> refer to any characters within, which will also be hashed, using probably an algorithm like <a href="http://en.wikipedia.org/wiki/MD5" rel="nofollow">MD5</a>.</p> <p>I will only convert the tag value, not the tags themselves.</p> <p>I hope, I am clear enough about my problem. How do I achieve this?</p>
2
2009-02-19T15:25:47Z
566,094
<p>As Welbog said, don't try to parse XML with a regex. You'll regret it eventually.</p> <p>Probably the easiest way to do this is using <a href="http://search.cpan.org/perldoc?XML::Twig" rel="nofollow">XML::Twig</a>. It can process XML in chunks, which lets you handle very large files.</p> <p>Another possibility would be using <a href="http://search.cpan.org/perldoc?XML::SAX::Intro" rel="nofollow">SAX</a>, especially with <a href="http://search.cpan.org/perldoc?XML::SAX::Machines" rel="nofollow">XML::SAX::Machines</a>. I've never really used that myself, but it's a stream-oriented system, so it should be able to handle large files. The downside is that you'll probably have to write more code to collect the text inside each tag that you care about (where XML::Twig will collect that text for you).</p>
3
2009-02-19T16:27:18Z
[ "python", "xml", "perl", "anonymize" ]
How can I anonymise XML data for selected tags?
565,823
<p>My question is as follows:</p> <p>I have to read a big XML file, 50 MB; and anonymise some tags/fields that relate to private issues, like name surname address, email, phone number, etc...</p> <p>I know exactly which tags in XML are to be anonymised.</p> <pre><code> s|&lt;a&gt;alpha&lt;/a&gt;|MD5ed(alpha)|e; s|&lt;h&gt;beta&lt;/h&gt;|MD5ed(beta)|e; </code></pre> <p>where <code>alpha</code> and <code>beta</code> refer to any characters within, which will also be hashed, using probably an algorithm like <a href="http://en.wikipedia.org/wiki/MD5" rel="nofollow">MD5</a>.</p> <p>I will only convert the tag value, not the tags themselves.</p> <p>I hope, I am clear enough about my problem. How do I achieve this?</p>
2
2009-02-19T15:25:47Z
566,803
<p>Using regexps is indeed dangerous, unless you know exactly the format of the file, it's easy to parse with regexps, and you are sure that it will not change in the future.</p> <p>Otherwise you could indeed use XML::Twig,as below. An alternative would be to use XML::LibXML, although the file might be a bit big to load it entirely in memory (then again, maybe not, memory is cheap these days) so you might have to use the pull mode, which I don't know much about.</p> <p>Compact XML::Twig code:</p> <pre><code>#!/usr/bin/perl use strict; use warnings; use XML::Twig; use Digest::MD5 'md5_base64'; my @tags_to_anonymize= qw( name surname address email phone); # the handler for each element ($_) sets its content with the md5 and then flushes my %handlers= map { $_ =&gt; sub { $_-&gt;set_text( md5_base64( $_-&gt;text))-&gt;flush } } @tags_to_anonymize; XML::Twig-&gt;new( twig_roots =&gt; \%handlers, twig_print_outside_roots =&gt; 1) -&gt;parsefile( "my_big_file.xml") -&gt;flush; </code></pre>
3
2009-02-19T19:32:37Z
[ "python", "xml", "perl", "anonymize" ]
python code for django view
566,083
<p>MODEL:</p> <pre><code>class Pathology(models.Model): pathology = models.CharField(max_length=100) class Publication(models.Model): pubtitle = models.TextField() class Pathpubcombo(models.Model): pathology = models.ForeignKey(Pathology) publication = models.ForeignKey(Publication) </code></pre> <ol> <li>List of pathology sent to HTML template as drop down menu</li> </ol> <p>VIEW:</p> <pre><code>def search(request): pathology_list = Pathology.objects.select_related().order_by('pathology') </code></pre> <ol> <li>User selects one pathology name from drop down menu and id retrieved by</li> </ol> <p>VIEW:</p> <pre><code>def pathology(request): pathology_id = request.POST['pathology_id'] p = get_object_or_404(Pathology, pk=pathology_id) </code></pre> <p>Where I'm stuck. I need the python/django syntax to write the following:</p> <p>The pathology_id must now retrieve the publication_id from the table Pathpubcombo (the intermediary manytomany table). Once the publication_id is retrieved then it must be used to retrieve all the attributes from the publication table and those attributes are sent to another html template for display to the user.</p>
2
2009-02-19T16:24:39Z
566,172
<p>you should be using many-to-many relations as described here: <a href="http://www.djangoproject.com/documentation/models/many_to_many/" rel="nofollow">http://www.djangoproject.com/documentation/models/many_to_many/</a></p> <p>Like:</p> <pre><code>class Pathology(models.Model): pathology = models.CharField(max_length=100) publications = models.ManyToManyField(Publication) class Publication(models.Model): pubtitle = models.TextField() </code></pre> <p>Then</p> <pre><code>def pathology(request): pathology_id = request.POST['pathology_id'] p = get_object_or_404(Pathology, pk=pathology_id) publications = p.publications.all() return render_to_response('my_template.html', {'publications':publications}, context_instance=RequestContext(request)) </code></pre> <p>Hope this works, haven't tested it, but you get the idea.</p> <p>edit: </p> <p>You can also use select_related() if there is no possibility to rename tables and use django's buildin support.</p> <p><a href="http://docs.djangoproject.com/en/dev/ref/models/querysets/#id4" rel="nofollow">http://docs.djangoproject.com/en/dev/ref/models/querysets/#id4</a></p>
5
2009-02-19T16:47:02Z
[ "python", "django", "syntax", "many-to-many" ]
How can I make this one-liner work in DOS?
566,559
<pre><code>python -c "for x in range(1,10) print x" </code></pre> <p>I enjoy python one liners with -c, but it is limited when indentation is needed.</p> <p>Any ideas?</p>
5
2009-02-19T18:29:30Z
566,563
<pre><code>python -c "for x in range(1,10): print x" </code></pre> <p>Just add the colon.</p> <p>To address the question in the comments:</p> <blockquote> <p>How can I make this work though? python -c "import calendar;print calendar.prcal(2009);for x in range(1,10): print x"</p> </blockquote> <pre><code>python -c "for x in range(1,10): x==1 and __import__('calendar').prcal(2009); print x;" </code></pre> <p>As you can see it's pretty gross. We can't import before the loop. To get around this we check if x is at the first iteration in the loop, if so we do the import.</p> <p>More examples <a href="https://web.archive.org/web/20071223101511/http://mail.python.org/pipermail/python-list/2003-April/199822.html" rel="nofollow">here</a>.</p>
12
2009-02-19T18:31:50Z
[ "python", "command-line" ]
How can I make this one-liner work in DOS?
566,559
<pre><code>python -c "for x in range(1,10) print x" </code></pre> <p>I enjoy python one liners with -c, but it is limited when indentation is needed.</p> <p>Any ideas?</p>
5
2009-02-19T18:29:30Z
566,568
<p>Not a python script, but might help:</p> <pre><code>for /L %i in (1, 1, 10) do echo %i </code></pre>
3
2009-02-19T18:32:18Z
[ "python", "command-line" ]
How can I make this one-liner work in DOS?
566,559
<pre><code>python -c "for x in range(1,10) print x" </code></pre> <p>I enjoy python one liners with -c, but it is limited when indentation is needed.</p> <p>Any ideas?</p>
5
2009-02-19T18:29:30Z
566,572
<p>Don't you just want this?</p> <p>python -c “for x in range(1,10): print x”</p>
1
2009-02-19T18:32:53Z
[ "python", "command-line" ]
How can I make this one-liner work in DOS?
566,559
<pre><code>python -c "for x in range(1,10) print x" </code></pre> <p>I enjoy python one liners with -c, but it is limited when indentation is needed.</p> <p>Any ideas?</p>
5
2009-02-19T18:29:30Z
566,573
<pre><code>python -c "for x in range(1,10): print x" </code></pre> <p>Remember the ":" !!</p>
3
2009-02-19T18:33:36Z
[ "python", "command-line" ]
How can I make this one-liner work in DOS?
566,559
<pre><code>python -c "for x in range(1,10) print x" </code></pre> <p>I enjoy python one liners with -c, but it is limited when indentation is needed.</p> <p>Any ideas?</p>
5
2009-02-19T18:29:30Z
566,629
<p>Here's a solution that doesn't require putting a statement after the colon, which is not considered very highly.</p> <pre><code>python2 -c "print '\n'.join([str(x) for x in range(1,10)])" </code></pre> <p>What's more pythonic than a list comprehension!</p>
1
2009-02-19T18:48:50Z
[ "python", "command-line" ]
How can I make this one-liner work in DOS?
566,559
<pre><code>python -c "for x in range(1,10) print x" </code></pre> <p>I enjoy python one liners with -c, but it is limited when indentation is needed.</p> <p>Any ideas?</p>
5
2009-02-19T18:29:30Z
566,698
<pre><code>python -c 'print "\n".join(map(str, range(1,10)))' </code></pre> <p>but what's wrong in a "real" python script? (you know, a foo.py launched via "python foo.py") If you really like one-liners, I suggest perl :)</p>
0
2009-02-19T19:04:24Z
[ "python", "command-line" ]
Building a "complete" number range w/out overlaps
566,574
<p>I need to build a full "number range" set given a series of numbers. I start with a list such as :</p> <pre><code>ID START * 0 a 4 b 70 c 700 d 701 e 85 </code></pre> <ul> <li>where "def" is the default range &amp; should "fill-in" the gaps </li> <li>"overlaps" are value (70, 700, 701) in starting data</li> </ul> <p>And need the following result: </p> <pre><code>ID START END * 0 - 39 a 4 - 49 * 5 - 69 c 700 - 7009 d 701 - 7019 b 702 - 709 * 71 - 849 e 85 - 859 * 86 - 9 </code></pre> <p>What I am trying to figure out is if there is some sort of algorithm out there or design pattern to tackle this. I have some ideas but I thought I'd run it by the "experts" first. I am using Python. </p> <p>Any ideas / direction would be greatly appreciated. Some initial ideas I have: </p> <ul> <li>Build a "range" list w/ the start &amp; end values padded to the full length. So default would be 0000 to 9999</li> <li>Build a "splits" list that is built on the fly</li> <li>Loop through "range" list comparing each value to the values in the splits list.</li> <li>In the event that an overlap is found, remove the value in the splits list and add the new range(s).</li> </ul>
0
2009-02-19T18:33:44Z
566,703
<pre><code>import operator ranges = { '4' : 'a', '70' : 'b', '700': 'c', '701': 'd', '85' : 'e', '87' : 'a', } def id_for_value(value): possible = '*' for idvalue, id in sorted(ranges.iteritems()): if value.startswith(idvalue): possible = id elif idvalue &gt; value: break return possible </code></pre> <p>That is enough to know the id of a certain value. Testing:</p> <pre><code>assert id_for_value('10') == '*' assert id_for_value('499') == 'a' assert id_for_value('703') == 'b' assert id_for_value('7007') == 'c' assert id_for_value('7017') == 'd' assert id_for_value('76') == id_for_value('83') == '*' assert id_for_value('857') == 'e' assert id_for_value('8716') == 'a' </code></pre> <p>If you really want the range, you can use itertools.groupby to calculate it:</p> <pre><code>def firstlast(iterator): """ Returns the first and last value of an iterator""" first = last = iterator.next() for value in iterator: last = value return first, last maxlen = max(len(x) for x in ranges) + 1 test_range = ('%0*d' % (maxlen, i) for i in xrange(10 ** maxlen)) result = dict((firstlast(gr), id) for id, gr in itertools.groupby(test_range, key=id_for_value)) </code></pre> <p>Gives:</p> <pre><code>{('0000', '3999'): '*', ('4000', '4999'): 'a', ('5000', '6999'): '*', ('7000', '7009'): 'c', ('7010', '7019'): 'd', ('7020', '7099'): 'b', ('7100', '8499'): '*', ('8500', '8599'): 'e', ('8600', '8699'): '*', ('8700', '8799'): 'a', ('8800', '9999'): '*'} </code></pre>
0
2009-02-19T19:05:03Z
[ "python", "range", "numbers", "overlap" ]
How to get console window width in python
566,746
<p>Is there a way in python to programmatically determine the width of the console? I mean the number of characters that fits in one line without wrapping, not the pixel width of the window.</p> <p><b>Edit</b></p> <p>Looking for a solution that works on Linux</p>
151
2009-02-19T19:17:19Z
566,752
<p>use</p> <pre><code>import console (width, height) = console.getTerminalSize() print "Your terminal's width is: %d" % width </code></pre> <p><strong>EDIT</strong>: oh, I'm sorry. That's not a python standard lib one, here's the source of console.py (I don't know where it's from).</p> <p>The module seems to work like that: It checks if <code>termcap</code> is available, when yes. It uses that; if no it checks whether the terminal supports a special <code>ioctl</code> call and that does not work, too, it checks for the environment variables some shells export for that. This will probably work on UNIX only.</p> <pre><code>def getTerminalSize(): import os env = os.environ def ioctl_GWINSZ(fd): try: import fcntl, termios, struct, os cr = struct.unpack('hh', fcntl.ioctl(fd, termios.TIOCGWINSZ, '1234')) except: return return cr cr = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2) if not cr: try: fd = os.open(os.ctermid(), os.O_RDONLY) cr = ioctl_GWINSZ(fd) os.close(fd) except: pass if not cr: cr = (env.get('LINES', 25), env.get('COLUMNS', 80)) ### Use get(key[, default]) instead of a try/catch #try: # cr = (env['LINES'], env['COLUMNS']) #except: # cr = (25, 80) return int(cr[1]), int(cr[0]) </code></pre>
63
2009-02-19T19:18:11Z
[ "python", "linux", "console", "terminal", "width" ]
How to get console window width in python
566,746
<p>Is there a way in python to programmatically determine the width of the console? I mean the number of characters that fits in one line without wrapping, not the pixel width of the window.</p> <p><b>Edit</b></p> <p>Looking for a solution that works on Linux</p>
151
2009-02-19T19:17:19Z
943,921
<pre><code>import os rows, columns = os.popen('stty size', 'r').read().split() </code></pre> <p>uses the 'stty size' command which according to <a href="http://mail.python.org/pipermail/python-list/2000-May/033312.html">a thread on the python mailing list</a> is reasonably universal on linux. It opens the 'stty size' command as a file, 'reads' from it, and uses a simple string split to separate the coordinates.</p> <p>Unlike the os.environ["COLUMNS"] value (which I can't access in spite of using bash as my standard shell) the data will also be up-to-date whereas I believe the os.environ["COLUMNS"] value would only be valid for the time of the launch of the python interpreter (suppose the user resized the window since then).</p>
175
2009-06-03T09:59:34Z
[ "python", "linux", "console", "terminal", "width" ]
How to get console window width in python
566,746
<p>Is there a way in python to programmatically determine the width of the console? I mean the number of characters that fits in one line without wrapping, not the pixel width of the window.</p> <p><b>Edit</b></p> <p>Looking for a solution that works on Linux</p>
151
2009-02-19T19:17:19Z
3,010,495
<p>Code above didn't return correct result on my linux because winsize-struct has 4 unsigned shorts, not 2 signed shorts:</p> <pre><code>def terminal_size(): import fcntl, termios, struct h, w, hp, wp = struct.unpack('HHHH', fcntl.ioctl(0, termios.TIOCGWINSZ, struct.pack('HHHH', 0, 0, 0, 0))) return w, h </code></pre> <p>hp and hp should contain pixel width and height, but don't.</p>
39
2010-06-09T22:36:38Z
[ "python", "linux", "console", "terminal", "width" ]
How to get console window width in python
566,746
<p>Is there a way in python to programmatically determine the width of the console? I mean the number of characters that fits in one line without wrapping, not the pixel width of the window.</p> <p><b>Edit</b></p> <p>Looking for a solution that works on Linux</p>
151
2009-02-19T19:17:19Z
3,051,350
<p>It looks like there are some problems with that code, Johannes:</p> <ul> <li><code>getTerminalSize</code> needs to <code>import os</code></li> <li>what is <code>env</code>? looks like <code>os.environ</code>.</li> </ul> <p>Also, why switch <code>lines</code> and <code>cols</code> before returning? If <code>TIOCGWINSZ</code> and <code>stty</code> both say <code>lines</code> then <code>cols</code>, I say leave it that way. This confused me for a good 10 minutes before I noticed the inconsistency.</p> <p>Sridhar, I didn't get that error when I piped output. I'm pretty sure it's being caught properly in the try-except.</p> <p>pascal, <code>"HHHH"</code> doesn't work on my machine, but <code>"hh"</code> does. I had trouble finding documentation for that function. It looks like it's platform dependent.</p> <p>chochem, incorporated.</p> <p>Here's my version:</p> <pre><code>def getTerminalSize(): """ returns (lines:int, cols:int) """ import os, struct def ioctl_GWINSZ(fd): import fcntl, termios return struct.unpack("hh", fcntl.ioctl(fd, termios.TIOCGWINSZ, "1234")) # try stdin, stdout, stderr for fd in (0, 1, 2): try: return ioctl_GWINSZ(fd) except: pass # try os.ctermid() try: fd = os.open(os.ctermid(), os.O_RDONLY) try: return ioctl_GWINSZ(fd) finally: os.close(fd) except: pass # try `stty size` try: return tuple(int(x) for x in os.popen("stty size", "r").read().split()) except: pass # try environment variables try: return tuple(int(os.getenv(var)) for var in ("LINES", "COLUMNS")) except: pass # i give up. return default. return (25, 80) </code></pre>
6
2010-06-16T07:23:51Z
[ "python", "linux", "console", "terminal", "width" ]
How to get console window width in python
566,746
<p>Is there a way in python to programmatically determine the width of the console? I mean the number of characters that fits in one line without wrapping, not the pixel width of the window.</p> <p><b>Edit</b></p> <p>Looking for a solution that works on Linux</p>
151
2009-02-19T19:17:19Z
5,711,313
<p>Here is an version that should be Linux and Solaris compatible. Based on the posts and commments from <a href="http://stackoverflow.com/users/68595/madchine">madchine</a>. Requires the subprocess module.</p> <pre> def termsize(): import shlex, subprocess, re output = subprocess.check_output(shlex.split('/bin/stty -a')) m = re.search('rows\D+(?P\d+); columns\D+(?P\d+);', output) if m: return m.group('rows'), m.group('columns') raise OSError('Bad response: %s' % (output)) </pre> <pre> >>> termsize() ('40', '100') </pre>
0
2011-04-19T03:33:30Z
[ "python", "linux", "console", "terminal", "width" ]
How to get console window width in python
566,746
<p>Is there a way in python to programmatically determine the width of the console? I mean the number of characters that fits in one line without wrapping, not the pixel width of the window.</p> <p><b>Edit</b></p> <p>Looking for a solution that works on Linux</p>
151
2009-02-19T19:17:19Z
6,550,596
<p>I searched around and found a solution for windows at :</p> <p><a href="http://code.activestate.com/recipes/440694-determine-size-of-console-window-on-windows/">http://code.activestate.com/recipes/440694-determine-size-of-console-window-on-windows/</a></p> <p>and a solution for linux here.</p> <p>So here is a version which works both on linux, os x and windows/cygwin :</p> <pre><code>""" getTerminalSize() - get width and height of console - works on linux,os x,windows,cygwin(windows) """ __all__=['getTerminalSize'] def getTerminalSize(): import platform current_os = platform.system() tuple_xy=None if current_os == 'Windows': tuple_xy = _getTerminalSize_windows() if tuple_xy is None: tuple_xy = _getTerminalSize_tput() # needed for window's python in cygwin's xterm! if current_os == 'Linux' or current_os == 'Darwin' or current_os.startswith('CYGWIN'): tuple_xy = _getTerminalSize_linux() if tuple_xy is None: print "default" tuple_xy = (80, 25) # default value return tuple_xy def _getTerminalSize_windows(): res=None try: from ctypes import windll, create_string_buffer # stdin handle is -10 # stdout handle is -11 # stderr handle is -12 h = windll.kernel32.GetStdHandle(-12) csbi = create_string_buffer(22) res = windll.kernel32.GetConsoleScreenBufferInfo(h, csbi) except: return None if res: import struct (bufx, bufy, curx, cury, wattr, left, top, right, bottom, maxx, maxy) = struct.unpack("hhhhHhhhhhh", csbi.raw) sizex = right - left + 1 sizey = bottom - top + 1 return sizex, sizey else: return None def _getTerminalSize_tput(): # get terminal width # src: http://stackoverflow.com/questions/263890/how-do-i-find-the-width-height-of-a-terminal-window try: import subprocess proc=subprocess.Popen(["tput", "cols"],stdin=subprocess.PIPE,stdout=subprocess.PIPE) output=proc.communicate(input=None) cols=int(output[0]) proc=subprocess.Popen(["tput", "lines"],stdin=subprocess.PIPE,stdout=subprocess.PIPE) output=proc.communicate(input=None) rows=int(output[0]) return (cols,rows) except: return None def _getTerminalSize_linux(): def ioctl_GWINSZ(fd): try: import fcntl, termios, struct, os cr = struct.unpack('hh', fcntl.ioctl(fd, termios.TIOCGWINSZ,'1234')) except: return None return cr cr = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2) if not cr: try: fd = os.open(os.ctermid(), os.O_RDONLY) cr = ioctl_GWINSZ(fd) os.close(fd) except: pass if not cr: try: cr = (env['LINES'], env['COLUMNS']) except: return None return int(cr[1]), int(cr[0]) if __name__ == "__main__": sizex,sizey=getTerminalSize() print 'width =',sizex,'height =',sizey </code></pre>
32
2011-07-01T16:23:02Z
[ "python", "linux", "console", "terminal", "width" ]
How to get console window width in python
566,746
<p>Is there a way in python to programmatically determine the width of the console? I mean the number of characters that fits in one line without wrapping, not the pixel width of the window.</p> <p><b>Edit</b></p> <p>Looking for a solution that works on Linux</p>
151
2009-02-19T19:17:19Z
14,422,538
<p>Not sure why it is in the module <code>shutil</code>, but it landed there in Python 3.3, <a href="http://docs.python.org/3/library/shutil.html#querying-the-size-of-the-output-terminal">Querying the size of the output terminal</a>:</p> <pre><code>&gt;&gt;&gt; import shutil &gt;&gt;&gt; shutil.get_terminal_size((80, 20)) # pass fallback os.terminal_size(columns=87, lines=23) # returns named-tuple </code></pre> <p>A low-level implementation is in the os module.</p> <p>A backport is now available for Python 3.2 and below: </p> <ul> <li><a href="https://pypi.python.org/pypi/backports.shutil_get_terminal_size">https://pypi.python.org/pypi/backports.shutil_get_terminal_size</a></li> </ul>
93
2013-01-20T07:25:34Z
[ "python", "linux", "console", "terminal", "width" ]
How to get console window width in python
566,746
<p>Is there a way in python to programmatically determine the width of the console? I mean the number of characters that fits in one line without wrapping, not the pixel width of the window.</p> <p><b>Edit</b></p> <p>Looking for a solution that works on Linux</p>
151
2009-02-19T19:17:19Z
23,330,276
<p>Starting at Python 3.3 it is straight forward: <a href="https://docs.python.org/3/library/os.html#querying-the-size-of-a-terminal">https://docs.python.org/3/library/os.html#querying-the-size-of-a-terminal</a></p> <pre><code>&gt;&gt;&gt; import os &gt;&gt;&gt; ts = os.get_terminal_size() &gt;&gt;&gt; ts.lines 24 &gt;&gt;&gt; ts.columns 80 </code></pre>
10
2014-04-27T23:24:31Z
[ "python", "linux", "console", "terminal", "width" ]
How to get console window width in python
566,746
<p>Is there a way in python to programmatically determine the width of the console? I mean the number of characters that fits in one line without wrapping, not the pixel width of the window.</p> <p><b>Edit</b></p> <p>Looking for a solution that works on Linux</p>
151
2009-02-19T19:17:19Z
24,895,052
<p>@reannual's answer works well, but there's an issue with it: <code>os.popen</code> <a href="https://docs.python.org/2/library/os.html#os.popen" rel="nofollow">is now deprecated</a>. The <code>subprocess</code> module should be used instead, so here's a version of @reannual's code that uses <code>subprocess</code> and directly answers the question (by giving the column width directly as an <code>int</code>:</p> <pre><code>import subprocess columns = int(subprocess.check_output(['stty', 'size']).split()[1]) </code></pre> <p>Tested on OS X 10.9</p>
0
2014-07-22T18:30:16Z
[ "python", "linux", "console", "terminal", "width" ]
How to get console window width in python
566,746
<p>Is there a way in python to programmatically determine the width of the console? I mean the number of characters that fits in one line without wrapping, not the pixel width of the window.</p> <p><b>Edit</b></p> <p>Looking for a solution that works on Linux</p>
151
2009-02-19T19:17:19Z
25,730,885
<p>I was trying the solution from here that calls out to <code>stty size</code>:</p> <pre><code>columns = int(subprocess.check_output(['stty', 'size']).split()[1]) </code></pre> <p>However this failed for me because I was working on a script that expects redirected input on stdin, and <code>stty</code> would complain that "stdin isn't a terminal" in that case.</p> <p>I was able to make it work like this:</p> <pre><code>with open('/dev/tty') as tty: height, width = subprocess.check_output(['stty', 'size'], stdin=tty).split() </code></pre>
1
2014-09-08T18:36:32Z
[ "python", "linux", "console", "terminal", "width" ]
How to get console window width in python
566,746
<p>Is there a way in python to programmatically determine the width of the console? I mean the number of characters that fits in one line without wrapping, not the pixel width of the window.</p> <p><b>Edit</b></p> <p>Looking for a solution that works on Linux</p>
151
2009-02-19T19:17:19Z
27,619,961
<p>Try <strong>"blessings"</strong></p> <p>I was looking for the very same thing. It is very easy to use and offers tools for coloring, styling and positioning in the terminal. What you need is as easy as:</p> <pre><code>from blessings import Terminal t = Terminal() w = t.width h = t.height </code></pre> <p>Works like a charm in Linux. (I'm not sure about MacOSX and Windows)</p> <p>Download and documentation <a href="https://pypi.python.org/pypi/blessings/" rel="nofollow">here</a></p> <p>or you can install it with pip:</p> <pre><code>pip install blessings </code></pre>
1
2014-12-23T12:00:41Z
[ "python", "linux", "console", "terminal", "width" ]
How to get console window width in python
566,746
<p>Is there a way in python to programmatically determine the width of the console? I mean the number of characters that fits in one line without wrapping, not the pixel width of the window.</p> <p><b>Edit</b></p> <p>Looking for a solution that works on Linux</p>
151
2009-02-19T19:17:19Z
34,419,755
<p>If you're using Python 3.3 or above, I'd recommend the built-in <code>get_terminal_size()</code> as already recommended. However if you are stuck with an older version and want a simple, cross-platform way of doing this, you could use <a href="https://github.com/peterbrittain/asciimatics" rel="nofollow">asciimatics</a>. This package supports versions of Python back to 2.7 and uses similar options to those suggested above to get the current terminal/console size.</p> <p>Simply construct your <code>Screen</code> class and use the <code>dimensions</code> property to get the height and width. This has been proven to work on Linux, OSX and Windows.</p> <p>Oh - and full disclosure here: I am the author, so please feel free to open a new issue if you have any problems getting this to work.</p>
0
2015-12-22T15:58:18Z
[ "python", "linux", "console", "terminal", "width" ]
How to get console window width in python
566,746
<p>Is there a way in python to programmatically determine the width of the console? I mean the number of characters that fits in one line without wrapping, not the pixel width of the window.</p> <p><b>Edit</b></p> <p>Looking for a solution that works on Linux</p>
151
2009-02-19T19:17:19Z
37,556,647
<p>Many of the Python 2 implementations here will fail if there is no controlling terminal when you call this script. You can check sys.stdout.isatty() to determine if this is in fact a terminal, but that will exclude a bunch of cases, so I believe the most pythonic way to figure out the terminal size is to use the builtin curses package.</p> <pre><code>import curses w = curses.initscr() height, width = w.getmaxyx() </code></pre>
1
2016-05-31T22:26:04Z
[ "python", "linux", "console", "terminal", "width" ]
PyDev debugger different from command line django runserver command
566,819
<p>I am trying to debug a problem with a django view. When I run it on the command line. I don't get any of these messages. However when I run the it in the PyDev debugger i get these error messages. I am running with the <strong>--noreload</strong> option.</p> <p>What do these error messages mean?</p> <p>Why do I not get them when I run it on the command line?</p> <pre><code>/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/threading.py:697: RuntimeWarning: tp_compare didn't return -1 or -2 for exception return _active[_get_ident()] Exception exceptions.SystemError: 'error return without exception set' in &lt;generator object at 0x786c10&gt; ignored Exception exceptions.SystemError: 'error return without exception set' in &lt;generator object at 0x7904e0&gt; ignored </code></pre>
1
2009-02-19T19:36:57Z
567,183
<p>I seem to recall having similar issues debugging in PyDev related to the auto-reload mechanism of Django's test server. You can turn reloading off by passing --noreload to your runserver command. From there you just have to train yourself to restart your test server after making a code change while debugging.</p> <p><strong>EDIT</strong></p> <p>It's been a while since I used PyDev together with Django, but I do recall there being some warning messages spit out to the console that didn't affect my ability to debug. There are quite a few message board posts related to that message in debugging other Python libraries, but I didn't find any that have a resolution. </p> <p>I guess it is benign as long as you can ignore it and still debug your code. I don't think you need to be concerned that it's a problem with your application code, but something deep down in PyDev or the Python debugging facilities.</p>
1
2009-02-19T21:13:20Z
[ "python", "django", "eclipse", "pydev" ]
Simple Prime Generator in Python
567,222
<p>could someone please tell me what I'm doing wrong with this code. It is just printing 'count' anyway. I just want a very simple prime generator (nothing fancy). Thanks a lot. lincoln.</p> <pre><code>import math def main(): count = 3 one = 1 while one == 1: for x in range(2, int(math.sqrt(count) + 1)): if count % x == 0: continue if count % x != 0: print count count += 1 </code></pre>
21
2009-02-19T21:22:24Z
567,253
<ul> <li><p>The continue statement looks wrong.</p></li> <li><p>You want to start at 2 because 2 is the first prime number.</p></li> <li><p>You can write "while True:" to get an infinite loop.</p></li> </ul>
0
2009-02-19T21:30:06Z
[ "python", "primes" ]
Simple Prime Generator in Python
567,222
<p>could someone please tell me what I'm doing wrong with this code. It is just printing 'count' anyway. I just want a very simple prime generator (nothing fancy). Thanks a lot. lincoln.</p> <pre><code>import math def main(): count = 3 one = 1 while one == 1: for x in range(2, int(math.sqrt(count) + 1)): if count % x == 0: continue if count % x != 0: print count count += 1 </code></pre>
21
2009-02-19T21:22:24Z
567,259
<p>This seems homework-y, so I'll give a hint rather than a detailed explanation. Correct me if I've assumed wrong.</p> <p>You're doing fine as far as bailing out when you see an even divisor. </p> <p>But you're printing 'count' as soon as you see even <em>one</em> number that doesn't divide into it. 2, for instance, does not divide evenly into 9. But that doesn't make 9 a prime. You might want to keep going until you're sure <em>no</em> number in the range matches.</p> <p>(as others have replied, a Sieve is a much more efficient way to go... just trying to help you understand why this specific code isn't doing what you want)</p>
1
2009-02-19T21:31:30Z
[ "python", "primes" ]
Simple Prime Generator in Python
567,222
<p>could someone please tell me what I'm doing wrong with this code. It is just printing 'count' anyway. I just want a very simple prime generator (nothing fancy). Thanks a lot. lincoln.</p> <pre><code>import math def main(): count = 3 one = 1 while one == 1: for x in range(2, int(math.sqrt(count) + 1)): if count % x == 0: continue if count % x != 0: print count count += 1 </code></pre>
21
2009-02-19T21:22:24Z
567,281
<p>You need to make sure that all possible divisors don't evenly divide the number you're checking. In this case you'll print the number you're checking any time just one of the possible divisors doesn't evenly divide the number.</p> <p>Also you don't want to use a continue statement because a continue will just cause it to check the next possible divisor when you've already found out that the number is not a prime.</p>
0
2009-02-19T21:35:36Z
[ "python", "primes" ]
Simple Prime Generator in Python
567,222
<p>could someone please tell me what I'm doing wrong with this code. It is just printing 'count' anyway. I just want a very simple prime generator (nothing fancy). Thanks a lot. lincoln.</p> <pre><code>import math def main(): count = 3 one = 1 while one == 1: for x in range(2, int(math.sqrt(count) + 1)): if count % x == 0: continue if count % x != 0: print count count += 1 </code></pre>
21
2009-02-19T21:22:24Z
568,618
<p>There are some problems:</p> <ul> <li>Why do you print out count when it didn't divide by x? It doesn't mean it's prime, it means only that this particular x doesn't divide it</li> <li><code>continue</code> moves to the next loop iteration - but you really want to stop it using <code>break</code></li> </ul> <p>Here's your code with a few fixes, it prints out only primes:</p> <pre><code>import math def main(): count = 3   while True: isprime = True   for x in range(2, int(math.sqrt(count) + 1)): if count % x == 0: isprime = False break   if isprime: print count   count += 1 </code></pre> <p>For much more efficient prime generation, see the Sieve of Erastothenes, as others have suggested. Here's a nice, optimized implementation with many comments:</p> <pre><code># Sieve of Eratosthenes # Code by David Eppstein, UC Irvine, 28 Feb 2002 # http://code.activestate.com/recipes/117119/ def gen_primes(): """ Generate an infinite sequence of prime numbers. """ # Maps composites to primes witnessing their compositeness. # This is memory efficient, as the sieve is not "run forward" # indefinitely, but only as long as required by the current # number being tested. # D = {}   # The running integer that's checked for primeness q = 2   while True: if q not in D: # q is a new prime. # Yield it and mark its first multiple that isn't # already marked in previous iterations # yield q D[q * q] = [q] else: # q is composite. D[q] is the list of primes that # divide it. Since we've reached q, we no longer # need it in the map, but we'll mark the next # multiples of its witnesses to prepare for larger # numbers # for p in D[q]: D.setdefault(p + q, []).append(p) del D[q]   q += 1 </code></pre> <p>Note that it returns a generator.</p>
108
2009-02-20T07:42:03Z
[ "python", "primes" ]
Simple Prime Generator in Python
567,222
<p>could someone please tell me what I'm doing wrong with this code. It is just printing 'count' anyway. I just want a very simple prime generator (nothing fancy). Thanks a lot. lincoln.</p> <pre><code>import math def main(): count = 3 one = 1 while one == 1: for x in range(2, int(math.sqrt(count) + 1)): if count % x == 0: continue if count % x != 0: print count count += 1 </code></pre>
21
2009-02-19T21:22:24Z
568,684
<pre><code>def is_prime(num): """Returns True if the number is prime else False.""" if num == 0 or num == 1: return False for x in range(2, num): if num % x == 0: return False else: return True &gt;&gt; filter(is_prime, range(1, 20)) [2, 3, 5, 7, 11, 13, 17, 19] </code></pre> <p>We will get all the prime numbers upto 20 in a list. I could have used Sieve of Eratosthenes but you said you want something very simple. ;)</p>
8
2009-02-20T08:13:32Z
[ "python", "primes" ]
Simple Prime Generator in Python
567,222
<p>could someone please tell me what I'm doing wrong with this code. It is just printing 'count' anyway. I just want a very simple prime generator (nothing fancy). Thanks a lot. lincoln.</p> <pre><code>import math def main(): count = 3 one = 1 while one == 1: for x in range(2, int(math.sqrt(count) + 1)): if count % x == 0: continue if count % x != 0: print count count += 1 </code></pre>
21
2009-02-19T21:22:24Z
660,070
<p>Here is what I have:</p> <pre><code>def is_prime(num): if num &lt; 2: return False elif num &lt; 4: return True elif not num % 2: return False elif num &lt; 9: return True elif not num % 3: return False else: for n in range(5, int(math.sqrt(num) + 1), 6): if not num % n: return False elif not num % (n + 2): return False return True </code></pre> <p>It's pretty fast for large numbers, as it only checks against already prime numbers for divisors of a number.</p> <p>Now if you want to generate a list of primes, you can do:</p> <pre><code># primes up to 'max' def primes_max(max): yield 2 for n in range(3, max, 2): if is_prime(n): yield n # the first 'count' primes def primes_count(count): counter = 0 num = 3 yield 2 while counter &lt; count: if is_prime(num): yield num counter += 1 num += 2 </code></pre> <p>using generators here might be desired for efficiency.</p> <p>And just for reference, instead of saying:</p> <pre><code>one = 1 while one == 1: # do stuff </code></pre> <p>you can simply say:</p> <pre><code>while 1: #do stuff </code></pre>
0
2009-03-18T20:57:56Z
[ "python", "primes" ]
Simple Prime Generator in Python
567,222
<p>could someone please tell me what I'm doing wrong with this code. It is just printing 'count' anyway. I just want a very simple prime generator (nothing fancy). Thanks a lot. lincoln.</p> <pre><code>import math def main(): count = 3 one = 1 while one == 1: for x in range(2, int(math.sqrt(count) + 1)): if count % x == 0: continue if count % x != 0: print count count += 1 </code></pre>
21
2009-02-19T21:22:24Z
660,658
<p>You can create a list of primes using list comprehensions in a fairly elegant manner. Taken from <a href="http://www.secnetix.de/~olli/Python/list%5Fcomprehensions.hawk" rel="nofollow">here:</a></p> <pre><code>&gt;&gt;&gt; noprimes = [j for i in range(2, 8) for j in range(i*2, 50, i)] &gt;&gt;&gt; primes = [x for x in range(2, 50) if x not in noprimes] &gt;&gt;&gt; print primes &gt;&gt;&gt; [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47] </code></pre>
0
2009-03-19T00:37:50Z
[ "python", "primes" ]
Simple Prime Generator in Python
567,222
<p>could someone please tell me what I'm doing wrong with this code. It is just printing 'count' anyway. I just want a very simple prime generator (nothing fancy). Thanks a lot. lincoln.</p> <pre><code>import math def main(): count = 3 one = 1 while one == 1: for x in range(2, int(math.sqrt(count) + 1)): if count % x == 0: continue if count % x != 0: print count count += 1 </code></pre>
21
2009-02-19T21:22:24Z
1,081,435
<p>Here's a <em>simple</em> (Python 2.6.2) solution... which is in-line with the OP's original request (now six-months old); and should be a perfectly acceptable solution in any "programming 101" course... Hence this post.</p> <pre><code>import math def isPrime(n): for i in range(2, int(math.sqrt(n)+1)): if n % i == 0: return False; return n&gt;1; print 2 for n in range(3, 50): if isPrime(n): print n </code></pre> <p>This simple "brute force" method is "fast enough" for numbers upto about about 16,000 on modern PC's (took about 8 seconds on my 2GHz box).</p> <p>Obviously, this could be done much more efficiently, by not recalculating the primeness of every even number, or every multiple of 3, 5, 7, etc for every single number... See the <a href="http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes" rel="nofollow">Sieve of Eratosthenes</a> (see eliben's implementation above), or even the <a href="http://en.wikipedia.org/wiki/Sieve_of_Atkin" rel="nofollow">Sieve of Atkin</a> if you're feeling particularly brave and/or crazy.</p> <p>Caveat Emptor: I'm a python noob. Please don't take anything I say as gospel.</p>
3
2009-07-04T03:38:20Z
[ "python", "primes" ]
Simple Prime Generator in Python
567,222
<p>could someone please tell me what I'm doing wrong with this code. It is just printing 'count' anyway. I just want a very simple prime generator (nothing fancy). Thanks a lot. lincoln.</p> <pre><code>import math def main(): count = 3 one = 1 while one == 1: for x in range(2, int(math.sqrt(count) + 1)): if count % x == 0: continue if count % x != 0: print count count += 1 </code></pre>
21
2009-02-19T21:22:24Z
2,624,386
<pre><code>print [x for x in range(2,100) if not [t for t in range(2,x) if not x%t]] </code></pre>
7
2010-04-12T18:28:58Z
[ "python", "primes" ]
Simple Prime Generator in Python
567,222
<p>could someone please tell me what I'm doing wrong with this code. It is just printing 'count' anyway. I just want a very simple prime generator (nothing fancy). Thanks a lot. lincoln.</p> <pre><code>import math def main(): count = 3 one = 1 while one == 1: for x in range(2, int(math.sqrt(count) + 1)): if count % x == 0: continue if count % x != 0: print count count += 1 </code></pre>
21
2009-02-19T21:22:24Z
5,543,655
<pre><code>def check_prime(x): if (x &lt; 2): return 0 elif (x == 2): return 1 t = range(x) for i in t[2:]: if (x % i == 0): return 0 return 1 </code></pre>
0
2011-04-04T20:00:25Z
[ "python", "primes" ]
Simple Prime Generator in Python
567,222
<p>could someone please tell me what I'm doing wrong with this code. It is just printing 'count' anyway. I just want a very simple prime generator (nothing fancy). Thanks a lot. lincoln.</p> <pre><code>import math def main(): count = 3 one = 1 while one == 1: for x in range(2, int(math.sqrt(count) + 1)): if count % x == 0: continue if count % x != 0: print count count += 1 </code></pre>
21
2009-02-19T21:22:24Z
9,247,082
<p>How about this if you want to compute the prime directly:</p> <pre><code>def oprime(n): counter = 0 b = 1 if n == 1: print 2 while counter &lt; n-1: b = b + 2 for a in range(2,b): if b % a == 0: break else: counter = counter + 1 if counter == n-1: print b </code></pre>
1
2012-02-12T07:04:00Z
[ "python", "primes" ]
Simple Prime Generator in Python
567,222
<p>could someone please tell me what I'm doing wrong with this code. It is just printing 'count' anyway. I just want a very simple prime generator (nothing fancy). Thanks a lot. lincoln.</p> <pre><code>import math def main(): count = 3 one = 1 while one == 1: for x in range(2, int(math.sqrt(count) + 1)): if count % x == 0: continue if count % x != 0: print count count += 1 </code></pre>
21
2009-02-19T21:22:24Z
10,348,627
<p>To my opinion it is always best to take the functional approach,</p> <p>So I create a function first to find out if the number is prime or not then use it in loop or other place as necessary.</p> <pre><code>def isprime(n): for x in range(2,n): if n%x == 0: return False return True </code></pre> <p>Then run a simple list comprehension or generator expression to get your list of prime,</p> <pre><code>[x for x in range(1,100) if isprime(x)] </code></pre>
2
2012-04-27T10:01:25Z
[ "python", "primes" ]
Simple Prime Generator in Python
567,222
<p>could someone please tell me what I'm doing wrong with this code. It is just printing 'count' anyway. I just want a very simple prime generator (nothing fancy). Thanks a lot. lincoln.</p> <pre><code>import math def main(): count = 3 one = 1 while one == 1: for x in range(2, int(math.sqrt(count) + 1)): if count % x == 0: continue if count % x != 0: print count count += 1 </code></pre>
21
2009-02-19T21:22:24Z
11,787,948
<p>Similar to user107745, but using 'all' instead of double negation (a little bit more readable, but I think same performance):</p> <pre><code>import math [x for x in xrange(2,10000) if all(x%t for t in xrange(2,int(math.sqrt(x))+1))] </code></pre> <p>Basically it iterates over the x in range of (2, 100) and picking only those that do not have mod == 0 for all t in range(2,x)</p> <p>Another way is probably just populating the prime numbers as we go:</p> <pre><code>primes = set() def isPrime(x): if x in primes: return x for i in primes: if not x % i: return None else: primes.add(x) return x filter(isPrime, range(2,10000)) </code></pre>
0
2012-08-03T01:04:57Z
[ "python", "primes" ]
Simple Prime Generator in Python
567,222
<p>could someone please tell me what I'm doing wrong with this code. It is just printing 'count' anyway. I just want a very simple prime generator (nothing fancy). Thanks a lot. lincoln.</p> <pre><code>import math def main(): count = 3 one = 1 while one == 1: for x in range(2, int(math.sqrt(count) + 1)): if count % x == 0: continue if count % x != 0: print count count += 1 </code></pre>
21
2009-02-19T21:22:24Z
15,587,546
<pre><code>def genPrimes(): primes = [] # primes generated so far last = 1 # last number tried while True: last += 1 for p in primes: if last % p == 0: break else: primes.append(last) yield last </code></pre>
0
2013-03-23T13:52:26Z
[ "python", "primes" ]
Simple Prime Generator in Python
567,222
<p>could someone please tell me what I'm doing wrong with this code. It is just printing 'count' anyway. I just want a very simple prime generator (nothing fancy). Thanks a lot. lincoln.</p> <pre><code>import math def main(): count = 3 one = 1 while one == 1: for x in range(2, int(math.sqrt(count) + 1)): if count % x == 0: continue if count % x != 0: print count count += 1 </code></pre>
21
2009-02-19T21:22:24Z
16,899,075
<p>Another simple example, with a simple optimization of only considering odd numbers. Everything done with lazy streams (python generators).</p> <p>Usage: primes = list(create_prime_iterator(1, 30))</p> <pre><code>import math import itertools def create_prime_iterator(rfrom, rto): """Create iterator of prime numbers in range [rfrom, rto]""" prefix = [2] if rfrom &lt; 3 and rto &gt; 1 else [] # include 2 if it is in range separately as it is a "weird" case of even prime odd_rfrom = 3 if rfrom &lt; 3 else make_odd(rfrom) # make rfrom an odd number so that we can skip all even nubers when searching for primes, also skip 1 as a non prime odd number. odd_numbers = (num for num in xrange(odd_rfrom, rto + 1, 2)) prime_generator = (num for num in odd_numbers if not has_odd_divisor(num)) return itertools.chain(prefix, prime_generator) def has_odd_divisor(num): """Test whether number is evenly divisable by odd divisor.""" maxDivisor = int(math.sqrt(num)) for divisor in xrange(3, maxDivisor + 1, 2): if num % divisor == 0: return True return False def make_odd(number): """Make number odd by adding one to it if it was even, otherwise return it unchanged""" return number | 1 </code></pre>
0
2013-06-03T14:26:17Z
[ "python", "primes" ]
Simple Prime Generator in Python
567,222
<p>could someone please tell me what I'm doing wrong with this code. It is just printing 'count' anyway. I just want a very simple prime generator (nothing fancy). Thanks a lot. lincoln.</p> <pre><code>import math def main(): count = 3 one = 1 while one == 1: for x in range(2, int(math.sqrt(count) + 1)): if count % x == 0: continue if count % x != 0: print count count += 1 </code></pre>
21
2009-02-19T21:22:24Z
19,498,432
<pre><code>def primes(n): # simple Sieve of Eratosthenes odds = range(3, n+1, 2) sieve = set(sum([range(q*q, n+1, q+q) for q in odds],[])) return [2] + [p for p in odds if p not in sieve] &gt;&gt;&gt; primes(50) [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47] </code></pre> <p>To test if a number is prime:</p> <pre><code>&gt;&gt;&gt; 541 in primes(541) True &gt;&gt;&gt; 543 in primes(543) False </code></pre>
3
2013-10-21T15:19:17Z
[ "python", "primes" ]
Simple Prime Generator in Python
567,222
<p>could someone please tell me what I'm doing wrong with this code. It is just printing 'count' anyway. I just want a very simple prime generator (nothing fancy). Thanks a lot. lincoln.</p> <pre><code>import math def main(): count = 3 one = 1 while one == 1: for x in range(2, int(math.sqrt(count) + 1)): if count % x == 0: continue if count % x != 0: print count count += 1 </code></pre>
21
2009-02-19T21:22:24Z
26,517,655
<pre><code>import time maxnum=input("You want the prime number of 1 through....") n=2 prime=[] start=time.time() while n&lt;=maxnum: d=2.0 pr=True cntr=0 while d&lt;n**.5: if n%d==0: pr=False else: break d=d+1 if cntr==0: prime.append(n) #print n n=n+1 print "Total time:",time.time()-start </code></pre>
-1
2014-10-22T21:43:20Z
[ "python", "primes" ]
Simple Prime Generator in Python
567,222
<p>could someone please tell me what I'm doing wrong with this code. It is just printing 'count' anyway. I just want a very simple prime generator (nothing fancy). Thanks a lot. lincoln.</p> <pre><code>import math def main(): count = 3 one = 1 while one == 1: for x in range(2, int(math.sqrt(count) + 1)): if count % x == 0: continue if count % x != 0: print count count += 1 </code></pre>
21
2009-02-19T21:22:24Z
33,951,990
<p>re is powerful:</p> <pre><code>import re def isprime(n): return re.compile(r'^1?$|^(11+)\1+$').match('1' * n) is None print [x for x in range(100) if isprime(x)] ###########Output############# [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97] </code></pre>
1
2015-11-27T07:09:37Z
[ "python", "primes" ]
Is it safe to use Python UUID module generated values in URL's of a webpage?
567,324
<p>Is it safe to use Python UUID module generated values in URL's of a webpage? Wnat to use those ID's as part of URL's. Are there any non-safe characters ever generated by Python UUID that shouldn't be in URL's?</p>
2
2009-02-19T21:47:29Z
567,337
<p>They are safe. See <a href="http://docs.python.org/library/uuid.html">here</a> for all possible output formats. All of them are readable strings or ints.</p>
6
2009-02-19T21:48:52Z
[ "python", "url", "uuid" ]
Is it safe to use Python UUID module generated values in URL's of a webpage?
567,324
<p>Is it safe to use Python UUID module generated values in URL's of a webpage? Wnat to use those ID's as part of URL's. Are there any non-safe characters ever generated by Python UUID that shouldn't be in URL's?</p>
2
2009-02-19T21:47:29Z
567,347
<p>It is good practice to <strong>always</strong> urlencode data that will be placed into URLs. Then you need not be concerned with the specifics of UUID or if it will change in the future.</p>
7
2009-02-19T21:51:42Z
[ "python", "url", "uuid" ]
Is it safe to use Python UUID module generated values in URL's of a webpage?
567,324
<p>Is it safe to use Python UUID module generated values in URL's of a webpage? Wnat to use those ID's as part of URL's. Are there any non-safe characters ever generated by Python UUID that shouldn't be in URL's?</p>
2
2009-02-19T21:47:29Z
18,518,355
<p>I use GUIDs mainly as primary keys and often need to pass them around as URL arguments.</p> <p>The hexadecimal form, with the dashes and extra characters seem unnecessarily long to me. But I also like that strings representing hexadecimal numbers are very safe in that they do not contain characters that can cause problems with URLs.</p> <p>Instead of hexadecimal, I use a url-safe base64 string. The following is some Python code that does this. It does not conform to any UUID/GUID spec though (other than having the required amount of randomness).</p> <pre><code>import base64 import uuid # get a UUID - URL safe, Base64 def get_a_Uuid(): r_uuid = base64.urlsafe_b64encode(uuid.uuid4().bytes) return r_uuid.replace('=', '') </code></pre>
0
2013-08-29T18:23:37Z
[ "python", "url", "uuid" ]
running a command as a super user from a python script
567,542
<p>So I'm trying to get a process to be run as a super user from within a python script using subprocess. In the ipython shell something like</p> <pre><code>proc = subprocess.Popen('sudo apach2ctl restart', shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) </code></pre> <p>works fine, but as soon as I stick it into a script I start getting: <code>sudo: apach2ctl: command not found</code>.</p> <p>I would guess this is due to the way sudo handles environments on ubuntu. (I've also tried <code>sudo -E apche2ctl restart</code> and <code>sudo env path=$PATH apache2ctl restart</code> with no avail)</p> <p>So my question is basically, if I want to run <code>apache2ctl restart</code> as super user that prompts the user for the super user password when required, how should I go about doing this? I have no intention of storing passwords in the script.</p> <p>Edit:</p> <p>I've tried passing in the commands as both a string and tokenized into a list. In the python interpreter, with a string I'll get the password prompt properly (still doesnt work in a python script as in my original problem), a list just gives the help screen for sudo.</p> <p>Edit 2:</p> <p>So what I gather is that while Popen will work with some commands just as strings when shell=True, it takes </p> <pre><code>proc = subprocess.Popen(['sudo','/usr/sbin/apache2ctl','restart']) </code></pre> <p>without 'shell=True' to get sudo to work.</p> <p>Thanks!</p>
19
2009-02-19T22:33:16Z
567,554
<p>You have to use Popen like this:</p> <pre><code>cmd = ['sudo', 'apache2ctl', 'restart'] proc = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) </code></pre> <p>It expects a list.</p>
2
2009-02-19T22:35:06Z
[ "python", "subprocess", "sudo" ]
running a command as a super user from a python script
567,542
<p>So I'm trying to get a process to be run as a super user from within a python script using subprocess. In the ipython shell something like</p> <pre><code>proc = subprocess.Popen('sudo apach2ctl restart', shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) </code></pre> <p>works fine, but as soon as I stick it into a script I start getting: <code>sudo: apach2ctl: command not found</code>.</p> <p>I would guess this is due to the way sudo handles environments on ubuntu. (I've also tried <code>sudo -E apche2ctl restart</code> and <code>sudo env path=$PATH apache2ctl restart</code> with no avail)</p> <p>So my question is basically, if I want to run <code>apache2ctl restart</code> as super user that prompts the user for the super user password when required, how should I go about doing this? I have no intention of storing passwords in the script.</p> <p>Edit:</p> <p>I've tried passing in the commands as both a string and tokenized into a list. In the python interpreter, with a string I'll get the password prompt properly (still doesnt work in a python script as in my original problem), a list just gives the help screen for sudo.</p> <p>Edit 2:</p> <p>So what I gather is that while Popen will work with some commands just as strings when shell=True, it takes </p> <pre><code>proc = subprocess.Popen(['sudo','/usr/sbin/apache2ctl','restart']) </code></pre> <p>without 'shell=True' to get sudo to work.</p> <p>Thanks!</p>
19
2009-02-19T22:33:16Z
567,599
<p>Try giving the full path to apache2ctl.</p>
11
2009-02-19T22:46:38Z
[ "python", "subprocess", "sudo" ]
running a command as a super user from a python script
567,542
<p>So I'm trying to get a process to be run as a super user from within a python script using subprocess. In the ipython shell something like</p> <pre><code>proc = subprocess.Popen('sudo apach2ctl restart', shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) </code></pre> <p>works fine, but as soon as I stick it into a script I start getting: <code>sudo: apach2ctl: command not found</code>.</p> <p>I would guess this is due to the way sudo handles environments on ubuntu. (I've also tried <code>sudo -E apche2ctl restart</code> and <code>sudo env path=$PATH apache2ctl restart</code> with no avail)</p> <p>So my question is basically, if I want to run <code>apache2ctl restart</code> as super user that prompts the user for the super user password when required, how should I go about doing this? I have no intention of storing passwords in the script.</p> <p>Edit:</p> <p>I've tried passing in the commands as both a string and tokenized into a list. In the python interpreter, with a string I'll get the password prompt properly (still doesnt work in a python script as in my original problem), a list just gives the help screen for sudo.</p> <p>Edit 2:</p> <p>So what I gather is that while Popen will work with some commands just as strings when shell=True, it takes </p> <pre><code>proc = subprocess.Popen(['sudo','/usr/sbin/apache2ctl','restart']) </code></pre> <p>without 'shell=True' to get sudo to work.</p> <p>Thanks!</p>
19
2009-02-19T22:33:16Z
567,687
<p>Try:</p> <p><code>subprocess.call(['sudo', 'apach2ctl', 'restart'])</code></p> <p>The subprocess needs to access the real stdin/out/err for it to be able to prompt you, and read in your password. If you set them up as pipes, you need to feed the password into that pipe yourself.</p> <p>If you don't define them, then it grabs sys.stdout, etc...</p>
14
2009-02-19T23:11:30Z
[ "python", "subprocess", "sudo" ]
running a command as a super user from a python script
567,542
<p>So I'm trying to get a process to be run as a super user from within a python script using subprocess. In the ipython shell something like</p> <pre><code>proc = subprocess.Popen('sudo apach2ctl restart', shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) </code></pre> <p>works fine, but as soon as I stick it into a script I start getting: <code>sudo: apach2ctl: command not found</code>.</p> <p>I would guess this is due to the way sudo handles environments on ubuntu. (I've also tried <code>sudo -E apche2ctl restart</code> and <code>sudo env path=$PATH apache2ctl restart</code> with no avail)</p> <p>So my question is basically, if I want to run <code>apache2ctl restart</code> as super user that prompts the user for the super user password when required, how should I go about doing this? I have no intention of storing passwords in the script.</p> <p>Edit:</p> <p>I've tried passing in the commands as both a string and tokenized into a list. In the python interpreter, with a string I'll get the password prompt properly (still doesnt work in a python script as in my original problem), a list just gives the help screen for sudo.</p> <p>Edit 2:</p> <p>So what I gather is that while Popen will work with some commands just as strings when shell=True, it takes </p> <pre><code>proc = subprocess.Popen(['sudo','/usr/sbin/apache2ctl','restart']) </code></pre> <p>without 'shell=True' to get sudo to work.</p> <p>Thanks!</p>
19
2009-02-19T22:33:16Z
24,643,463
<p>Another way is to make your user a password-less <code>sudo user</code>.</p> <p>Type the following on command line:</p> <pre><code>sudo visudo </code></pre> <p>Then add the following and replace the <code>&lt;username&gt;</code> with yours:</p> <pre><code>&lt;username&gt; ALL=(ALL) NOPASSWD: ALL </code></pre> <p>This will allow the user to execute <code>sudo</code> command without having to ask for password (including application launched by the said user. <strong>This might be a security risk though</strong></p>
3
2014-07-09T00:06:59Z
[ "python", "subprocess", "sudo" ]
is there a pythonic way to try something up to a maximum number of times?
567,622
<p>I have a python script which is querying a MySQL server on a shared linux host. For some reason, queries to MySQL often return a "server has gone away" error:</p> <pre><code>_mysql_exceptions.OperationalError: (2006, 'MySQL server has gone away') </code></pre> <p>If you try the query again immediately afterwards, it usually succeeds. So, I'd like to know if there's a sensible way in python to try to execute a query, and if it fails, to try again, up to a fixed number of tries. Probably I'd want it to try 5 times before giving up altogether.</p> <p>Here's the kind of code I have:</p> <pre><code>conn = MySQLdb.connect(host, user, password, database) cursor = conn.cursor() try: cursor.execute(query) rows = cursor.fetchall() for row in rows: # do something with the data except MySQLdb.Error, e: print "MySQL Error %d: %s" % (e.args[0], e.args[1]) </code></pre> <p>Clearly I could do it by having another attempt in the except clause, but that's incredibly ugly, and I have a feeling there must be a decent way to achieve this.</p>
59
2009-02-19T22:52:01Z
567,645
<p>How about:</p> <pre><code>conn = MySQLdb.connect(host, user, password, database) cursor = conn.cursor() attempts = 0 while attempts &lt; 3: try: cursor.execute(query) rows = cursor.fetchall() for row in rows: # do something with the data break except MySQLdb.Error, e: attempts += 1 print "MySQL Error %d: %s" % (e.args[0], e.args[1]) </code></pre>
55
2009-02-19T23:00:09Z
[ "python", "exception-handling" ]
is there a pythonic way to try something up to a maximum number of times?
567,622
<p>I have a python script which is querying a MySQL server on a shared linux host. For some reason, queries to MySQL often return a "server has gone away" error:</p> <pre><code>_mysql_exceptions.OperationalError: (2006, 'MySQL server has gone away') </code></pre> <p>If you try the query again immediately afterwards, it usually succeeds. So, I'd like to know if there's a sensible way in python to try to execute a query, and if it fails, to try again, up to a fixed number of tries. Probably I'd want it to try 5 times before giving up altogether.</p> <p>Here's the kind of code I have:</p> <pre><code>conn = MySQLdb.connect(host, user, password, database) cursor = conn.cursor() try: cursor.execute(query) rows = cursor.fetchall() for row in rows: # do something with the data except MySQLdb.Error, e: print "MySQL Error %d: %s" % (e.args[0], e.args[1]) </code></pre> <p>Clearly I could do it by having another attempt in the except clause, but that's incredibly ugly, and I have a feeling there must be a decent way to achieve this.</p>
59
2009-02-19T22:52:01Z
567,691
<p>I'd refactor it like so:</p> <pre><code>def callee(cursor): cursor.execute(query) rows = cursor.fetchall() for row in rows: # do something with the data def caller(attempt_count=3, wait_interval=20): """:param wait_interval: In seconds.""" conn = MySQLdb.connect(host, user, password, database) cursor = conn.cursor() for attempt_number in range(attempt_count): try: callee(cursor) except MySQLdb.Error, e: logging.warn("MySQL Error %d: %s", e.args[0], e.args[1]) time.sleep(wait_interval) else: break </code></pre> <p>Factoring out the <code>callee</code> function seems to break up the functionality so that it's easy to see the business logic without getting bogged down in the retry code.</p>
5
2009-02-19T23:13:06Z
[ "python", "exception-handling" ]
is there a pythonic way to try something up to a maximum number of times?
567,622
<p>I have a python script which is querying a MySQL server on a shared linux host. For some reason, queries to MySQL often return a "server has gone away" error:</p> <pre><code>_mysql_exceptions.OperationalError: (2006, 'MySQL server has gone away') </code></pre> <p>If you try the query again immediately afterwards, it usually succeeds. So, I'd like to know if there's a sensible way in python to try to execute a query, and if it fails, to try again, up to a fixed number of tries. Probably I'd want it to try 5 times before giving up altogether.</p> <p>Here's the kind of code I have:</p> <pre><code>conn = MySQLdb.connect(host, user, password, database) cursor = conn.cursor() try: cursor.execute(query) rows = cursor.fetchall() for row in rows: # do something with the data except MySQLdb.Error, e: print "MySQL Error %d: %s" % (e.args[0], e.args[1]) </code></pre> <p>Clearly I could do it by having another attempt in the except clause, but that's incredibly ugly, and I have a feeling there must be a decent way to achieve this.</p>
59
2009-02-19T22:52:01Z
567,697
<p>Building on Dana's answer, you might want to do this as a decorator:</p> <pre><code>def retry(howmany): def tryIt(func): def f(): attempts = 0 while attempts &lt; howmany: try: return func() except: attempts += 1 return f return tryIt </code></pre> <p>Then...</p> <pre><code>@retry(5) def the_db_func(): # [...] </code></pre> <h3>Enhanced version that uses the <code>decorator</code> module</h3> <pre><code>import decorator, time def retry(howmany, *exception_types, **kwargs): timeout = kwargs.get('timeout', 0.0) # seconds @decorator.decorator def tryIt(func, *fargs, **fkwargs): for _ in xrange(howmany): try: return func(*fargs, **fkwargs) except exception_types or Exception: if timeout is not None: time.sleep(timeout) return tryIt </code></pre> <p>Then...</p> <pre><code>@retry(5, MySQLdb.Error, timeout=0.5) def the_db_func(): # [...] </code></pre> <p>To install <a href="http://pypi.python.org/pypi/decorator">the <code>decorator</code> module</a>:</p> <pre><code>$ easy_install decorator </code></pre>
65
2009-02-19T23:16:22Z
[ "python", "exception-handling" ]
is there a pythonic way to try something up to a maximum number of times?
567,622
<p>I have a python script which is querying a MySQL server on a shared linux host. For some reason, queries to MySQL often return a "server has gone away" error:</p> <pre><code>_mysql_exceptions.OperationalError: (2006, 'MySQL server has gone away') </code></pre> <p>If you try the query again immediately afterwards, it usually succeeds. So, I'd like to know if there's a sensible way in python to try to execute a query, and if it fails, to try again, up to a fixed number of tries. Probably I'd want it to try 5 times before giving up altogether.</p> <p>Here's the kind of code I have:</p> <pre><code>conn = MySQLdb.connect(host, user, password, database) cursor = conn.cursor() try: cursor.execute(query) rows = cursor.fetchall() for row in rows: # do something with the data except MySQLdb.Error, e: print "MySQL Error %d: %s" % (e.args[0], e.args[1]) </code></pre> <p>Clearly I could do it by having another attempt in the except clause, but that's incredibly ugly, and I have a feeling there must be a decent way to achieve this.</p>
59
2009-02-19T22:52:01Z
567,749
<pre><code>conn = MySQLdb.connect(host, user, password, database) cursor = conn.cursor() for i in range(3): try: cursor.execute(query) rows = cursor.fetchall() for row in rows: # do something with the data break except MySQLdb.Error, e: print "MySQL Error %d: %s" % (e.args[0], e.args[1]) </code></pre>
6
2009-02-19T23:43:51Z
[ "python", "exception-handling" ]
is there a pythonic way to try something up to a maximum number of times?
567,622
<p>I have a python script which is querying a MySQL server on a shared linux host. For some reason, queries to MySQL often return a "server has gone away" error:</p> <pre><code>_mysql_exceptions.OperationalError: (2006, 'MySQL server has gone away') </code></pre> <p>If you try the query again immediately afterwards, it usually succeeds. So, I'd like to know if there's a sensible way in python to try to execute a query, and if it fails, to try again, up to a fixed number of tries. Probably I'd want it to try 5 times before giving up altogether.</p> <p>Here's the kind of code I have:</p> <pre><code>conn = MySQLdb.connect(host, user, password, database) cursor = conn.cursor() try: cursor.execute(query) rows = cursor.fetchall() for row in rows: # do something with the data except MySQLdb.Error, e: print "MySQL Error %d: %s" % (e.args[0], e.args[1]) </code></pre> <p>Clearly I could do it by having another attempt in the except clause, but that's incredibly ugly, and I have a feeling there must be a decent way to achieve this.</p>
59
2009-02-19T22:52:01Z
574,924
<p>Like S.Lott, I like a flag to check if we're done:</p> <pre><code>conn = MySQLdb.connect(host, user, password, database) cursor = conn.cursor() success = False attempts = 0 while attempts &lt; 3 and not success: try: cursor.execute(query) rows = cursor.fetchall() for row in rows: # do something with the data success = True except MySQLdb.Error, e: print "MySQL Error %d: %s" % (e.args[0], e.args[1]) attempts += 1 </code></pre>
6
2009-02-22T13:24:47Z
[ "python", "exception-handling" ]
is there a pythonic way to try something up to a maximum number of times?
567,622
<p>I have a python script which is querying a MySQL server on a shared linux host. For some reason, queries to MySQL often return a "server has gone away" error:</p> <pre><code>_mysql_exceptions.OperationalError: (2006, 'MySQL server has gone away') </code></pre> <p>If you try the query again immediately afterwards, it usually succeeds. So, I'd like to know if there's a sensible way in python to try to execute a query, and if it fails, to try again, up to a fixed number of tries. Probably I'd want it to try 5 times before giving up altogether.</p> <p>Here's the kind of code I have:</p> <pre><code>conn = MySQLdb.connect(host, user, password, database) cursor = conn.cursor() try: cursor.execute(query) rows = cursor.fetchall() for row in rows: # do something with the data except MySQLdb.Error, e: print "MySQL Error %d: %s" % (e.args[0], e.args[1]) </code></pre> <p>Clearly I could do it by having another attempt in the except clause, but that's incredibly ugly, and I have a feeling there must be a decent way to achieve this.</p>
59
2009-02-19T22:52:01Z
14,279,634
<p>This is my generic solution:</p> <pre><code>class TryTimes(object): ''' A context-managed coroutine that returns True until a number of tries have been reached. ''' def __init__(self, times): ''' times: Number of retries before failing. ''' self.times = times self.count = 0 def __next__(self): ''' A generator expression that counts up to times. ''' while self.count &lt; self.times: self.count += 1 yield False def __call__(self, *args, **kwargs): ''' This allows "o() calls for "o = TryTimes(3)". ''' return self.__next__().next() def __enter__(self): ''' Context manager entry, bound to t in "with TryTimes(3) as t" ''' return self def __exit__(self, exc_type, exc_val, exc_tb): ''' Context manager exit. ''' return False # don't suppress exception </code></pre> <p>This allows code like the following:</p> <pre><code>with TryTimes(3) as t: while t(): print "Your code to try several times" </code></pre> <p>Also possible:</p> <pre><code>t = TryTimes(3) while t(): print "Your code to try several times" </code></pre> <p>This can be improved by handling exceptions in a more intuitive way, I hope. Open to suggestions.</p>
0
2013-01-11T13:57:07Z
[ "python", "exception-handling" ]
is there a pythonic way to try something up to a maximum number of times?
567,622
<p>I have a python script which is querying a MySQL server on a shared linux host. For some reason, queries to MySQL often return a "server has gone away" error:</p> <pre><code>_mysql_exceptions.OperationalError: (2006, 'MySQL server has gone away') </code></pre> <p>If you try the query again immediately afterwards, it usually succeeds. So, I'd like to know if there's a sensible way in python to try to execute a query, and if it fails, to try again, up to a fixed number of tries. Probably I'd want it to try 5 times before giving up altogether.</p> <p>Here's the kind of code I have:</p> <pre><code>conn = MySQLdb.connect(host, user, password, database) cursor = conn.cursor() try: cursor.execute(query) rows = cursor.fetchall() for row in rows: # do something with the data except MySQLdb.Error, e: print "MySQL Error %d: %s" % (e.args[0], e.args[1]) </code></pre> <p>Clearly I could do it by having another attempt in the except clause, but that's incredibly ugly, and I have a feeling there must be a decent way to achieve this.</p>
59
2009-02-19T22:52:01Z
29,299,362
<pre><code>def successful_transaction(transaction): try: transaction() return True except SQL...: return False succeeded = any(successful_transaction(transaction) for transaction in repeat(transaction, 3)) </code></pre>
0
2015-03-27T11:12:03Z
[ "python", "exception-handling" ]
is there a pythonic way to try something up to a maximum number of times?
567,622
<p>I have a python script which is querying a MySQL server on a shared linux host. For some reason, queries to MySQL often return a "server has gone away" error:</p> <pre><code>_mysql_exceptions.OperationalError: (2006, 'MySQL server has gone away') </code></pre> <p>If you try the query again immediately afterwards, it usually succeeds. So, I'd like to know if there's a sensible way in python to try to execute a query, and if it fails, to try again, up to a fixed number of tries. Probably I'd want it to try 5 times before giving up altogether.</p> <p>Here's the kind of code I have:</p> <pre><code>conn = MySQLdb.connect(host, user, password, database) cursor = conn.cursor() try: cursor.execute(query) rows = cursor.fetchall() for row in rows: # do something with the data except MySQLdb.Error, e: print "MySQL Error %d: %s" % (e.args[0], e.args[1]) </code></pre> <p>Clearly I could do it by having another attempt in the except clause, but that's incredibly ugly, and I have a feeling there must be a decent way to achieve this.</p>
59
2009-02-19T22:52:01Z
31,003,926
<p>Yes, there is the <a href="https://pypi.python.org/pypi/retrying" rel="nofollow">retrying library</a>, which has a decorator that implements several kinds of retrying logic that you can combine:</p> <p>Some examples:</p> <pre><code>@retry(stop_max_attempt_number=7) def stop_after_7_attempts(): print "Stopping after 7 attempts" @retry(wait_fixed=2000) def wait_2_s(): print "Wait 2 second between retries" @retry(wait_exponential_multiplier=1000, wait_exponential_max=10000) def wait_exponential_1000(): print "Wait 2^x * 1000 milliseconds between each retry," print "up to 10 seconds, then 10 seconds afterwards" </code></pre>
4
2015-06-23T13:19:32Z
[ "python", "exception-handling" ]
is there a pythonic way to try something up to a maximum number of times?
567,622
<p>I have a python script which is querying a MySQL server on a shared linux host. For some reason, queries to MySQL often return a "server has gone away" error:</p> <pre><code>_mysql_exceptions.OperationalError: (2006, 'MySQL server has gone away') </code></pre> <p>If you try the query again immediately afterwards, it usually succeeds. So, I'd like to know if there's a sensible way in python to try to execute a query, and if it fails, to try again, up to a fixed number of tries. Probably I'd want it to try 5 times before giving up altogether.</p> <p>Here's the kind of code I have:</p> <pre><code>conn = MySQLdb.connect(host, user, password, database) cursor = conn.cursor() try: cursor.execute(query) rows = cursor.fetchall() for row in rows: # do something with the data except MySQLdb.Error, e: print "MySQL Error %d: %s" % (e.args[0], e.args[1]) </code></pre> <p>Clearly I could do it by having another attempt in the except clause, but that's incredibly ugly, and I have a feeling there must be a decent way to achieve this.</p>
59
2009-02-19T22:52:01Z
34,079,995
<p>1.Definition:</p> <pre><code>def try_three_times(express): att = 0 while att &lt; 3: try: return express() except: att += 1 else: return u"FAILED" </code></pre> <p>2.Usage:</p> <pre><code>try_three_times(lambda: do_some_function_or_express()) </code></pre> <p>I use it for parse html context.</p>
1
2015-12-04T02:36:31Z
[ "python", "exception-handling" ]
How can I process command line arguments in Python?
567,879
<p>What would be an easy expression to process command line arguments if I'm expecting anything like 001 or 999 (let's limit expectations to 001...999 range for this time), and few other arguments passed, and would like to ignore any unexpected?</p> <p>I understand if for example I need to find out if "debug" was passed among parameters it'll be something like that:</p> <pre><code>if 'debug' in argv[1:]: print 'Will be running in debug mode.' </code></pre> <p>How to find out if 009 or 575 was passed?</p> <p>All those are expected calls:</p> <pre><code>python script.py python script.py 011 python script.py 256 debug python script.py 391 xls python script.py 999 debug pdf </code></pre> <p>At this point I don't care about calls like that:</p> <pre><code>python script.py 001 002 245 568 python script.py some unexpected argument python script.py 0001 python script.py 02 </code></pre> <p>...first one - because of more than one "numeric" argument; second - because of... well, unexpected arguments; third and fourth - because of non-3-digits arguments.</p>
18
2009-02-20T00:41:02Z
567,899
<p>Have a look at the <a href="http://docs.python.org/library/optparse.html" rel="nofollow">optparse</a> module. Dealing with sys.argv yourself is fine for really simple stuff, but it gets out of hand quickly.</p> <p>Note that you may find optparse easier to use if you can change your argument format a little; e.g. replace <code>debug</code> with <code>--debug</code> and <code>xls</code> with <code>--xls</code> or <code>--output=xls</code>.</p>
15
2009-02-20T00:51:36Z
[ "python", "command-line", "command-line-arguments" ]
How can I process command line arguments in Python?
567,879
<p>What would be an easy expression to process command line arguments if I'm expecting anything like 001 or 999 (let's limit expectations to 001...999 range for this time), and few other arguments passed, and would like to ignore any unexpected?</p> <p>I understand if for example I need to find out if "debug" was passed among parameters it'll be something like that:</p> <pre><code>if 'debug' in argv[1:]: print 'Will be running in debug mode.' </code></pre> <p>How to find out if 009 or 575 was passed?</p> <p>All those are expected calls:</p> <pre><code>python script.py python script.py 011 python script.py 256 debug python script.py 391 xls python script.py 999 debug pdf </code></pre> <p>At this point I don't care about calls like that:</p> <pre><code>python script.py 001 002 245 568 python script.py some unexpected argument python script.py 0001 python script.py 02 </code></pre> <p>...first one - because of more than one "numeric" argument; second - because of... well, unexpected arguments; third and fourth - because of non-3-digits arguments.</p>
18
2009-02-20T00:41:02Z
567,907
<p><a href="http://docs.python.org/library/optparse.html" rel="nofollow">optparse</a> is your best friend for parsing the command line. Also look into <a href="http://argparse.python-hosting.com/" rel="nofollow">argparse</a>; it's not in the standard library, though.</p>
2
2009-02-20T00:54:06Z
[ "python", "command-line", "command-line-arguments" ]
How can I process command line arguments in Python?
567,879
<p>What would be an easy expression to process command line arguments if I'm expecting anything like 001 or 999 (let's limit expectations to 001...999 range for this time), and few other arguments passed, and would like to ignore any unexpected?</p> <p>I understand if for example I need to find out if "debug" was passed among parameters it'll be something like that:</p> <pre><code>if 'debug' in argv[1:]: print 'Will be running in debug mode.' </code></pre> <p>How to find out if 009 or 575 was passed?</p> <p>All those are expected calls:</p> <pre><code>python script.py python script.py 011 python script.py 256 debug python script.py 391 xls python script.py 999 debug pdf </code></pre> <p>At this point I don't care about calls like that:</p> <pre><code>python script.py 001 002 245 568 python script.py some unexpected argument python script.py 0001 python script.py 02 </code></pre> <p>...first one - because of more than one "numeric" argument; second - because of... well, unexpected arguments; third and fourth - because of non-3-digits arguments.</p>
18
2009-02-20T00:41:02Z
567,923
<p>As others answered, optparse is the best option, but if you just want quick code try something like this:</p> <pre><code>import sys, re first_re = re.compile(r'^\d{3}$') if len(sys.argv) &gt; 1: if first_re.match(sys.argv[1]): print "Primary argument is : ", sys.argv[1] else: raise ValueError("First argument should be ...") args = sys.argv[2:] else: args = () # ... anywhere in code ... if 'debug' in args: print 'debug flag' if 'xls' in args: print 'xls flag' </code></pre> <p><strong>EDIT</strong>: Here's an optparse example because so many people are answering optparse without really explaining why, or explaining what you have to change to make it work.</p> <p>The primary reason to use optparse is it gives you more flexibility for expansion later, and gives you more flexibility on the command line. In other words, your options can appear in any order and usage messages are generated automatically. However to make it work with optparse you need to change your specifications to put '-' or '--' in front of the optional arguments and you need to allow all the arguments to be in any order.</p> <p>So here's an example using optparse:</p> <pre><code>import sys, re, optparse first_re = re.compile(r'^\d{3}$') parser = optparse.OptionParser() parser.set_defaults(debug=False,xls=False) parser.add_option('--debug', action='store_true', dest='debug') parser.add_option('--xls', action='store_true', dest='xls') (options, args) = parser.parse_args() if len(args) == 1: if first_re.match(args[0]): print "Primary argument is : ", args[0] else: raise ValueError("First argument should be ...") elif len(args) &gt; 1: raise ValueError("Too many command line arguments") if options.debug: print 'debug flag' if options.xls: print 'xls flag' </code></pre> <p>The differences here with optparse and your spec is that now you can have command lines like:</p> <pre><code>python script.py --debug --xls 001 </code></pre> <p>and you can easily add new options by calling parser.add_option()</p>
25
2009-02-20T01:02:40Z
[ "python", "command-line", "command-line-arguments" ]
How can I process command line arguments in Python?
567,879
<p>What would be an easy expression to process command line arguments if I'm expecting anything like 001 or 999 (let's limit expectations to 001...999 range for this time), and few other arguments passed, and would like to ignore any unexpected?</p> <p>I understand if for example I need to find out if "debug" was passed among parameters it'll be something like that:</p> <pre><code>if 'debug' in argv[1:]: print 'Will be running in debug mode.' </code></pre> <p>How to find out if 009 or 575 was passed?</p> <p>All those are expected calls:</p> <pre><code>python script.py python script.py 011 python script.py 256 debug python script.py 391 xls python script.py 999 debug pdf </code></pre> <p>At this point I don't care about calls like that:</p> <pre><code>python script.py 001 002 245 568 python script.py some unexpected argument python script.py 0001 python script.py 02 </code></pre> <p>...first one - because of more than one "numeric" argument; second - because of... well, unexpected arguments; third and fourth - because of non-3-digits arguments.</p>
18
2009-02-20T00:41:02Z
568,003
<p>If you want to implement actual command line switches, give <a href="http://docs.python.org/library/getopt.html" rel="nofollow">getopt</a> a look. It's incredibly simple to use, too.</p>
2
2009-02-20T01:55:06Z
[ "python", "command-line", "command-line-arguments" ]
How can I process command line arguments in Python?
567,879
<p>What would be an easy expression to process command line arguments if I'm expecting anything like 001 or 999 (let's limit expectations to 001...999 range for this time), and few other arguments passed, and would like to ignore any unexpected?</p> <p>I understand if for example I need to find out if "debug" was passed among parameters it'll be something like that:</p> <pre><code>if 'debug' in argv[1:]: print 'Will be running in debug mode.' </code></pre> <p>How to find out if 009 or 575 was passed?</p> <p>All those are expected calls:</p> <pre><code>python script.py python script.py 011 python script.py 256 debug python script.py 391 xls python script.py 999 debug pdf </code></pre> <p>At this point I don't care about calls like that:</p> <pre><code>python script.py 001 002 245 568 python script.py some unexpected argument python script.py 0001 python script.py 02 </code></pre> <p>...first one - because of more than one "numeric" argument; second - because of... well, unexpected arguments; third and fourth - because of non-3-digits arguments.</p>
18
2009-02-20T00:41:02Z
568,339
<p>Van Gale is largely correct in using the regular expression against the argument. However, it is NOT absolutely necessary to make everything an option when using optparse, which splits sys.argv into options and arguments, based on whether a "-" or "--" is in front or not. Some example code to go through just the arguments:</p> <pre><code>import sys import optparse claParser = optparse.OptionParser() claParser.add_option( (opts, args) = claParser.parse_args() if (len(args) &gt;= 1): print "Arguments:" for arg in args: print " " + arg else: print "No arguments" sys.exit(0) </code></pre> <p>Yes, the args array is parsed much the same way as sys.argv would be, but the ability to easily add options if needed has been added. For more about optparse, check out the <a href="http://docs.python.org/library/optparse.html" rel="nofollow">relevant Python doc</a>.</p>
0
2009-02-20T05:02:44Z
[ "python", "command-line", "command-line-arguments" ]
Preventing BeautifulSoup from converting my XML tags to lowercase
567,999
<p>I am using BeautifulStoneSoup to parse an XML document and change some attributes. I noticed that it automatically converts all XML tags to lowercase. For example, my source file has <code>&lt;DocData&gt;</code> elements, which BeautifulSoup converts to <code>&lt;docdata&gt;</code>. This appears to be causing problems since the program I am feeding my modified XML document to does not seem to accept the lowercase versions. Is there a way to prevent this behavior in BeautifulSoup?</p>
7
2009-02-20T01:52:26Z
568,081
<p>No, that's not a built-in option. The source is pretty straightforward, though. It looks like you want to change the value of encodedName in Tag.<code>__str__.</code></p>
3
2009-02-20T02:37:40Z
[ "python", "xml", "beautifulsoup" ]
Flexible, Solid and Portable Service Discovery
568,028
<p>I am looking for a way for clients in a LAN to find all the instances of my server application without any configuration. Instead of hacking something myself, I'd like to use an existing solution. Personally, I need it to be done in Python, but I'd happy to hear about solutions in any other language.</p> <p>So why am I not using <a href="http://avahi.org/" rel="nofollow">avahi</a> or <a href="http://www.openslp.org/" rel="nofollow">OpenSLP</a> or some other <a href="http://en.wikipedia.org/wiki/Zeroconf#Service_discovery" rel="nofollow">Zeroconf</a>/<a href="http://tools.ietf.org/html/rfc2608" rel="nofollow">SLP</a> solution? Well, there are a couple of additional criteria, and I'm under the impression neither of the aforementioned systems matches them.</p> <p>I'm looking for a solution that is:</p> <ul> <li><strong>Flexible</strong>. It must not require superuser rights, i.e. only use ports>1024. </li> <li><strong>Solid</strong>. It must allow multiple services of the same and different service type on a single machine and continue advertising the services even when the instance that started the advertisement server stops or crashes.</li> <li><strong>Portable</strong>. It must run nearly everywhere, or at least on *BSD, Debian/gentoo/RedHat/SuSe Linux, Mac OS X, Solaris and Windows NT.</li> <li><strong>Light</strong>. Ideally, one Python script would be the whole solution. I'm not in the least interested in address autoconfiguration or something like that, although I'd begrudgingly accept a solution that has lots of features I don't need. Furthermore, any one-time setup is a strict no-no.</li> </ul> <p>I expect something like this:</p> <pre><code>def registerService(service): # (type, port) if listen(multicast, someport): if fork() == child: services = [service] for q in queriesToMe(): if q == DISCOVERY: answer(filter(q.criteria, services)) elif q == ADVERTISE and q.sender == "localhost": services.append(q.service) else: advertiseAt("localhost", service) </code></pre>
4
2009-02-20T02:08:38Z
568,549
<p>I assume you have control over the client apps, not just the server app, in which case <a href="http://pyro.sourceforge.net/" rel="nofollow">Pyro</a> might work well for you.</p> <p><strong>Flexible:</strong> uses non privileged ports.</p> <p><strong>Solid:</strong> It has been well maintained for many years.</p> <p><strong>Portable:</strong> pure Python and well tested on multiple platforms.</p> <p><strong>Light:</strong> I think Pyro is light for what you're getting. Maybe asking for one Python script is unrealistic for a network naming service?</p> <p>Even if you don't want to actually use the "remote object" paradigm of Pyro, you still might be able to just use its naming service.</p>
1
2009-02-20T06:43:55Z
[ "python", "language-agnostic", "service-discovery" ]
Flexible, Solid and Portable Service Discovery
568,028
<p>I am looking for a way for clients in a LAN to find all the instances of my server application without any configuration. Instead of hacking something myself, I'd like to use an existing solution. Personally, I need it to be done in Python, but I'd happy to hear about solutions in any other language.</p> <p>So why am I not using <a href="http://avahi.org/" rel="nofollow">avahi</a> or <a href="http://www.openslp.org/" rel="nofollow">OpenSLP</a> or some other <a href="http://en.wikipedia.org/wiki/Zeroconf#Service_discovery" rel="nofollow">Zeroconf</a>/<a href="http://tools.ietf.org/html/rfc2608" rel="nofollow">SLP</a> solution? Well, there are a couple of additional criteria, and I'm under the impression neither of the aforementioned systems matches them.</p> <p>I'm looking for a solution that is:</p> <ul> <li><strong>Flexible</strong>. It must not require superuser rights, i.e. only use ports>1024. </li> <li><strong>Solid</strong>. It must allow multiple services of the same and different service type on a single machine and continue advertising the services even when the instance that started the advertisement server stops or crashes.</li> <li><strong>Portable</strong>. It must run nearly everywhere, or at least on *BSD, Debian/gentoo/RedHat/SuSe Linux, Mac OS X, Solaris and Windows NT.</li> <li><strong>Light</strong>. Ideally, one Python script would be the whole solution. I'm not in the least interested in address autoconfiguration or something like that, although I'd begrudgingly accept a solution that has lots of features I don't need. Furthermore, any one-time setup is a strict no-no.</li> </ul> <p>I expect something like this:</p> <pre><code>def registerService(service): # (type, port) if listen(multicast, someport): if fork() == child: services = [service] for q in queriesToMe(): if q == DISCOVERY: answer(filter(q.criteria, services)) elif q == ADVERTISE and q.sender == "localhost": services.append(q.service) else: advertiseAt("localhost", service) </code></pre>
4
2009-02-20T02:08:38Z
655,429
<p>I wrote an application/library (currently Python and CLI interface) that matches all these critera. It's called <a href="http://code.google.com/p/minusconf/" rel="nofollow">minusconf</a>. Turns out forking is not even necessary.</p>
3
2009-03-17T18:09:38Z
[ "python", "language-agnostic", "service-discovery" ]
Flexible, Solid and Portable Service Discovery
568,028
<p>I am looking for a way for clients in a LAN to find all the instances of my server application without any configuration. Instead of hacking something myself, I'd like to use an existing solution. Personally, I need it to be done in Python, but I'd happy to hear about solutions in any other language.</p> <p>So why am I not using <a href="http://avahi.org/" rel="nofollow">avahi</a> or <a href="http://www.openslp.org/" rel="nofollow">OpenSLP</a> or some other <a href="http://en.wikipedia.org/wiki/Zeroconf#Service_discovery" rel="nofollow">Zeroconf</a>/<a href="http://tools.ietf.org/html/rfc2608" rel="nofollow">SLP</a> solution? Well, there are a couple of additional criteria, and I'm under the impression neither of the aforementioned systems matches them.</p> <p>I'm looking for a solution that is:</p> <ul> <li><strong>Flexible</strong>. It must not require superuser rights, i.e. only use ports>1024. </li> <li><strong>Solid</strong>. It must allow multiple services of the same and different service type on a single machine and continue advertising the services even when the instance that started the advertisement server stops or crashes.</li> <li><strong>Portable</strong>. It must run nearly everywhere, or at least on *BSD, Debian/gentoo/RedHat/SuSe Linux, Mac OS X, Solaris and Windows NT.</li> <li><strong>Light</strong>. Ideally, one Python script would be the whole solution. I'm not in the least interested in address autoconfiguration or something like that, although I'd begrudgingly accept a solution that has lots of features I don't need. Furthermore, any one-time setup is a strict no-no.</li> </ul> <p>I expect something like this:</p> <pre><code>def registerService(service): # (type, port) if listen(multicast, someport): if fork() == child: services = [service] for q in queriesToMe(): if q == DISCOVERY: answer(filter(q.criteria, services)) elif q == ADVERTISE and q.sender == "localhost": services.append(q.service) else: advertiseAt("localhost", service) </code></pre>
4
2009-02-20T02:08:38Z
18,213,927
<p>For node discovery in a LAN I've used Twisted and UDP Multicast. Hope it helps you too.</p> <p>Link to the twisted documentation that explains how to do it: <a href="https://twistedmatrix.com/documents/current/core/howto/udp.html#auto3" rel="nofollow">https://twistedmatrix.com/documents/current/core/howto/udp.html#auto3</a></p> <p>Here is a basic implementation of a server/client based in the twisted's code. It answers itself if you run once, but all the checking code and extra features were removed in order to make it simpler to read.</p> <pre><code>from twisted.internet.protocol import DatagramProtocol from twisted.internet import reactor class MulticastPingPong(DatagramProtocol): MULTICAST_ADDR = ('228.0.0.5', 8005) CMD_PING = "PING" CMD_PONG = "PONG" def startProtocol(self): """ Called after protocol has started listening. """ # Set the TTL&gt;1 so multicast will cross router hops: self.transport.setTTL(5) # Join a specific multicast group: self.transport.joinGroup(self.MULTICAST_ADDR[0]) self.send_alive() def send_alive(self): """ Sends a multicast signal asking for clients. The receivers will reply if they want to be found. """ self.transport.write(self.CMD_PING, self.MULTICAST_ADDR) def datagramReceived(self, datagram, address): print "Datagram %s received from %s" % (repr(datagram), repr(address)) if datagram.startswith(self.CMD_PING): # someone publishes itself, we reply that we are here self.transport.write(self.CMD_PONG, address) elif datagram.startswith(self.CMD_PONG): # someone reply to our publish message print "Got client: ", address[0], address[1] if __name__ == '__main__': reactor.listenMulticast(8005, MulticastPingPong(), listenMultiple=True) reactor.run() </code></pre>
2
2013-08-13T16:02:32Z
[ "python", "language-agnostic", "service-discovery" ]
pycurl fails but curl (from bash) works in ubuntu
568,247
<p>I'm using curl and pycurl to connect to a secure 3rd party api and when I use pycurl I'm getting authentication errors back from the server, but when I use curl on the command line and do the same thing it works. I set both to verbose mode and am seeing some differences in the request, but I can't seem to figure out what the error is.</p> <p>They seem to be using different encryption methods, perhaps that is the problem? If anyone has ideas on different options to try with pycurl or suggestions for recompiling pycurl to work like curl, that would be awesome. Thanks.</p> <p>Here are my pycurl settings, fyi:</p> <pre><code> buffer = cStringIO.StringIO() curl = pycurl.Curl() curl.setopt(pycurl.VERBOSE,1) curl.setopt(pycurl.POST, 1) curl.setopt(pycurl.POSTFIELDS, post_data) curl.setopt(pycurl.TIMEOUT_MS, self.HTTP_TIMEOUT) curl.setopt(pycurl.URL, url) curl.setopt(pycurl.FOLLOWLOCATION, self.HTTP_FOLLOW_REDIRECTS) curl.setopt(pycurl.MAXREDIRS, self.HTTP_MAX_REDIRECTS) curl.setopt(pycurl.WRITEFUNCTION, buffer.write) curl.setopt(pycurl.NOSIGNAL, 1) curl.setopt(pycurl.SSLCERT, self.path_to_ssl_cert) curl.setopt(pycurl.SSL_VERIFYPEER, 0) # 1/0 try: curl.perform() </code></pre> <p>...</p> <p>Oh, last thing: the same python script I'm using works on my Mac laptop but doesn't work on the ubuntu server I'm trying to setup.</p> <pre><code>python test.py 18:09:13,299 root INFO fetching: https://secure..... * About to connect() to secure.... 1129 (#0) * Trying 216....... * connected * Connected to secure.... port 1129 (#0) * found 102 certificates in /etc/ssl/certs/ca-certificates.crt * server certificate verification OK * common name: secure.... (matched) * server certificate expiration date OK * server certificate activation date OK * certificate public key: RSA * certificate version: #3 * subject: ....... * start date: Sat, 14 Feb 2009 22:45:27 GMT * expire date: Mon, 15 Feb 2010 22:45:27 GMT * issuer: ... * compression: NULL * cipher: AES 128 CBC * MAC: SHA User-Agent: PycURL/7.16.4 Host: secure.... Accept: */* Content-Length: 387 Content-Type: application/x-www-form-urlencoded &lt; HTTP/1.1 200 OK &lt; Content-Length: 291 &lt; * Connection #0 to host secure.... left intact * Closing connection #0 curl -v -d '...' --cert cert.pem https://secure.... * About to connect() to secure.... port 1129 (#0) * Trying 216....... connected * Connected to secure.... port 1129 (#0) * successfully set certificate verify locations: * CAfile: /etc/ssl/certs/ca-certificates.crt CApath: none * SSLv2, Client hello (1): * SSLv3, TLS handshake, Server hello (2): * SSLv3, TLS handshake, CERT (11): * SSLv3, TLS handshake, Request CERT (13): * SSLv3, TLS handshake, Server finished (14): * SSLv3, TLS handshake, CERT (11): * SSLv3, TLS handshake, Client key exchange (16): * SSLv3, TLS handshake, CERT verify (15): * SSLv3, TLS change cipher, Client hello (1): * SSLv3, TLS handshake, Finished (20): * SSLv3, TLS change cipher, Client hello (1): * SSLv3, TLS handshake, Finished (20): * SSL connection using AES256-SHA * Server certificate: * subject: ....... * start date: 2009-02-14 22:45:27 GMT * expire date: 2010-02-15 22:45:27 GMT * common name: secure.... (matched) * issuer: ... Certificate Authority * SSL certificate verify ok. &gt; User-Agent: curl/7.16.4 (i486-pc-linux-gnu) libcurl/7.16.4 OpenSSL/0.9.8e zlib/1.2.3.3 libidn/1.0 &gt; Host: secure....:1129 &gt; Accept: */* &gt; Content-Length: 387 &gt; Content-Type: application/x-www-form-urlencoded &gt; &lt; HTTP/1.1 200 OK &lt; Content-Length: 342 </code></pre>
3
2009-02-20T04:07:39Z
601,879
<p>I have a little trouble understanding the code/output fragments you have posted. Is the actual error message included?</p> <p>Problems with SSL/TLS are often because of the X.509 certificate infrastructure. There are "Certificate Authorities" (CA) like Verisign, RapidSSL etc. which digitally "sign" the certificates of servers. To check these signatures, you need the so called "root certificate" of the CA who signed the certificate of the server ("issuer") you are connecting to.</p> <p>Usually operating systems come with a fair amount of certificates pre-installed. And often Browsers, the OS and certain libraries all have their own list of certificates. On a Mac you can see them, if you start the program "Keychain Access" and open the "System Roots" keychain.</p> <p>So I suggest you check if the cert is missing from Ubuntu and if so to add it there. (Maybe that is all saved in /etc/ssl/certs/)</p>
1
2009-03-02T10:27:04Z
[ "python", "ssl", "curl", "https", "pycurl" ]
pycurl fails but curl (from bash) works in ubuntu
568,247
<p>I'm using curl and pycurl to connect to a secure 3rd party api and when I use pycurl I'm getting authentication errors back from the server, but when I use curl on the command line and do the same thing it works. I set both to verbose mode and am seeing some differences in the request, but I can't seem to figure out what the error is.</p> <p>They seem to be using different encryption methods, perhaps that is the problem? If anyone has ideas on different options to try with pycurl or suggestions for recompiling pycurl to work like curl, that would be awesome. Thanks.</p> <p>Here are my pycurl settings, fyi:</p> <pre><code> buffer = cStringIO.StringIO() curl = pycurl.Curl() curl.setopt(pycurl.VERBOSE,1) curl.setopt(pycurl.POST, 1) curl.setopt(pycurl.POSTFIELDS, post_data) curl.setopt(pycurl.TIMEOUT_MS, self.HTTP_TIMEOUT) curl.setopt(pycurl.URL, url) curl.setopt(pycurl.FOLLOWLOCATION, self.HTTP_FOLLOW_REDIRECTS) curl.setopt(pycurl.MAXREDIRS, self.HTTP_MAX_REDIRECTS) curl.setopt(pycurl.WRITEFUNCTION, buffer.write) curl.setopt(pycurl.NOSIGNAL, 1) curl.setopt(pycurl.SSLCERT, self.path_to_ssl_cert) curl.setopt(pycurl.SSL_VERIFYPEER, 0) # 1/0 try: curl.perform() </code></pre> <p>...</p> <p>Oh, last thing: the same python script I'm using works on my Mac laptop but doesn't work on the ubuntu server I'm trying to setup.</p> <pre><code>python test.py 18:09:13,299 root INFO fetching: https://secure..... * About to connect() to secure.... 1129 (#0) * Trying 216....... * connected * Connected to secure.... port 1129 (#0) * found 102 certificates in /etc/ssl/certs/ca-certificates.crt * server certificate verification OK * common name: secure.... (matched) * server certificate expiration date OK * server certificate activation date OK * certificate public key: RSA * certificate version: #3 * subject: ....... * start date: Sat, 14 Feb 2009 22:45:27 GMT * expire date: Mon, 15 Feb 2010 22:45:27 GMT * issuer: ... * compression: NULL * cipher: AES 128 CBC * MAC: SHA User-Agent: PycURL/7.16.4 Host: secure.... Accept: */* Content-Length: 387 Content-Type: application/x-www-form-urlencoded &lt; HTTP/1.1 200 OK &lt; Content-Length: 291 &lt; * Connection #0 to host secure.... left intact * Closing connection #0 curl -v -d '...' --cert cert.pem https://secure.... * About to connect() to secure.... port 1129 (#0) * Trying 216....... connected * Connected to secure.... port 1129 (#0) * successfully set certificate verify locations: * CAfile: /etc/ssl/certs/ca-certificates.crt CApath: none * SSLv2, Client hello (1): * SSLv3, TLS handshake, Server hello (2): * SSLv3, TLS handshake, CERT (11): * SSLv3, TLS handshake, Request CERT (13): * SSLv3, TLS handshake, Server finished (14): * SSLv3, TLS handshake, CERT (11): * SSLv3, TLS handshake, Client key exchange (16): * SSLv3, TLS handshake, CERT verify (15): * SSLv3, TLS change cipher, Client hello (1): * SSLv3, TLS handshake, Finished (20): * SSLv3, TLS change cipher, Client hello (1): * SSLv3, TLS handshake, Finished (20): * SSL connection using AES256-SHA * Server certificate: * subject: ....... * start date: 2009-02-14 22:45:27 GMT * expire date: 2010-02-15 22:45:27 GMT * common name: secure.... (matched) * issuer: ... Certificate Authority * SSL certificate verify ok. &gt; User-Agent: curl/7.16.4 (i486-pc-linux-gnu) libcurl/7.16.4 OpenSSL/0.9.8e zlib/1.2.3.3 libidn/1.0 &gt; Host: secure....:1129 &gt; Accept: */* &gt; Content-Length: 387 &gt; Content-Type: application/x-www-form-urlencoded &gt; &lt; HTTP/1.1 200 OK &lt; Content-Length: 342 </code></pre>
3
2009-02-20T04:07:39Z
1,441,046
<p>Ubuntu pycurl uses GnuTLS while ubuntu curl command line uses OpenSSL. There are differences e.g. in supported certificate formats.</p> <p>I for one cannot comprehend this decision taken by ubuntu devs/packagers. I stumbled on this once and could not work around it, luckily there are other distributions than ubuntu :-)</p> <p>You could always try to complain to "humanity towards others."</p>
3
2009-09-17T20:03:38Z
[ "python", "ssl", "curl", "https", "pycurl" ]
How to check if there exists a process with a given pid?
568,271
<p>Is there a way to check to see if a pid corresponds to a valid process? I'm getting a pid from a different source other than from <code>os.getpid()</code> and I need to check to see if a process with that pid doesn't exist on the machine. </p> <p>I need it to be available in Unix and Windows. I'm also checking to see if the PID is NOT in use.</p>
53
2009-02-20T04:22:43Z
568,285
<p>Sending signal 0 to a pid will raise an OSError exception if the pid is not running, and do nothing otherwise.</p> <pre><code>import os def check_pid(pid): """ Check For the existence of a unix pid. """ try: os.kill(pid, 0) except OSError: return False else: return True </code></pre>
90
2009-02-20T04:31:14Z
[ "python", "process", "pid" ]
How to check if there exists a process with a given pid?
568,271
<p>Is there a way to check to see if a pid corresponds to a valid process? I'm getting a pid from a different source other than from <code>os.getpid()</code> and I need to check to see if a process with that pid doesn't exist on the machine. </p> <p>I need it to be available in Unix and Windows. I'm also checking to see if the PID is NOT in use.</p>
53
2009-02-20T04:22:43Z
568,589
<p>Look <a href="http://mail.python.org/pipermail/python-win32/2003-December/001482.html">here</a> for windows-specific way of getting full list of running processes with their IDs. It would be something like</p> <pre><code>from win32com.client import GetObject def get_proclist(): WMI = GetObject('winmgmts:') processes = WMI.InstancesOf('Win32_Process') return [process.Properties_('ProcessID').Value for process in processes] </code></pre> <p>You can then verify pid you get against this list. I have no idea about performance cost, so you'd better check this if you're going to do pid verification often.</p> <p>For *NIx, just use mluebke's solution.</p>
6
2009-02-20T07:20:11Z
[ "python", "process", "pid" ]
How to check if there exists a process with a given pid?
568,271
<p>Is there a way to check to see if a pid corresponds to a valid process? I'm getting a pid from a different source other than from <code>os.getpid()</code> and I need to check to see if a process with that pid doesn't exist on the machine. </p> <p>I need it to be available in Unix and Windows. I'm also checking to see if the PID is NOT in use.</p>
53
2009-02-20T04:22:43Z
568,614
<p>I'd say use the PID for whatever purpose you're obtaining it and handle the errors gracefully. Otherwise, it's a classic race (the PID may be valid when you check it's valid, but go away an instant later)</p>
0
2009-02-20T07:39:21Z
[ "python", "process", "pid" ]
How to check if there exists a process with a given pid?
568,271
<p>Is there a way to check to see if a pid corresponds to a valid process? I'm getting a pid from a different source other than from <code>os.getpid()</code> and I need to check to see if a process with that pid doesn't exist on the machine. </p> <p>I need it to be available in Unix and Windows. I'm also checking to see if the PID is NOT in use.</p>
53
2009-02-20T04:22:43Z
6,940,314
<p>mluebke code is not 100% correct; kill() can also raise EPERM (access denied) in which case that obviously means a process exists. This is supposed to work:</p> <p>(edited as per Jason R. Coombs comments)</p> <pre><code>import errno import os import sys def pid_exists(pid): """Check whether pid exists in the current process table. UNIX only. """ if pid &lt; 0: return False if pid == 0: # According to "man 2 kill" PID 0 refers to every process # in the process group of the calling process. # On certain systems 0 is a valid PID but we have no way # to know that in a portable fashion. raise ValueError('invalid PID 0') try: os.kill(pid, 0) except OSError as err: if err.errno == errno.ESRCH: # ESRCH == No such process return False elif err.errno == errno.EPERM: # EPERM clearly means there's a process to deny access to return True else: # According to "man 2 kill" possible error values are # (EINVAL, EPERM, ESRCH) raise else: return True </code></pre> <p>You can't do this on Windows unless you use pywin32, ctypes or a C extension module. If you're OK with depending from an external lib you can use <a href="https://github.com/giampaolo/psutil">psutil</a>:</p> <pre><code>&gt;&gt;&gt; import psutil &gt;&gt;&gt; psutil.pid_exists(2353) True </code></pre>
38
2011-08-04T11:08:51Z
[ "python", "process", "pid" ]
How to check if there exists a process with a given pid?
568,271
<p>Is there a way to check to see if a pid corresponds to a valid process? I'm getting a pid from a different source other than from <code>os.getpid()</code> and I need to check to see if a process with that pid doesn't exist on the machine. </p> <p>I need it to be available in Unix and Windows. I'm also checking to see if the PID is NOT in use.</p>
53
2009-02-20T04:22:43Z
17,622,447
<p>Have a look at the <a href="https://pypi.python.org/pypi/psutil"><code>psutil</code></a> module: </p> <blockquote> <p><strong>psutil</strong> (python system and process utilities) is a cross-platform library for retrieving information on <strong>running processes</strong> and <strong>system utilization</strong> (CPU, memory, disks, network) in Python. [...] It currently supports <strong>Linux</strong>, <strong>Windows</strong>, <strong>OSX</strong>, <strong>FreeBSD</strong> and <strong>Sun Solaris</strong>, both <strong>32-bit</strong> and <strong>64-bit</strong> architectures, with Python versions from <strong>2.6 to 3.4</strong> (users of Python 2.4 and 2.5 may use 2.1.3 version). PyPy is also known to work.</p> </blockquote> <p>It has a function called <code>pid_exists()</code> that you can use to check whether a process with the given pid exists.</p> <p>Here's an example:</p> <pre><code>import psutil pid = 12345 if psutil.pid_exists(pid): print "a process with pid %d exists" % pid else: print "a process with pid %d does not exist" % pid </code></pre> <p>For reference:</p> <ul> <li><a href="https://pypi.python.org/pypi/psutil">https://pypi.python.org/pypi/psutil</a></li> <li><a href="https://github.com/giampaolo/psutil">https://github.com/giampaolo/psutil</a></li> <li><a href="http://pythonhosted.org/psutil/#psutil.pid_exists">http://pythonhosted.org/psutil/#psutil.pid_exists</a></li> </ul>
28
2013-07-12T19:16:25Z
[ "python", "process", "pid" ]
How to check if there exists a process with a given pid?
568,271
<p>Is there a way to check to see if a pid corresponds to a valid process? I'm getting a pid from a different source other than from <code>os.getpid()</code> and I need to check to see if a process with that pid doesn't exist on the machine. </p> <p>I need it to be available in Unix and Windows. I'm also checking to see if the PID is NOT in use.</p>
53
2009-02-20T04:22:43Z
17,645,146
<p>Combining <a href="http://stackoverflow.com/a/6940314/1777162">Giampaolo Rodolà's answer for POSIX</a> and <a href="http://stackoverflow.com/a/17645054/1777162">mine for Windows</a> I got this:</p> <pre><code>import os if os.name == 'posix': def pid_exists(pid): """Check whether pid exists in the current process table.""" import errno if pid &lt; 0: return False try: os.kill(pid, 0) except OSError as e: return e.errno == errno.EPERM else: return True else: def pid_exists(pid): import ctypes kernel32 = ctypes.windll.kernel32 SYNCHRONIZE = 0x100000 process = kernel32.OpenProcess(SYNCHRONIZE, 0, pid) if process != 0: kernel32.CloseHandle(process) return True else: return False </code></pre>
4
2013-07-15T00:24:57Z
[ "python", "process", "pid" ]
How to check if there exists a process with a given pid?
568,271
<p>Is there a way to check to see if a pid corresponds to a valid process? I'm getting a pid from a different source other than from <code>os.getpid()</code> and I need to check to see if a process with that pid doesn't exist on the machine. </p> <p>I need it to be available in Unix and Windows. I'm also checking to see if the PID is NOT in use.</p>
53
2009-02-20T04:22:43Z
20,186,516
<p>In Python 3.3+, you could use exception names instead of errno constants. <a href="http://pubs.opengroup.org/onlinepubs/9699919799/functions/kill.html" rel="nofollow">Posix version</a>:</p> <pre><code>import os def pid_exists(pid): if pid &lt; 0: return False #NOTE: pid == 0 returns True try: os.kill(pid, 0) except ProcessLookupError: # errno.ESRCH return False # No such process except PermissionError: # errno.EPERM return True # Operation not permitted (i.e., process exists) else: return True # no error, we can send a signal to the process </code></pre>
2
2013-11-25T07:05:53Z
[ "python", "process", "pid" ]
How to check if there exists a process with a given pid?
568,271
<p>Is there a way to check to see if a pid corresponds to a valid process? I'm getting a pid from a different source other than from <code>os.getpid()</code> and I need to check to see if a process with that pid doesn't exist on the machine. </p> <p>I need it to be available in Unix and Windows. I'm also checking to see if the PID is NOT in use.</p>
53
2009-02-20T04:22:43Z
23,409,343
<p>Building upon ntrrgc's I've beefed up the windows version so it checks the process exit code and checks for permissions:</p> <pre><code>def pid_exists(pid): """Check whether pid exists in the current process table.""" if os.name == 'posix': import errno if pid &lt; 0: return False try: os.kill(pid, 0) except OSError as e: return e.errno == errno.EPERM else: return True else: import ctypes kernel32 = ctypes.windll.kernel32 HANDLE = ctypes.c_void_p DWORD = ctypes.c_ulong LPDWORD = ctypes.POINTER(DWORD) class ExitCodeProcess(ctypes.Structure): _fields_ = [ ('hProcess', HANDLE), ('lpExitCode', LPDWORD)] SYNCHRONIZE = 0x100000 process = kernel32.OpenProcess(SYNCHRONIZE, 0, pid) if not process: return False ec = ExitCodeProcess() out = kernel32.GetExitCodeProcess(process, ctypes.byref(ec)) if not out: err = kernel32.GetLastError() if kernel32.GetLastError() == 5: # Access is denied. logging.warning("Access is denied to get pid info.") kernel32.CloseHandle(process) return False elif bool(ec.lpExitCode): # print ec.lpExitCode.contents # There is an exist code, it quit kernel32.CloseHandle(process) return False # No exit code, it's running. kernel32.CloseHandle(process) return True </code></pre>
2
2014-05-01T14:06:04Z
[ "python", "process", "pid" ]
How to check if there exists a process with a given pid?
568,271
<p>Is there a way to check to see if a pid corresponds to a valid process? I'm getting a pid from a different source other than from <code>os.getpid()</code> and I need to check to see if a process with that pid doesn't exist on the machine. </p> <p>I need it to be available in Unix and Windows. I'm also checking to see if the PID is NOT in use.</p>
53
2009-02-20T04:22:43Z
23,878,745
<p>This will work for Linux, for example if you want to check if banshee is running... (banshee is a music player)</p> <pre><code>import subprocess def running_process(process): "check if process is running. &lt; process &gt; is the name of the process." proc = subprocess.Popen(["if pgrep " + process + " &gt;/dev/null 2&gt;&amp;1; then echo 'True'; else echo 'False'; fi"], stdout=subprocess.PIPE, shell=True) (Process_Existance, err) = proc.communicate() return Process_Existance # use the function print running_process("banshee") </code></pre>
1
2014-05-26T23:00:03Z
[ "python", "process", "pid" ]
How to check if there exists a process with a given pid?
568,271
<p>Is there a way to check to see if a pid corresponds to a valid process? I'm getting a pid from a different source other than from <code>os.getpid()</code> and I need to check to see if a process with that pid doesn't exist on the machine. </p> <p>I need it to be available in Unix and Windows. I'm also checking to see if the PID is NOT in use.</p>
53
2009-02-20T04:22:43Z
28,065,945
<p>In Windows, you can do it in this way:</p> <pre><code>import ctypes PROCESS_QUERY_INFROMATION = 0x1000 def checkPid(pid): processHandle = ctypes.windll.kernel32.OpenProcess(PROCESS_QUERY_INFROMATION, 0,pid) if processHandle == 0: return False else: ctypes.windll.kernel32.CloseHandle(processHandle) return True </code></pre> <p>First of all, in this code you try to get a handle for process with pid given. If the handle is valid, then close the handle for process and return True; otherwise, you return False. Documentation for OpenProcess: <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/ms684320%28v=vs.85%29.aspx" rel="nofollow">https://msdn.microsoft.com/en-us/library/windows/desktop/ms684320%28v=vs.85%29.aspx</a></p>
1
2015-01-21T11:19:17Z
[ "python", "process", "pid" ]
How do I create an empty array/matrix in NumPy?
568,962
<p>I can't figure out how to use an array or matrix in the way that I would normally use a list. I want to create an empty array (or matrix) and then add one column (or row) to it at a time.</p> <p>At the moment the only way I can find to do this is like:</p> <pre><code>mat = None for col in columns: if mat is None: mat = col else: mat = hstack((mat, col)) </code></pre> <p>Whereas if it were a list, I'd do something like this:</p> <pre><code>list = [] for item in data: list.append(item) </code></pre> <p>Is there a way to use that kind of notation for <a href="http://en.wikipedia.org/wiki/NumPy">NumPy</a> arrays or matrices?</p>
103
2009-02-20T09:58:11Z
569,036
<p>You can use the append function. For rows:</p> <pre><code>&gt;&gt;&gt; from numpy import * &gt;&gt;&gt; a = array([10,20,30]) &gt;&gt;&gt; append(a, [[1,2,3]], axis=0) array([[10, 20, 30], [1, 2, 3]]) </code></pre> <p>For columns:</p> <pre><code>&gt;&gt;&gt; append(a, [[15],[15]], axis=1) array([[10, 20, 30, 15], [1, 2, 3, 15]]) </code></pre> <hr> <p><strong>EDIT</strong><br> Of course, as mentioned in other answers, unless you're doing some processing (ex. inversion) on the matrix/array EVERY time you append something to it, I would just create a list, append to it then convert it to an array.</p>
5
2009-02-20T10:27:31Z
[ "python", "arrays", "numpy" ]
How do I create an empty array/matrix in NumPy?
568,962
<p>I can't figure out how to use an array or matrix in the way that I would normally use a list. I want to create an empty array (or matrix) and then add one column (or row) to it at a time.</p> <p>At the moment the only way I can find to do this is like:</p> <pre><code>mat = None for col in columns: if mat is None: mat = col else: mat = hstack((mat, col)) </code></pre> <p>Whereas if it were a list, I'd do something like this:</p> <pre><code>list = [] for item in data: list.append(item) </code></pre> <p>Is there a way to use that kind of notation for <a href="http://en.wikipedia.org/wiki/NumPy">NumPy</a> arrays or matrices?</p>
103
2009-02-20T09:58:11Z
569,063
<p>You have the wrong mental model for using NumPy efficiently. NumPy arrays are stored in contiguous blocks of memory. If you want to add rows or columns to an existing array, the entire array needs to be copied to a new block of memory, creating gaps for the new elements to be stored. This is very inefficient if done repeatedly to build an array.</p> <p>In the case of adding rows, your best bet is to create an array that is as big as your data set will eventually be, and then add data to it row-by-row:</p> <pre><code>&gt;&gt;&gt; import numpy &gt;&gt;&gt; a = numpy.zeros(shape=(5,2)) &gt;&gt;&gt; a array([[ 0., 0.], [ 0., 0.], [ 0., 0.], [ 0., 0.], [ 0., 0.]]) &gt;&gt;&gt; a[0] = [1,2] &gt;&gt;&gt; a[1] = [2,3] &gt;&gt;&gt; a array([[ 1., 2.], [ 2., 3.], [ 0., 0.], [ 0., 0.], [ 0., 0.]]) </code></pre>
162
2009-02-20T10:36:46Z
[ "python", "arrays", "numpy" ]