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, "=", co...
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, "=", co...
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 MyConfigPa...
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>does...
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>does...
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" betwee...
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>does...
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-Wind...
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>does...
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 pr...
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>does...
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 Lin...
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>does...
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>does...
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>does...
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>...
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-dja...
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> ...
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 ...
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" r...
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 ...
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 ...
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...
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|&...
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|&...
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).hexdiges...
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|&...
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 w...
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|&...
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 lo...
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> <o...
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_...
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...
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,...
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 &g...
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 l...
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' ...
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))) ...
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>TIOCGWI...
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('/bi...
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 ver...
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, ...
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...
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> an...
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...
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 ...
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...
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 bu...
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 no...
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> ...
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) +...
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) +...
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,...
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) +...
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 cau...
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) +...
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>Her...
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) +...
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...
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) +...
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): ...
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) +...
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...
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) +...
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)): ...
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) +...
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) +...
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) +...
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: prin...
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) +...
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 </c...
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) +...
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...
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) +...
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) +...
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 nu...
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) +...
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...
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) +...
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...
-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) +...
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 p...
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, ...
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, ...
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, ...
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, t...
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, ...
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> <...
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, ...
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.Erro...
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, ...
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, da...
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, ...
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 ...
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, ...
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:...
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, ...
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: ...
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, ...
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...
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, ...
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, ...
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 ...
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, ...
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 c...
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 pass...
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. r...
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 pass...
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 pass...
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 ValueE...
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 pass...
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 pass...
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 a...
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 proble...
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 ...
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> ...
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 ...
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 ...
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#...
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...
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...
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...
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...
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 s...
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 T...
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 s...
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:') ...
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 s...
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 s...
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 ...
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 s...
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> (...
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 s...
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 curre...
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 s...
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.k...
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 s...
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 Fals...
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 s...
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...
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 s...
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(proc...
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 No...
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...
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 No...
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...
162
2009-02-20T10:36:46Z
[ "python", "arrays", "numpy" ]