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 |
|---|---|---|---|---|---|---|---|---|---|
Reading specific lines only (Python) | 2,081,836 | <p>I'm using a for loop to read a file, but I only want to read specific lines, say line #26 and #30. Is there any built-in feature to achieve this?</p>
<p>Thanks</p>
| 85 | 2010-01-17T17:14:11Z | 2,083,264 | <p>@OP, you can use enumerate</p>
<pre><code>for n,line in enumerate(open("file")):
if n+1 in [26,30]: # or n in [25,29]
print line.rstrip()
</code></pre>
| 1 | 2010-01-18T00:32:05Z | [
"python",
"file",
"line"
] |
Reading specific lines only (Python) | 2,081,836 | <p>I'm using a for loop to read a file, but I only want to read specific lines, say line #26 and #30. Is there any built-in feature to achieve this?</p>
<p>Thanks</p>
| 85 | 2010-01-17T17:14:11Z | 2,090,476 | <p>Here's my little 2 cents, for what it's worth ;)</p>
<pre><code>def indexLines(filename, lines=[2,4,6,8,10,12,3,5,7,1]):
fp = open(filename, "r")
src = fp.readlines()
data = [(index, line) for index, line in enumerate(src) if index in lines]
fp.close()
return data
# Usage below
filename = "... | 1 | 2010-01-19T01:29:25Z | [
"python",
"file",
"line"
] |
Reading specific lines only (Python) | 2,081,836 | <p>I'm using a for loop to read a file, but I only want to read specific lines, say line #26 and #30. Is there any built-in feature to achieve this?</p>
<p>Thanks</p>
| 85 | 2010-01-17T17:14:11Z | 3,990,042 | <p>if you want line 7</p>
<pre>
line = open("file.txt", "r").readlines()[7]
</pre>
| 10 | 2010-10-21T17:07:39Z | [
"python",
"file",
"line"
] |
Reading specific lines only (Python) | 2,081,836 | <p>I'm using a for loop to read a file, but I only want to read specific lines, say line #26 and #30. Is there any built-in feature to achieve this?</p>
<p>Thanks</p>
| 85 | 2010-01-17T17:14:11Z | 16,432,254 | <p>For the sake of offering another solution:</p>
<pre><code>import linecache
linecache.getline('Sample.txt', Number_of_Line)
</code></pre>
<p>I hope this is quick and easy :)</p>
| 12 | 2013-05-08T03:38:48Z | [
"python",
"file",
"line"
] |
Reading specific lines only (Python) | 2,081,836 | <p>I'm using a for loop to read a file, but I only want to read specific lines, say line #26 and #30. Is there any built-in feature to achieve this?</p>
<p>Thanks</p>
| 85 | 2010-01-17T17:14:11Z | 27,108,718 | <p>For the sake of completeness, here is one more option.</p>
<p>Let's start with a definition from <a href="https://docs.python.org/2.7/glossary.html#term-slice">python docs</a>:</p>
<blockquote>
<p><strong>slice</strong> An object usually containing a portion of a sequence. A slice is created using the subscript ... | 6 | 2014-11-24T15:49:56Z | [
"python",
"file",
"line"
] |
Reading specific lines only (Python) | 2,081,836 | <p>I'm using a for loop to read a file, but I only want to read specific lines, say line #26 and #30. Is there any built-in feature to achieve this?</p>
<p>Thanks</p>
| 85 | 2010-01-17T17:14:11Z | 29,219,956 | <p>Reading files is incredible fast. Reading a 100MB file takes less than 0.1 seconds (see my article <a href="http://martin-thoma.com/reading-files-with-python/" rel="nofollow">Reading and Writing Files with Python</a>). Hence you should read it completely and then work with the single lines.</p>
<p>What most answer ... | 1 | 2015-03-23T20:41:26Z | [
"python",
"file",
"line"
] |
Reading specific lines only (Python) | 2,081,836 | <p>I'm using a for loop to read a file, but I only want to read specific lines, say line #26 and #30. Is there any built-in feature to achieve this?</p>
<p>Thanks</p>
| 85 | 2010-01-17T17:14:11Z | 29,554,444 | <p>I think this would work</p>
<pre><code> open_file1 = open("E:\\test.txt",'r')
read_it1 = open_file1.read()
myline1 = []
for line1 in read_it1.splitlines():
myline1.append(line1)
print myline1[0]
</code></pre>
| 1 | 2015-04-10T06:05:04Z | [
"python",
"file",
"line"
] |
Reading specific lines only (Python) | 2,081,836 | <p>I'm using a for loop to read a file, but I only want to read specific lines, say line #26 and #30. Is there any built-in feature to achieve this?</p>
<p>Thanks</p>
| 85 | 2010-01-17T17:14:11Z | 30,288,686 | <pre><code>file = '/path/to/file_to_be_read.txt'
with open(file) as f:
print f.readlines()[26]
print f.readlines()[30]
</code></pre>
<p>Using the with statement, this opens the file, prints lines 26 and 30, then closes the file. Simple!</p>
| 2 | 2015-05-17T15:38:08Z | [
"python",
"file",
"line"
] |
Reading specific lines only (Python) | 2,081,836 | <p>I'm using a for loop to read a file, but I only want to read specific lines, say line #26 and #30. Is there any built-in feature to achieve this?</p>
<p>Thanks</p>
| 85 | 2010-01-17T17:14:11Z | 34,283,079 | <p>A better and minor change for Alok Singhal's answer</p>
<pre><code>fp = open("file")
for i, line in enumerate(fp,1):
if i == 26:
# 26th line
elif i == 30:
# 30th line
elif i > 30:
break
fp.close()
</code></pre>
| 0 | 2015-12-15T07:13:10Z | [
"python",
"file",
"line"
] |
Reading specific lines only (Python) | 2,081,836 | <p>I'm using a for loop to read a file, but I only want to read specific lines, say line #26 and #30. Is there any built-in feature to achieve this?</p>
<p>Thanks</p>
| 85 | 2010-01-17T17:14:11Z | 35,541,828 | <p>You can do this very simply with this syntax that someone already mentioned, but it's by far the easiest way to do it:</p>
<pre><code>inputFile = open("lineNumbers.txt", "r")
lines = inputFile.readlines()
print (lines[0])
print (lines[2])
</code></pre>
| 0 | 2016-02-21T20:48:12Z | [
"python",
"file",
"line"
] |
Passing multiple values to a function call (Python) | 2,081,929 | <pre><code>import re
def strip_tags(value):
"Return the given HTML with all tags stripped."
return re.sub(r'<[^>]*?>', '', value)
</code></pre>
<p>I have this function to strip HTML tags, but it seems to accept only single value, what do I need to change if I want to pass multiple (not fixed) values a... | 1 | 2010-01-17T17:35:49Z | 2,081,931 | <p>Could you use a loop.</p>
<pre><code>for value in values:
strip_tags(value)
</code></pre>
| 2 | 2010-01-17T17:37:07Z | [
"python",
"function"
] |
Passing multiple values to a function call (Python) | 2,081,929 | <pre><code>import re
def strip_tags(value):
"Return the given HTML with all tags stripped."
return re.sub(r'<[^>]*?>', '', value)
</code></pre>
<p>I have this function to strip HTML tags, but it seems to accept only single value, what do I need to change if I want to pass multiple (not fixed) values a... | 1 | 2010-01-17T17:35:49Z | 2,081,933 | <p>You could pass in <code>value</code> as an array of strings, and then return the array of cleaned values.</p>
| 1 | 2010-01-17T17:37:48Z | [
"python",
"function"
] |
Passing multiple values to a function call (Python) | 2,081,929 | <pre><code>import re
def strip_tags(value):
"Return the given HTML with all tags stripped."
return re.sub(r'<[^>]*?>', '', value)
</code></pre>
<p>I have this function to strip HTML tags, but it seems to accept only single value, what do I need to change if I want to pass multiple (not fixed) values a... | 1 | 2010-01-17T17:35:49Z | 2,081,934 | <pre><code>import re
def strip_tags(values):
return map(lambda i: re.sub(r'<[^>]*?>', '', i), values)
</code></pre>
| 1 | 2010-01-17T17:38:09Z | [
"python",
"function"
] |
Passing multiple values to a function call (Python) | 2,081,929 | <pre><code>import re
def strip_tags(value):
"Return the given HTML with all tags stripped."
return re.sub(r'<[^>]*?>', '', value)
</code></pre>
<p>I have this function to strip HTML tags, but it seems to accept only single value, what do I need to change if I want to pass multiple (not fixed) values a... | 1 | 2010-01-17T17:35:49Z | 2,081,949 | <p>here is a function written over the function you have provided. this would take in a list of values and return the corresponding processed list:</p>
<pre><code>import re
def strip_tags_list(values):
return map(strip_tags, values)
</code></pre>
<p>note: this would work on python 2.6 and earleir versions. on py... | 0 | 2010-01-17T17:44:09Z | [
"python",
"function"
] |
Passing multiple values to a function call (Python) | 2,081,929 | <pre><code>import re
def strip_tags(value):
"Return the given HTML with all tags stripped."
return re.sub(r'<[^>]*?>', '', value)
</code></pre>
<p>I have this function to strip HTML tags, but it seems to accept only single value, what do I need to change if I want to pass multiple (not fixed) values a... | 1 | 2010-01-17T17:35:49Z | 2,081,965 | <p>Python offers a way to use arbitrary-length argument lists:</p>
<pre><code>def myfunc(*args):
for argument in args:
print "myfunc was given", argument
</code></pre>
<p>If you put <code>*args</code> in your function definition, all values passed to the function are available as a tuple called <code>args... | 7 | 2010-01-17T17:49:53Z | [
"python",
"function"
] |
Passing multiple values to a function call (Python) | 2,081,929 | <pre><code>import re
def strip_tags(value):
"Return the given HTML with all tags stripped."
return re.sub(r'<[^>]*?>', '', value)
</code></pre>
<p>I have this function to strip HTML tags, but it seems to accept only single value, what do I need to change if I want to pass multiple (not fixed) values a... | 1 | 2010-01-17T17:35:49Z | 2,081,974 | <p>If the values are independent of each other, then don't modify strip_tags, just change how you call it:</p>
<pre><code>values = [some_value, another_value]
values = [strip_tags(v) for v in values]
# values[0] is now the strip_tags version of the old values[0]
# similar to values[0] = strip_tags(values[0]), except f... | 1 | 2010-01-17T17:52:14Z | [
"python",
"function"
] |
Regex for removing whitespace | 2,081,991 | <pre><code>def remove_whitespaces(value):
"Remove all whitespaces"
p = re.compile(r'\s+')
return p.sub(' ', value)
</code></pre>
<p>The above code strips tags but doesn't remove "all" whitespaces from the value.</p>
<p>Thanks</p>
| 1 | 2010-01-17T17:58:05Z | 2,081,996 | <pre><code>p.sub(' ', value)
</code></pre>
<p>should be</p>
<pre><code>p.sub('', value)
</code></pre>
<p>The former replaces all whitespace with a single space, the latter replaces with nothing.</p>
| 3 | 2010-01-17T17:59:34Z | [
"python",
"regex",
"function"
] |
Regex for removing whitespace | 2,081,991 | <pre><code>def remove_whitespaces(value):
"Remove all whitespaces"
p = re.compile(r'\s+')
return p.sub(' ', value)
</code></pre>
<p>The above code strips tags but doesn't remove "all" whitespaces from the value.</p>
<p>Thanks</p>
| 1 | 2010-01-17T17:58:05Z | 2,082,046 | <p>Maybe <strike>value.join(p.split())</strike> ''.join(value.split()) could work for you?</p>
| 1 | 2010-01-17T18:14:47Z | [
"python",
"regex",
"function"
] |
Regex for removing whitespace | 2,081,991 | <pre><code>def remove_whitespaces(value):
"Remove all whitespaces"
p = re.compile(r'\s+')
return p.sub(' ', value)
</code></pre>
<p>The above code strips tags but doesn't remove "all" whitespaces from the value.</p>
<p>Thanks</p>
| 1 | 2010-01-17T17:58:05Z | 2,082,051 | <p>The fastest general approach eschews REs in favor of string's fast, powerful <a href="http://docs.python.org/library/stdtypes.html?highlight=translate#str.translate"><code>.translate</code></a> method:</p>
<pre><code>import string
identity = string.maketrans('', '')
def remove_whitespace(value):
return value.tra... | 6 | 2010-01-17T18:15:41Z | [
"python",
"regex",
"function"
] |
Regex for removing whitespace | 2,081,991 | <pre><code>def remove_whitespaces(value):
"Remove all whitespaces"
p = re.compile(r'\s+')
return p.sub(' ', value)
</code></pre>
<p>The above code strips tags but doesn't remove "all" whitespaces from the value.</p>
<p>Thanks</p>
| 1 | 2010-01-17T17:58:05Z | 2,082,080 | <p><code>re.sub(r'\s', '', value)</code> function works well for me, in this case.</p>
| 0 | 2010-01-17T18:24:07Z | [
"python",
"regex",
"function"
] |
Regex for removing whitespace | 2,081,991 | <pre><code>def remove_whitespaces(value):
"Remove all whitespaces"
p = re.compile(r'\s+')
return p.sub(' ', value)
</code></pre>
<p>The above code strips tags but doesn't remove "all" whitespaces from the value.</p>
<p>Thanks</p>
| 1 | 2010-01-17T17:58:05Z | 2,083,259 | <p>@OP, compile your regex pattern outside, so you don't have to call re.compile everytime you use the procedure. Also you are substituting back to one space, that is not removing spaces is it?</p>
<pre><code>p = re.compile(r'\s+')
def remove_whitespaces(p,value):
"Remove all whitespaces"
return p.sub('', ... | 0 | 2010-01-18T00:29:43Z | [
"python",
"regex",
"function"
] |
Regex for removing whitespace | 2,081,991 | <pre><code>def remove_whitespaces(value):
"Remove all whitespaces"
p = re.compile(r'\s+')
return p.sub(' ', value)
</code></pre>
<p>The above code strips tags but doesn't remove "all" whitespaces from the value.</p>
<p>Thanks</p>
| 1 | 2010-01-17T17:58:05Z | 2,086,536 | <p><code>re.sub('\s*', '', value)</code> should also work!</p>
| 1 | 2010-01-18T14:10:24Z | [
"python",
"regex",
"function"
] |
Simplest way to integrate python gui app with c console app | 2,082,028 | <p>I have a c console app which converts a c file to a html file, the c file location is passed to the program as a command line argument.(the app is for the windows platform)</p>
<p>What I would like to do is have a python gui app to allow the user to select a file and pass the location of the file to the c app for p... | 3 | 2010-01-17T18:09:12Z | 2,082,040 | <p>You probably want the <a href="http://docs.python.org/library/subprocess.html" rel="nofollow">subprocess</a> module.</p>
<p>At the very minimum:</p>
<pre><code>import subprocess
retcode = subprocess.call(["/path/to/myCprogram", "/path/to/file.c"])
if retcode == 0:
print "success!"
</code></pre>
<p>This will ru... | 10 | 2010-01-17T18:13:08Z | [
"python",
"c",
"user-interface",
"integrate"
] |
Simplest way to integrate python gui app with c console app | 2,082,028 | <p>I have a c console app which converts a c file to a html file, the c file location is passed to the program as a command line argument.(the app is for the windows platform)</p>
<p>What I would like to do is have a python gui app to allow the user to select a file and pass the location of the file to the c app for p... | 3 | 2010-01-17T18:09:12Z | 2,082,044 | <p>There are a number of ways you could acheive this, but in your case the requirements seems so straightforward all you need is to use <code>Popen</code> from the <code>subprocess</code> module.</p>
<pre><code> process = subprocess.Popen(['myutil', file_location]...)
process.wait()
</code></pre>
<p>If you need to g... | 2 | 2010-01-17T18:14:41Z | [
"python",
"c",
"user-interface",
"integrate"
] |
Strange bug while combining images in Python | 2,082,145 | <p>I have a hundred 10x10 px images, and I want to combine them into a big 100x100 image. I'm using the Image library to first create a blank image and then paste in the smaller images:</p>
<pre><code>blank = Image.new('P',(100,100))
blank.paste(im,box)
</code></pre>
<p>The smaller images are in color, but the result... | 0 | 2010-01-17T18:47:01Z | 2,082,176 | <p>It's probably something to do with using a palette type image (mode P). Is there a specific reason you are doing this? If not, try passing <code>'RGB'</code> as the first argument.</p>
| 2 | 2010-01-17T18:53:55Z | [
"python",
"image",
"image-processing",
"python-imaging-library"
] |
Case insensitive dictionary | 2,082,152 | <p>I'd like my dictionary to be case insensitive.</p>
<p>I have this example code:</p>
<pre><code>text = "practice changing the color"
words = {'color': 'colour',
'practice': 'practise'}
def replace(words,text):
keys = words.keys()
for i in keys:
text= text.replace(i ,words[i])
return ... | 37 | 2010-01-17T18:48:20Z | 2,082,169 | <p>If I understand you correctly and you want a way to key dictionaries in a non case-sensitive fashion, one way would be to subclass dict and overload the setter / getter:</p>
<pre><code>class CaseInsensitiveDict(dict):
def __setitem__(self, key, value):
super(CaseInsensitiveDict, self).__setitem__(key.lo... | 29 | 2010-01-17T18:50:55Z | [
"python"
] |
Case insensitive dictionary | 2,082,152 | <p>I'd like my dictionary to be case insensitive.</p>
<p>I have this example code:</p>
<pre><code>text = "practice changing the color"
words = {'color': 'colour',
'practice': 'practise'}
def replace(words,text):
keys = words.keys()
for i in keys:
text= text.replace(i ,words[i])
return ... | 37 | 2010-01-17T18:48:20Z | 2,082,261 | <p>While a case insensitive dictionary is a solution, and there are answers to how to achieve that, there is a possibly easier way in this case. A case insensitive search is sufficient:</p>
<pre><code>import re
text = "Practice changing the Color"
words = {'color': 'colour', 'practice': 'practise'}
def replace(words... | 2 | 2010-01-17T19:17:48Z | [
"python"
] |
Case insensitive dictionary | 2,082,152 | <p>I'd like my dictionary to be case insensitive.</p>
<p>I have this example code:</p>
<pre><code>text = "practice changing the color"
words = {'color': 'colour',
'practice': 'practise'}
def replace(words,text):
keys = words.keys()
for i in keys:
text= text.replace(i ,words[i])
return ... | 37 | 2010-01-17T18:48:20Z | 2,082,959 | <p>Would you consider using <code>string.lower()</code> on your inputs and using a fully lowercase dictionary? It's a bit of a hacky solution, but it works</p>
| 6 | 2010-01-17T22:47:15Z | [
"python"
] |
Case insensitive dictionary | 2,082,152 | <p>I'd like my dictionary to be case insensitive.</p>
<p>I have this example code:</p>
<pre><code>text = "practice changing the color"
words = {'color': 'colour',
'practice': 'practise'}
def replace(words,text):
keys = words.keys()
for i in keys:
text= text.replace(i ,words[i])
return ... | 37 | 2010-01-17T18:48:20Z | 16,817,943 | <p>Just for the record. I found an awesome impementation on <a href="http://docs.python-requests.org/">Requests</a>:</p>
<p><a href="https://github.com/kennethreitz/requests/blob/v1.2.3/requests/structures.py#L37">https://github.com/kennethreitz/requests/blob/v1.2.3/requests/structures.py#L37</a></p>
| 21 | 2013-05-29T15:24:45Z | [
"python"
] |
Case insensitive dictionary | 2,082,152 | <p>I'd like my dictionary to be case insensitive.</p>
<p>I have this example code:</p>
<pre><code>text = "practice changing the color"
words = {'color': 'colour',
'practice': 'practise'}
def replace(words,text):
keys = words.keys()
for i in keys:
text= text.replace(i ,words[i])
return ... | 37 | 2010-01-17T18:48:20Z | 30,221,547 | <p>In my particular instance, I needed a case insensitive lookup, however, I did not want to modify the original case of the key. For example:</p>
<pre><code>>>> d = {}
>>> d['MyConfig'] = 'value'
>>> d['myconfig'] = 'new_value'
>>> d
{'MyConfig': 'new_value'}
</code></pre>
<p>You ... | 2 | 2015-05-13T17:26:36Z | [
"python"
] |
Case insensitive dictionary | 2,082,152 | <p>I'd like my dictionary to be case insensitive.</p>
<p>I have this example code:</p>
<pre><code>text = "practice changing the color"
words = {'color': 'colour',
'practice': 'practise'}
def replace(words,text):
keys = words.keys()
for i in keys:
text= text.replace(i ,words[i])
return ... | 37 | 2010-01-17T18:48:20Z | 32,888,599 | <p>The <a href="http://stackoverflow.com/a/2082169/277172">currently approved answer</a> doesn't work for <strong>a lot</strong> of cases, so it cannot be used as a drop-in <code>dict</code> replacement. Some tricky points in getting a proper <code>dict</code> replacement:</p>
<ul>
<li>overloading all of the methods t... | 16 | 2015-10-01T13:16:54Z | [
"python"
] |
How to export C# methods? | 2,082,159 | <p>How can we export C# methods?</p>
<p>I have a dll and I want to use its methods in the Python language with the ctypes module.
Because I need to use the ctypes module, I need to export the C# methods for them to be visible in Python.</p>
<p>So, how can I export the C# methods (like they do in C++)?</p>
| 15 | 2010-01-17T18:49:24Z | 2,082,194 | <p>With the normal Python implementation ("CPython"), you can't, at least not directly.</p>
<p>You could write native C wrappers around our C# methods using <a href="http://en.wikipedia.org/wiki/C%2B%2B/CLI" rel="nofollow">C++/CLI</a>, and call these wrappers from Python.</p>
<p>Or, you could try <a href="http://iron... | 1 | 2010-01-17T18:58:04Z | [
"c#",
"python",
"methods",
"export",
"python.net"
] |
How to export C# methods? | 2,082,159 | <p>How can we export C# methods?</p>
<p>I have a dll and I want to use its methods in the Python language with the ctypes module.
Because I need to use the ctypes module, I need to export the C# methods for them to be visible in Python.</p>
<p>So, how can I export the C# methods (like they do in C++)?</p>
| 15 | 2010-01-17T18:49:24Z | 2,082,198 | <p>(This may no longer be relevant since SLaks has found that ingenious link, but I'll leave an edited version for reference...)</p>
<p>The "normal" way of exposing .NET/C# objects to unmanaged code (like Python) is to create a COM-callable wrapper for the C# DLL (.NET assembly), and call that using Python's COM/OLE s... | 1 | 2010-01-17T18:59:48Z | [
"c#",
"python",
"methods",
"export",
"python.net"
] |
How to export C# methods? | 2,082,159 | <p>How can we export C# methods?</p>
<p>I have a dll and I want to use its methods in the Python language with the ctypes module.
Because I need to use the ctypes module, I need to export the C# methods for them to be visible in Python.</p>
<p>So, how can I export the C# methods (like they do in C++)?</p>
| 15 | 2010-01-17T18:49:24Z | 2,082,202 | <p>Contrary to popular belief, this <em>is</em> possible.<br>
See <a href="http://sites.google.com/site/robertgiesecke/Home/uploads/unmanagedexports">here</a>.</p>
| 22 | 2010-01-17T19:01:36Z | [
"c#",
"python",
"methods",
"export",
"python.net"
] |
How to export C# methods? | 2,082,159 | <p>How can we export C# methods?</p>
<p>I have a dll and I want to use its methods in the Python language with the ctypes module.
Because I need to use the ctypes module, I need to export the C# methods for them to be visible in Python.</p>
<p>So, how can I export the C# methods (like they do in C++)?</p>
| 15 | 2010-01-17T18:49:24Z | 2,082,212 | <p>That's not possible. If you need DLL exports you'll need to use the C++/CLI language. For example:</p>
<pre><code>public ref class Class1 {
public:
static int add(int a, int b) {
return a + b;
}
};
extern "C" __declspec(dllexport)
int add(int a, int b) {
return Class1::add(a, b);
}
</code></pre>
<p... | 1 | 2010-01-17T19:03:26Z | [
"c#",
"python",
"methods",
"export",
"python.net"
] |
Reading input from raw_input() without having the prompt overwritten by other threads in Python | 2,082,387 | <p>I'm trying to let the user input commands at a console using raw_input(), this works fine. The problem is I have background threads that occasionally output log-information to the screen and when they do they mess up the input prompt (since the output go wherever the cursor happens to be at the moment).</p>
<p>This... | 10 | 2010-01-17T19:55:47Z | 2,082,403 | <p>I don't think it's possible. How should that behave anyways? Nothing shows up until the user presses Enter? If that's so, output would only come when the user issues a command (or whatever your system expects), and that doesn't sound desirable.</p>
<p>Methinks your threads should output to another file.</p>
| 0 | 2010-01-17T20:01:22Z | [
"python",
"multithreading",
"raw-input"
] |
Reading input from raw_input() without having the prompt overwritten by other threads in Python | 2,082,387 | <p>I'm trying to let the user input commands at a console using raw_input(), this works fine. The problem is I have background threads that occasionally output log-information to the screen and when they do they mess up the input prompt (since the output go wherever the cursor happens to be at the moment).</p>
<p>This... | 10 | 2010-01-17T19:55:47Z | 2,082,446 | <p>I think you need something that lets you dynamically print/delete/overwrite text from the terminal window e.g. how the UNIX <code>watch</code> or <code>top</code> commands work. </p>
<p>I think in your case you would print "Prompt>" but then when you get a "Hello World" you overwrite "Prompt>" with "Hello World", a... | 3 | 2010-01-17T20:16:46Z | [
"python",
"multithreading",
"raw-input"
] |
Reading input from raw_input() without having the prompt overwritten by other threads in Python | 2,082,387 | <p>I'm trying to let the user input commands at a console using raw_input(), this works fine. The problem is I have background threads that occasionally output log-information to the screen and when they do they mess up the input prompt (since the output go wherever the cursor happens to be at the moment).</p>
<p>This... | 10 | 2010-01-17T19:55:47Z | 2,082,685 | <p>you need to update stdout from a single thread, not from multiple threads... or else you have no control over interleaved i/o. </p>
<p>you will want to create a single thread for output writing. </p>
<p>you can use a Queue in the thread and have all other threads write their output logging info to it.. then read... | 1 | 2010-01-17T21:17:15Z | [
"python",
"multithreading",
"raw-input"
] |
Reading input from raw_input() without having the prompt overwritten by other threads in Python | 2,082,387 | <p>I'm trying to let the user input commands at a console using raw_input(), this works fine. The problem is I have background threads that occasionally output log-information to the screen and when they do they mess up the input prompt (since the output go wherever the cursor happens to be at the moment).</p>
<p>This... | 10 | 2010-01-17T19:55:47Z | 4,653,306 | <p>I recently encountered this problem, and would like to leave this solution here for future reference.
These solutions clear the pending raw_input (readline) text from the terminal, print the new text, then reprint to the terminal what was in the raw_input buffer.</p>
<p>This first program is pretty simple, but only... | 21 | 2011-01-11T01:22:25Z | [
"python",
"multithreading",
"raw-input"
] |
preprocessing RIPEMD-160 | 2,082,474 | <p>is the padding of RIPEMD-160 exactly the same as MD4 padding, down to the little-endian change?</p>
<p>if i input "abc" in ascii, the processed data in hex should be 8063626100000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000001800000000</p>
<p>right?</p>
| 0 | 2010-01-17T20:24:18Z | 2,083,361 | <p>Yes, per the good pseudocode file found <a href="http://homes.esat.kuleuven.be/~bosselae/ripemd/rmd128.txt" rel="nofollow">here</a> (for ripemd-128, but ripemd-160 just extends that),</p>
<pre><code>Padding is identical to that of MD4.
</code></pre>
| 1 | 2010-01-18T01:07:57Z | [
"python",
"cryptography"
] |
Python function returning None after recursion | 2,082,635 | <p>I can't figure out why this python function returns None if it calls itself recursively.</p>
<p>It was part of my solution to a Project Euler problem. I have solved the problem in a better way anyhow, but this is still annoying me as the function seems to work OK - and it seems to know the value of the variable I ... | 3 | 2010-01-17T21:05:15Z | 2,082,661 | <p>You forgot to return a value when there is failure to find a prime:</p>
<pre><code>for div in range(2,candidate//2,1):
if candidate % div == 0:
prime = False
print candidate, "is not prime - divisible by", div
return next_prime(candidate)
</code></pre>
<p>Recursion isn't really suitable... | 6 | 2010-01-17T21:11:08Z | [
"python",
"recursion"
] |
Python function returning None after recursion | 2,082,635 | <p>I can't figure out why this python function returns None if it calls itself recursively.</p>
<p>It was part of my solution to a Project Euler problem. I have solved the problem in a better way anyhow, but this is still annoying me as the function seems to work OK - and it seems to know the value of the variable I ... | 3 | 2010-01-17T21:05:15Z | 2,082,675 | <p>Notice that you are making recursive calls to the next_prime function, but not returning the value from it from the calling function.</p>
<p>Replace the lines:</p>
<pre><code>print candidate, "is not prime - divisible by", div
next_prime(candidate)
</code></pre>
<p>with</p>
<pre><code>print candidate, "is not pr... | 0 | 2010-01-17T21:14:18Z | [
"python",
"recursion"
] |
Python function returning None after recursion | 2,082,635 | <p>I can't figure out why this python function returns None if it calls itself recursively.</p>
<p>It was part of my solution to a Project Euler problem. I have solved the problem in a better way anyhow, but this is still annoying me as the function seems to work OK - and it seems to know the value of the variable I ... | 3 | 2010-01-17T21:05:15Z | 2,082,740 | <p>As others have said, this is not really the place for recursion. Here is an example using iteration. I've also defined another function which tests the primality of an integer - I think this makes the code simpler.</p>
<pre><code>def is_prime(n):
"""Return True if n is prime."""
for i in xrange(2, n//2):
... | 1 | 2010-01-17T21:31:43Z | [
"python",
"recursion"
] |
real time subprocess.Popen via stdout and PIPE | 2,082,850 | <p>I am trying to grab stdout from a subprocess,Popen call and although I am achieving this easily by doing:</p>
<pre><code>cmd = subprocess.Popen('ls -l', shell=True, stdout=PIPE)
for line in cmd.stdout.readlines():
print line
</code></pre>
<p>I would like to grab stdout in "real time". With the above method, PI... | 14 | 2010-01-17T22:03:03Z | 2,082,873 | <p>The call to <code>readlines</code> is waiting for the process to exit. Replace this with a loop around <code>cmd.stdout.readline()</code> (note singular) and all should be well.</p>
| 0 | 2010-01-17T22:09:27Z | [
"python",
"logging",
"subprocess",
"pipe",
"popen"
] |
real time subprocess.Popen via stdout and PIPE | 2,082,850 | <p>I am trying to grab stdout from a subprocess,Popen call and although I am achieving this easily by doing:</p>
<pre><code>cmd = subprocess.Popen('ls -l', shell=True, stdout=PIPE)
for line in cmd.stdout.readlines():
print line
</code></pre>
<p>I would like to grab stdout in "real time". With the above method, PI... | 14 | 2010-01-17T22:03:03Z | 2,082,883 | <pre><code>cmd = subprocess.Popen(["ls", "-l"], stdout=subprocess.PIPE)
for line in cmd.stdout:
print line.rstrip("\n")
</code></pre>
| 1 | 2010-01-17T22:13:24Z | [
"python",
"logging",
"subprocess",
"pipe",
"popen"
] |
real time subprocess.Popen via stdout and PIPE | 2,082,850 | <p>I am trying to grab stdout from a subprocess,Popen call and although I am achieving this easily by doing:</p>
<pre><code>cmd = subprocess.Popen('ls -l', shell=True, stdout=PIPE)
for line in cmd.stdout.readlines():
print line
</code></pre>
<p>I would like to grab stdout in "real time". With the above method, PI... | 14 | 2010-01-17T22:03:03Z | 2,082,917 | <p>Drop the readlines() which is coalescing the output.
Also you'll need to enforce line buffering since most commands will interally buffer output to a pipe. For details see: <a href="http://www.pixelbeat.org/programming/stdio_buffering/" rel="nofollow">http://www.pixelbeat.org/programming/stdio_buffering/</a></p>
| 3 | 2010-01-17T22:31:11Z | [
"python",
"logging",
"subprocess",
"pipe",
"popen"
] |
real time subprocess.Popen via stdout and PIPE | 2,082,850 | <p>I am trying to grab stdout from a subprocess,Popen call and although I am achieving this easily by doing:</p>
<pre><code>cmd = subprocess.Popen('ls -l', shell=True, stdout=PIPE)
for line in cmd.stdout.readlines():
print line
</code></pre>
<p>I would like to grab stdout in "real time". With the above method, PI... | 14 | 2010-01-17T22:03:03Z | 2,083,432 | <p>To get output "in real time", <code>subprocess</code> is unsuitable because it can't defeat the other process's buffering strategies. That's the reason I always recommend, whenever such "real time" output grabbing is desired (quite a frequent question on stack overflow!), to use instead <a href="http://www.noah.org... | 9 | 2010-01-18T01:30:31Z | [
"python",
"logging",
"subprocess",
"pipe",
"popen"
] |
real time subprocess.Popen via stdout and PIPE | 2,082,850 | <p>I am trying to grab stdout from a subprocess,Popen call and although I am achieving this easily by doing:</p>
<pre><code>cmd = subprocess.Popen('ls -l', shell=True, stdout=PIPE)
for line in cmd.stdout.readlines():
print line
</code></pre>
<p>I would like to grab stdout in "real time". With the above method, PI... | 14 | 2010-01-17T22:03:03Z | 2,345,019 | <p>Your interpreter is buffering. Add a call to sys.stdout.flush() after your print statement.</p>
| 17 | 2010-02-26T21:41:31Z | [
"python",
"logging",
"subprocess",
"pipe",
"popen"
] |
real time subprocess.Popen via stdout and PIPE | 2,082,850 | <p>I am trying to grab stdout from a subprocess,Popen call and although I am achieving this easily by doing:</p>
<pre><code>cmd = subprocess.Popen('ls -l', shell=True, stdout=PIPE)
for line in cmd.stdout.readlines():
print line
</code></pre>
<p>I would like to grab stdout in "real time". With the above method, PI... | 14 | 2010-01-17T22:03:03Z | 16,404,840 | <p>As this is a question I searched for an answer to for days, I wanted to leave this here for those who follow. While it is true that <code>subprocess</code> cannot combat the other process's buffering strategy, in the case where you are calling another Python script with <code>subprocess.Popen</code>, you CAN tell i... | 3 | 2013-05-06T18:26:33Z | [
"python",
"logging",
"subprocess",
"pipe",
"popen"
] |
real time subprocess.Popen via stdout and PIPE | 2,082,850 | <p>I am trying to grab stdout from a subprocess,Popen call and although I am achieving this easily by doing:</p>
<pre><code>cmd = subprocess.Popen('ls -l', shell=True, stdout=PIPE)
for line in cmd.stdout.readlines():
print line
</code></pre>
<p>I would like to grab stdout in "real time". With the above method, PI... | 14 | 2010-01-17T22:03:03Z | 24,127,532 | <p>Actually, the real solution is to directly redirect the stdout of the subprocess to the stdout of your process.</p>
<p>Indeed, with your solution, you can only print stdout, and not stderr, for instance, at the same time.</p>
<pre><code>import sys
from subprocess import Popen
Popen("./slow_cmd_output.sh", stdout=s... | 5 | 2014-06-09T19:30:27Z | [
"python",
"logging",
"subprocess",
"pipe",
"popen"
] |
real time subprocess.Popen via stdout and PIPE | 2,082,850 | <p>I am trying to grab stdout from a subprocess,Popen call and although I am achieving this easily by doing:</p>
<pre><code>cmd = subprocess.Popen('ls -l', shell=True, stdout=PIPE)
for line in cmd.stdout.readlines():
print line
</code></pre>
<p>I would like to grab stdout in "real time". With the above method, PI... | 14 | 2010-01-17T22:03:03Z | 32,538,935 | <p>As stated already the issue is in the stdio library's buffering of printf like statements when no terminal is attached to the process. There is a way around this on the Windows platform anyway. There may be a similar solution on other platforms as well.</p>
<p>On Windows you can force create a new console at proces... | 0 | 2015-09-12T12:43:06Z | [
"python",
"logging",
"subprocess",
"pipe",
"popen"
] |
Using Nose & NoseXUnit on a Python package | 2,083,102 | <p><a href="http://stackoverflow.com/questions/225598/pretty-continuous-integration-for-python">This is a previous post</a> detailing a CI setup for Python. The asker and answerer detail the use of <em>Nose</em> and <em>NoseXUnit</em> with Hudson for their builds. However, <em>NoseXUnit</em> throws an error when run o... | 4 | 2010-01-17T23:34:38Z | 2,438,878 | <p>You probably shouldn't use NoseXUnit - it's really out of date, and a similar feature exists in nose >= 0.11.</p>
<p>From nose --help:</p>
<pre><code> --with-xunit Enable plugin Xunit: This plugin provides test results
in the standard XUnit XML format. [NOSE_WITH_XUNIT]
--xunit-... | 5 | 2010-03-13T15:31:24Z | [
"python",
"package",
"web2py",
"nose",
"nosetests"
] |
Import all the modules in a directory | 2,083,140 | <p>Is there any way to import all modules in the current directory, and return a list of them?</p>
<p>For example, for the directory with:</p>
<ul>
<li>mod.py</li>
<li>mod2.py</li>
<li>mod3.py</li>
</ul>
<p>It will give you <code>[<module 'mod'>, <module 'mod2'>, <module 'mod3'>]</code></p>
| 5 | 2010-01-17T23:46:53Z | 16,495,561 | <p>I think I've got your idea.</p>
<p>Try the following:</p>
<pre><code>import glob
modules = []
for module_name in glob.glob("*.py"):
modules.append(__import__(module_name[:-3]))
</code></pre>
<p>This way you get a list of <code>module</code> objects and don't pollute the global namespace.</p>
| 1 | 2013-05-11T09:12:59Z | [
"python",
"module"
] |
Opening and Printing files using Recursion in python | 2,083,185 | <p>So I am trying to write a code that opens a file and inside that file might be empty or contains the name of other files to open on each line. For example. 1.txt has 2.txt. on the first line and 3.txt on the second line. 2.txt is a empty file and 3.txt has 4.txt on the first line. I have to have an output that print... | 0 | 2010-01-17T23:59:30Z | 2,083,210 | <p>I am going to assume that a line contains the full path to the file. If this is not the case, then you should be able to make the necessary path modifications very easily. This IS homework, so I'll let you figure that out on your own</p>
<p>Try this:</p>
<pre><code>def search(doc):
print "Visiting", doc
f ... | 4 | 2010-01-18T00:11:30Z | [
"python",
"recursion"
] |
"Pre-importing" a variable into a module | 2,083,350 | <p>Python beginner here, so I apologize if this question has a simple answer. (I hope it does.)</p>
<p>I am working on a python module--a plugin for a larger program. I'm trying to develop the module using the Eclipse IDE (with pydev), which means I need to be able to run this module stand-alone, i.e. not as a plug... | 1 | 2010-01-18T01:04:52Z | 2,083,384 | <p>Presumably, when you run it "stand-alone" under Eclipse (or "stand-alone" without Eclipse, for that matter, just as "python foobar.py" at a shell prompt), your module's <code>__name__</code> global variable has the value of <code>'__main__'</code> (if the module gets imported, instead, that global variable's value w... | 2 | 2010-01-18T01:15:44Z | [
"python",
"pydev"
] |
Cannot change global variables in a function through an exec() statement? | 2,083,353 | <p>Why can I not change global variables from inside a function, using exec()? It works fine when the assignment statement is outside of exec(). Here is an example of my problem:</p>
<pre>
>>> myvar = 'test'
>>> def myfunc():
... global myvar
... exec('myvar = "changed!"')
... print(myvar)
...
>>> myfunc(... | 11 | 2010-01-18T01:05:37Z | 2,083,374 | <p>Per <a href="http://docs.python.org/reference/simple_stmts.html#the-exec-statement" rel="nofollow">the docs</a>, the <code>exec</code> statement takes two optional expressions, defaulting to <code>globals()</code> and <code>locals()</code>, and always performs changes (if any) in the <code>locals()</code> one.</p>
... | 18 | 2010-01-18T01:12:36Z | [
"python",
"exec",
"global"
] |
Cannot change global variables in a function through an exec() statement? | 2,083,353 | <p>Why can I not change global variables from inside a function, using exec()? It works fine when the assignment statement is outside of exec(). Here is an example of my problem:</p>
<pre>
>>> myvar = 'test'
>>> def myfunc():
... global myvar
... exec('myvar = "changed!"')
... print(myvar)
...
>>> myfunc(... | 11 | 2010-01-18T01:05:37Z | 2,083,375 | <p>How about this:</p>
<pre><code>>>> myvar = 'test'
>>> def myfunc():
... exec('globals()["myvar"] = "changed!"')
... print(myvar)
...
>>> myfunc()
changed!
>>> print(myvar)
changed!
</code></pre>
<p>It worked for me in Python 2.6.</p>
<p>EDIT: Actually Alex Martelli's e... | 2 | 2010-01-18T01:12:46Z | [
"python",
"exec",
"global"
] |
Cannot change global variables in a function through an exec() statement? | 2,083,353 | <p>Why can I not change global variables from inside a function, using exec()? It works fine when the assignment statement is outside of exec(). Here is an example of my problem:</p>
<pre>
>>> myvar = 'test'
>>> def myfunc():
... global myvar
... exec('myvar = "changed!"')
... print(myvar)
...
>>> myfunc(... | 11 | 2010-01-18T01:05:37Z | 2,083,436 | <p>To add to Alex's answer: although when you omit the locals/globals arguments they default to the locals and globals of the caller, this only a convenience hack; it does <em>not</em> mean they are inheriting the full execution context of the caller. In particular:</p>
<p>a. nested scope cells are not available to th... | 4 | 2010-01-18T01:31:38Z | [
"python",
"exec",
"global"
] |
Is there any difference between UserDict and Dict? | 2,083,504 | <p>If I want a class to have a dictionary behavior, why should I inherit from <code>dict</code> or <code>UserDict</code>?</p>
| 3 | 2010-01-18T01:56:43Z | 2,083,524 | <p>You can inherit from <code>dict</code> in any Python that's version 2.2 or better, but you'll have to override every single method of interest -- for example, your override of <code>__getitem__</code> will <strong>not</strong> be used by <code>get</code> unless you also override that one, and so on, and so forth.</p... | 8 | 2010-01-18T02:04:11Z | [
"python"
] |
Python C-API module exit handler - an atexit equivalent? | 2,083,523 | <p>I'm using Python ver 2.6.4</p>
<p>There is a function I have to call from a C library when my extension module exits/is unloaded. What would be the equivalent of atexit for a C extension module? </p>
| 3 | 2010-01-18T02:04:03Z | 2,083,532 | <p>The <a href="https://docs.python.org/2/c-api/sys.html#c.Py_AtExit" rel="nofollow"><code>Py_AtExit()</code></a> function can be used to register up to 32 cleanup functions.</p>
| 4 | 2010-01-18T02:06:28Z | [
"python",
"python-c-api",
"python-c-extension"
] |
what is the encoding of this string,'base64' or 'utf-8'??? ,how can i get it readable | 2,083,734 | <pre><code>print "4-12\u4e2a\u82f1\u6587\u5b57\u6bcd\u3001\u6570\u5b57\u548c\u4e0b\u5212\u7ebf".decode('base64')#no
</code></pre>
<p>thanks</p>
<hr>
<p>and </p>
<p>if i have '4-12ä¸ªè±æåæ¯ãæ°ååä¸å线'</p>
<p>how can i get the string '4-12\u4e2a\u82f1\u6587\u5b57\u6bcd\u3001\u6570\u5b57\u548c\u4e0b\... | 2 | 2010-01-18T03:25:30Z | 2,083,743 | <p>It's a Unicode representation. Try <code>.decode('unicode-escape')</code>.</p>
<p><strong>EDIT:</strong></p>
<p>For the second decode, what you use depends on your terminal/console settings. <code>'utf-8'</code> is a sane starting point, then encode using <code>'unicode-escape'</code> in order to get the Unicode ... | 1 | 2010-01-18T03:28:15Z | [
"javascript",
"python"
] |
what is the encoding of this string,'base64' or 'utf-8'??? ,how can i get it readable | 2,083,734 | <pre><code>print "4-12\u4e2a\u82f1\u6587\u5b57\u6bcd\u3001\u6570\u5b57\u548c\u4e0b\u5212\u7ebf".decode('base64')#no
</code></pre>
<p>thanks</p>
<hr>
<p>and </p>
<p>if i have '4-12ä¸ªè±æåæ¯ãæ°ååä¸å线'</p>
<p>how can i get the string '4-12\u4e2a\u82f1\u6587\u5b57\u6bcd\u3001\u6570\u5b57\u548c\u4e0b\... | 2 | 2010-01-18T03:25:30Z | 2,083,744 | <p>It's encoded as a python unicode literal:</p>
<pre><code>>>> print u"4-12\u4e2a\u82f1\u6587\u5b57\u6bcd\u3001\u6570\u5b57\u548c\u4e0b\u5212\u7ebf"
4-12ä¸ªè±æåæ¯ãæ°ååä¸å线
</code></pre>
| 1 | 2010-01-18T03:28:26Z | [
"javascript",
"python"
] |
what is the encoding of this string,'base64' or 'utf-8'??? ,how can i get it readable | 2,083,734 | <pre><code>print "4-12\u4e2a\u82f1\u6587\u5b57\u6bcd\u3001\u6570\u5b57\u548c\u4e0b\u5212\u7ebf".decode('base64')#no
</code></pre>
<p>thanks</p>
<hr>
<p>and </p>
<p>if i have '4-12ä¸ªè±æåæ¯ãæ°ååä¸å线'</p>
<p>how can i get the string '4-12\u4e2a\u82f1\u6587\u5b57\u6bcd\u3001\u6570\u5b57\u548c\u4e0b\... | 2 | 2010-01-18T03:25:30Z | 2,083,745 | <p>That string says "4-12ä¸ªè±æåæ¯ãæ°ååä¸å线", by just typing it in to a JavaScript interpreter (in this case, the WebKit inspector).</p>
<p>It does not appear to have any base64 encoded information in it.</p>
<p>Was there something else that you wanted to know?</p>
| 1 | 2010-01-18T03:28:34Z | [
"javascript",
"python"
] |
what is the encoding of this string,'base64' or 'utf-8'??? ,how can i get it readable | 2,083,734 | <pre><code>print "4-12\u4e2a\u82f1\u6587\u5b57\u6bcd\u3001\u6570\u5b57\u548c\u4e0b\u5212\u7ebf".decode('base64')#no
</code></pre>
<p>thanks</p>
<hr>
<p>and </p>
<p>if i have '4-12ä¸ªè±æåæ¯ãæ°ååä¸å线'</p>
<p>how can i get the string '4-12\u4e2a\u82f1\u6587\u5b57\u6bcd\u3001\u6570\u5b57\u548c\u4e0b\... | 2 | 2010-01-18T03:25:30Z | 2,083,768 | <p>I guess it is python 3.x representation of unicode string.</p>
<p>In python 2.x you will need <code>u""</code> at the start of unicode string.</p>
| 1 | 2010-01-18T03:36:06Z | [
"javascript",
"python"
] |
what is the encoding of this string,'base64' or 'utf-8'??? ,how can i get it readable | 2,083,734 | <pre><code>print "4-12\u4e2a\u82f1\u6587\u5b57\u6bcd\u3001\u6570\u5b57\u548c\u4e0b\u5212\u7ebf".decode('base64')#no
</code></pre>
<p>thanks</p>
<hr>
<p>and </p>
<p>if i have '4-12ä¸ªè±æåæ¯ãæ°ååä¸å线'</p>
<p>how can i get the string '4-12\u4e2a\u82f1\u6587\u5b57\u6bcd\u3001\u6570\u5b57\u548c\u4e0b\... | 2 | 2010-01-18T03:25:30Z | 2,087,144 | <p>Your final comment:</p>
<pre><code>>>> print '4-12ä¸ªè±æåæ¯ãæ°ååä¸å线'.decode('gb2312').encode('unicode-escape')
</code></pre>
<p>would only work if your source file is saved in gb2312 encoding. Make sure you declare that at the top of your file, then you can use Unicode strings:</p>
<p... | 0 | 2010-01-18T15:39:36Z | [
"javascript",
"python"
] |
How to retry after exception in python? | 2,083,987 | <p>I have a loop starting with <code>for i in range(0, 100)</code>. Normally it runs correctly, but sometimes it fails due to network conditions. Currently I have it set so that on failure, it will <code>continue</code> in the except clause (continue on to the next number for <code>i</code>).</p>
<p>Is it possible for... | 85 | 2010-01-18T05:00:19Z | 2,083,996 | <p>Do a <code>while True</code> inside your for loop, put your <code>try</code> code inside, and break from that <code>while</code> loop only when your code succeeds.</p>
<pre><code>for i in range(0,100):
while True:
try:
# do stuff
except SomeSpecificException:
continue
... | 145 | 2010-01-18T05:02:20Z | [
"python"
] |
How to retry after exception in python? | 2,083,987 | <p>I have a loop starting with <code>for i in range(0, 100)</code>. Normally it runs correctly, but sometimes it fails due to network conditions. Currently I have it set so that on failure, it will <code>continue</code> in the except clause (continue on to the next number for <code>i</code>).</p>
<p>Is it possible for... | 85 | 2010-01-18T05:00:19Z | 2,084,028 | <p>The clearest way would be to explicitly set <code>i</code>. For example:</p>
<pre><code>i = 0
while i < 100:
i += 1
try:
# do stuff
except MyException:
continue
</code></pre>
| 3 | 2010-01-18T05:13:47Z | [
"python"
] |
How to retry after exception in python? | 2,083,987 | <p>I have a loop starting with <code>for i in range(0, 100)</code>. Normally it runs correctly, but sometimes it fails due to network conditions. Currently I have it set so that on failure, it will <code>continue</code> in the except clause (continue on to the next number for <code>i</code>).</p>
<p>Is it possible for... | 85 | 2010-01-18T05:00:19Z | 2,085,009 | <p>increment your loop variable only when the try clause succeeds</p>
| -9 | 2010-01-18T09:34:27Z | [
"python"
] |
How to retry after exception in python? | 2,083,987 | <p>I have a loop starting with <code>for i in range(0, 100)</code>. Normally it runs correctly, but sometimes it fails due to network conditions. Currently I have it set so that on failure, it will <code>continue</code> in the except clause (continue on to the next number for <code>i</code>).</p>
<p>Is it possible for... | 85 | 2010-01-18T05:00:19Z | 4,047,051 | <p>The more "functional" approach without using those ugly while loops:</p>
<pre><code>def tryAgain(retries=0):
if retries > 10: return
try:
# Do stuff
except:
retries+=1
tryAgain(retries)
tryAgain()
</code></pre>
| 3 | 2010-10-28T20:46:42Z | [
"python"
] |
How to retry after exception in python? | 2,083,987 | <p>I have a loop starting with <code>for i in range(0, 100)</code>. Normally it runs correctly, but sometimes it fails due to network conditions. Currently I have it set so that on failure, it will <code>continue</code> in the except clause (continue on to the next number for <code>i</code>).</p>
<p>Is it possible for... | 85 | 2010-01-18T05:00:19Z | 6,354,713 | <p>There is something similar in the <a href="http://wiki.python.org/moin/PythonDecoratorLibrary#Retry" rel="nofollow">Python Decorator Library</a>.</p>
<p>Please bear in mind that it does not test for exceptions, but the return value. It retries until the decorated function returns True.</p>
<p>A slightly modified v... | 3 | 2011-06-15T07:58:16Z | [
"python"
] |
How to retry after exception in python? | 2,083,987 | <p>I have a loop starting with <code>for i in range(0, 100)</code>. Normally it runs correctly, but sometimes it fails due to network conditions. Currently I have it set so that on failure, it will <code>continue</code> in the except clause (continue on to the next number for <code>i</code>).</p>
<p>Is it possible for... | 85 | 2010-01-18T05:00:19Z | 7,663,441 | <p>I prefer to limit the number of retries, so that if there's a problem with that specific item you will eventually continue onto the next one, thus:</p>
<pre><code>for i in range(100):
for attempt in range(10):
try:
# do thing
except:
# perhaps reconnect, etc.
else:
break
else:
... | 63 | 2011-10-05T15:03:37Z | [
"python"
] |
How to retry after exception in python? | 2,083,987 | <p>I have a loop starting with <code>for i in range(0, 100)</code>. Normally it runs correctly, but sometimes it fails due to network conditions. Currently I have it set so that on failure, it will <code>continue</code> in the except clause (continue on to the next number for <code>i</code>).</p>
<p>Is it possible for... | 85 | 2010-01-18T05:00:19Z | 25,912,659 | <p>The <a href="https://pypi.python.org/pypi/retrying">retrying package</a> is a nice way to retry a block of code on failure.</p>
<p>For example:</p>
<pre><code>@retry(wait_random_min=1000, wait_random_max=2000)
def wait_random_1_to_2_s():
print "Randomly wait 1 to 2 seconds between retries"
</code></pre>
| 25 | 2014-09-18T12:29:43Z | [
"python"
] |
How to retry after exception in python? | 2,083,987 | <p>I have a loop starting with <code>for i in range(0, 100)</code>. Normally it runs correctly, but sometimes it fails due to network conditions. Currently I have it set so that on failure, it will <code>continue</code> in the except clause (continue on to the next number for <code>i</code>).</p>
<p>Is it possible for... | 85 | 2010-01-18T05:00:19Z | 27,300,194 | <p>A generic solution with a timeout:</p>
<pre><code>import time
def onerror_retry(exception, callback, timeout=2, timedelta=.1):
end_time = time.time() + timeout
while True:
try:
yield callback
break
except exception:
if time.time() > end_time:
... | 2 | 2014-12-04T17:26:13Z | [
"python"
] |
How to retry after exception in python? | 2,083,987 | <p>I have a loop starting with <code>for i in range(0, 100)</code>. Normally it runs correctly, but sometimes it fails due to network conditions. Currently I have it set so that on failure, it will <code>continue</code> in the except clause (continue on to the next number for <code>i</code>).</p>
<p>Is it possible for... | 85 | 2010-01-18T05:00:19Z | 34,456,161 | <p>Here's my idea on how to fix this:</p>
<pre><code>j = 19
def calc(y):
global j
try:
j = j + 8 - y
x = int(y/j) # this will eventually raise DIV/0 when j=0
print("i = ", str(y), " j = ", str(j), " x = ", str(x))
except:
j = j + 1 # when the exception happens, increment... | 1 | 2015-12-24T17:35:50Z | [
"python"
] |
How to retry after exception in python? | 2,083,987 | <p>I have a loop starting with <code>for i in range(0, 100)</code>. Normally it runs correctly, but sometimes it fails due to network conditions. Currently I have it set so that on failure, it will <code>continue</code> in the except clause (continue on to the next number for <code>i</code>).</p>
<p>Is it possible for... | 85 | 2010-01-18T05:00:19Z | 34,885,906 | <p>Here is a solution similar to others, but it will raise the exception if it doesn't succeed in the prescribed number or retries.</p>
<pre><code>tries = 3
for i in range(tries):
try:
do_the_thing()
except KeyError as e:
if i < tries - 1: # i is zero indexed
continue
els... | 3 | 2016-01-19T20:01:18Z | [
"python"
] |
How to retry after exception in python? | 2,083,987 | <p>I have a loop starting with <code>for i in range(0, 100)</code>. Normally it runs correctly, but sometimes it fails due to network conditions. Currently I have it set so that on failure, it will <code>continue</code> in the except clause (continue on to the next number for <code>i</code>).</p>
<p>Is it possible for... | 85 | 2010-01-18T05:00:19Z | 39,249,035 | <p>Using while and a counter:</p>
<pre><code>count = 1
while count <= 3: # try 3 times
try:
# do_the_logic()
break
except SomeSpecificException as e:
# If trying 3rd time and still error??
# Just throw the error- we don't have anything to hide :)
if count == 3:
... | 1 | 2016-08-31T11:57:34Z | [
"python"
] |
How to retry after exception in python? | 2,083,987 | <p>I have a loop starting with <code>for i in range(0, 100)</code>. Normally it runs correctly, but sometimes it fails due to network conditions. Currently I have it set so that on failure, it will <code>continue</code> in the except clause (continue on to the next number for <code>i</code>).</p>
<p>Is it possible for... | 85 | 2010-01-18T05:00:19Z | 39,249,214 | <p>Using recursion</p>
<pre><code>for i in range(100):
def do():
try:
## Network related scripts
except SpecificException as ex:
do()
do() ## invoke do() whenever required inside this loop
</code></pre>
| 1 | 2016-08-31T12:06:23Z | [
"python"
] |
Checking for value within same type in python | 2,084,017 | <pre><code>a = 0
if a == False:
print a
</code></pre>
<p>in php I can say:</p>
<pre><code>$a = 0;
if $a === false {
echo $a;
}
</code></pre>
<p>The triple === in php check for the value within the same type, thus making the integer 0 not be read as a boolean value False
How can I do this in python? I would li... | 4 | 2010-01-18T05:10:40Z | 2,084,025 | <p><code>type()</code> will give you the type of an object. But if you're worried about distinguishing between <code>0</code> and <code>False</code> then perhaps you should use <code>None</code> instead.</p>
| 0 | 2010-01-18T05:12:50Z | [
"python"
] |
Checking for value within same type in python | 2,084,017 | <pre><code>a = 0
if a == False:
print a
</code></pre>
<p>in php I can say:</p>
<pre><code>$a = 0;
if $a === false {
echo $a;
}
</code></pre>
<p>The triple === in php check for the value within the same type, thus making the integer 0 not be read as a boolean value False
How can I do this in python? I would li... | 4 | 2010-01-18T05:10:40Z | 2,084,035 | <p>You should use the <a href="http://docs.python.org/library/operator.html#operator.is_" rel="nofollow"><code>is</code></a> keyword in that case. It's the identity operator, the same as <code>===</code> in PHP.</p>
<pre><code>>>> a = 0
>>> if a is False:
... print a
...
>>>
</code></pr... | 5 | 2010-01-18T05:16:51Z | [
"python"
] |
How would I discover the memory used by an application through a python script? | 2,084,063 | <p>Recently I've found myself testing an aplication in Froglogic's Squish, using Python to create test scripts. Just the other day, the question of how much memory the program is using has come up, and I've found myself unable to answer it.
It seems reasonable to assume that there's a way to query the os (windows 7) AP... | 1 | 2010-01-18T05:30:36Z | 2,084,070 | <p>In command line: <code>tasklist /FO LIST</code> and parse the results?</p>
<p>Sorry, I don't know a Pythonic way. =P</p>
| -1 | 2010-01-18T05:34:19Z | [
"python",
"windows-7",
"memory-management"
] |
How would I discover the memory used by an application through a python script? | 2,084,063 | <p>Recently I've found myself testing an aplication in Froglogic's Squish, using Python to create test scripts. Just the other day, the question of how much memory the program is using has come up, and I've found myself unable to answer it.
It seems reasonable to assume that there's a way to query the os (windows 7) AP... | 1 | 2010-01-18T05:30:36Z | 2,084,075 | <p>this answer has some code (for windows and unix):</p>
<p><a href="http://stackoverflow.com/questions/938733/python-total-memory-used/938800#938800">http://stackoverflow.com/questions/938733/python-total-memory-used/938800#938800</a></p>
<p>on win, you are checking <code>Win32_PerfRawData_PerfProc_Process</code> an... | 2 | 2010-01-18T05:35:35Z | [
"python",
"windows-7",
"memory-management"
] |
How would I discover the memory used by an application through a python script? | 2,084,063 | <p>Recently I've found myself testing an aplication in Froglogic's Squish, using Python to create test scripts. Just the other day, the question of how much memory the program is using has come up, and I've found myself unable to answer it.
It seems reasonable to assume that there's a way to query the os (windows 7) AP... | 1 | 2010-01-18T05:30:36Z | 2,175,363 | <p>Remember that Squish allows remote testing of the application. A system parameter queried via Python directly will only apply to the case of local testing.</p>
<p>An approach that works in either case is to call the currentApplicationContext() function that will give you a handle to the Application Under Test. It h... | 0 | 2010-02-01T08:09:17Z | [
"python",
"windows-7",
"memory-management"
] |
Create a .csv file with values from a Python list | 2,084,069 | <p>I am trying to create a .csv file with the values from a Python list. When I print the values in the list they are all unicode (?), i.e. they look something like this </p>
<pre><code>[u'value 1', u'value 2', ...]
</code></pre>
<p>If I iterate through the values in the list i.e. <code>for v in mylist: print v</code... | 64 | 2010-01-18T05:34:08Z | 2,084,083 | <p>You could use the string.join method in this case.</p>
<p>Split over a few of lines for clarity - here's an interactive session</p>
<pre><code>>>> a = ['a','b','c']
>>> first = '", "'.join(a)
>>> second = '"%s"' % first
>>> print second
"a", "b", "c"
</code></pre>
<p>Or as a si... | 6 | 2010-01-18T05:38:18Z | [
"python",
"csv",
"xlrd"
] |
Create a .csv file with values from a Python list | 2,084,069 | <p>I am trying to create a .csv file with the values from a Python list. When I print the values in the list they are all unicode (?), i.e. they look something like this </p>
<pre><code>[u'value 1', u'value 2', ...]
</code></pre>
<p>If I iterate through the values in the list i.e. <code>for v in mylist: print v</code... | 64 | 2010-01-18T05:34:08Z | 2,084,135 | <pre><code>import csv
myfile = open(..., 'wb')
wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
wr.writerow(mylist)
</code></pre>
| 87 | 2010-01-18T05:53:25Z | [
"python",
"csv",
"xlrd"
] |
Create a .csv file with values from a Python list | 2,084,069 | <p>I am trying to create a .csv file with the values from a Python list. When I print the values in the list they are all unicode (?), i.e. they look something like this </p>
<pre><code>[u'value 1', u'value 2', ...]
</code></pre>
<p>If I iterate through the values in the list i.e. <code>for v in mylist: print v</code... | 64 | 2010-01-18T05:34:08Z | 2,084,136 | <p>Use python's <code>csv</code> module for reading and writing comma or tab-delimited files. The csv module is preferred because it gives you good control over quoting.</p>
<p>For example, here is the worked example for you:</p>
<pre><code>import csv
data = ["value %d" % i for i in range(1,4)]
out = csv.writer(open... | 10 | 2010-01-18T05:53:30Z | [
"python",
"csv",
"xlrd"
] |
Create a .csv file with values from a Python list | 2,084,069 | <p>I am trying to create a .csv file with the values from a Python list. When I print the values in the list they are all unicode (?), i.e. they look something like this </p>
<pre><code>[u'value 1', u'value 2', ...]
</code></pre>
<p>If I iterate through the values in the list i.e. <code>for v in mylist: print v</code... | 64 | 2010-01-18T05:34:08Z | 21,872,153 | <p>Here is a secure version of Alex Martelli's:</p>
<pre><code>import csv
with open('filename', 'wb') as myfile:
wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
wr.writerow(mylist)
</code></pre>
| 40 | 2014-02-19T05:48:28Z | [
"python",
"csv",
"xlrd"
] |
Create a .csv file with values from a Python list | 2,084,069 | <p>I am trying to create a .csv file with the values from a Python list. When I print the values in the list they are all unicode (?), i.e. they look something like this </p>
<pre><code>[u'value 1', u'value 2', ...]
</code></pre>
<p>If I iterate through the values in the list i.e. <code>for v in mylist: print v</code... | 64 | 2010-01-18T05:34:08Z | 28,026,000 | <p>you should use the CSV module for sure , but the chances are , you need to write unicode . For those Who need to write unicode , this is the class from example page , that you can use as a util module: </p>
<pre><code>import csv, codecs, cStringIO
class UTF8Recoder:
"""
Iterator that reads an encoded strea... | 1 | 2015-01-19T13:41:33Z | [
"python",
"csv",
"xlrd"
] |
Create a .csv file with values from a Python list | 2,084,069 | <p>I am trying to create a .csv file with the values from a Python list. When I print the values in the list they are all unicode (?), i.e. they look something like this </p>
<pre><code>[u'value 1', u'value 2', ...]
</code></pre>
<p>If I iterate through the values in the list i.e. <code>for v in mylist: print v</code... | 64 | 2010-01-18T05:34:08Z | 30,219,300 | <p>The best option I've found was using the <code>savetxt</code> from the <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.savetxt.html" rel="nofollow"><code>numpy</code> module</a>:</p>
<pre><code>import numpy as np
np.savetxt("file_name.csv", data1, delimiter=",", fmt='%s', header=header)
</code></... | 4 | 2015-05-13T15:30:05Z | [
"python",
"csv",
"xlrd"
] |
Create a .csv file with values from a Python list | 2,084,069 | <p>I am trying to create a .csv file with the values from a Python list. When I print the values in the list they are all unicode (?), i.e. they look something like this </p>
<pre><code>[u'value 1', u'value 2', ...]
</code></pre>
<p>If I iterate through the values in the list i.e. <code>for v in mylist: print v</code... | 64 | 2010-01-18T05:34:08Z | 36,589,930 | <p>Here is another solution that does not require the <code>csv</code> module.</p>
<pre><code>print ', '.join(['"'+i+'"' for i in myList])
</code></pre>
<p>Example :</p>
<pre><code>>>> myList = [u'value 1', u'value 2', u'value 3']
>>> print ', '.join(['"'+i+'"' for i in myList])
"value 1", "value 2... | 0 | 2016-04-13T06:06:53Z | [
"python",
"csv",
"xlrd"
] |
Windows process management using Python | 2,084,111 | <p>I need a script that check if a particular process is running and return something if not found. I know that this can be done using subprocess, but is there a simpler way to do it?</p>
| 3 | 2010-01-18T05:46:32Z | 2,084,186 | <p>On Windows, you can use WMI:</p>
<pre><code>import win32com.client
def find_process(name):
objWMIService = win32com.client.Dispatch("WbemScripting.SWbemLocator")
objSWbemServices = objWMIService.ConnectServer(".", "root\cimv2")
colItems = objSWbemServices.ExecQuery(
"Select * from Win32_Proces... | 6 | 2010-01-18T06:08:05Z | [
"python",
"windows",
"process"
] |
Windows process management using Python | 2,084,111 | <p>I need a script that check if a particular process is running and return something if not found. I know that this can be done using subprocess, but is there a simpler way to do it?</p>
| 3 | 2010-01-18T05:46:32Z | 2,084,356 | <p>Take a look at: <a href="http://code.activestate.com/recipes/305279/" rel="nofollow">getting process information on windows</a></p>
| 1 | 2010-01-18T06:58:21Z | [
"python",
"windows",
"process"
] |
Windows process management using Python | 2,084,111 | <p>I need a script that check if a particular process is running and return something if not found. I know that this can be done using subprocess, but is there a simpler way to do it?</p>
| 3 | 2010-01-18T05:46:32Z | 16,519,577 | <p>For similar purposes I have used <a href="https://github.com/giampaolo/psutil" rel="nofollow">psutil</a> library. Some hints:</p>
<ul>
<li>list processes with <code>psutil.pids()</code> (<a href="http://pythonhosted.org/psutil/#psutil.pids" rel="nofollow">reference</a>)</li>
<li>inspect process information with <co... | 1 | 2013-05-13T10:13:08Z | [
"python",
"windows",
"process"
] |
Where (at which point in the code) does pyAMF client accept SSL certificate? | 2,084,292 | <p>I've set up a server listening on an SSL port. I am able to connect to it and with proper credentials I am able to access the services (echo service in the example below)</p>
<p>The code below works fine, but I don't understand <b>at which point the client accepts the certificate</b></p>
<p>Server:</p>
<pre><code... | 3 | 2010-01-18T06:40:32Z | 2,106,361 | <p>PyAMF uses <code>httplib</code> under the hood to power the remoting requests. When connecting via <code>https://</code>, <a href="http://docs.python.org/library/httplib.html#httplib.HTTPSConnection" rel="nofollow">httplib.HTTPSConnection</a> is used as the <code>connection</code> attribute to the <code>RemotingServ... | 2 | 2010-01-21T01:41:24Z | [
"python",
"ssl",
"certificate",
"cherrypy",
"pyamf"
] |
md5 module error | 2,084,407 | <p>I'm using an older version of PLY that uses the md5 module (among others):</p>
<pre><code>import re, types, sys, cStringIO, md5, os.path
</code></pre>
<p>... although the script runs but not without this error:</p>
<pre><code>DeprecationWarning: the md5 module is deprecated; use hashlib instead
</code></pre>
<p>... | 5 | 2010-01-18T07:13:23Z | 2,084,423 | <p>i think the warning message is quite straightforward. you need to </p>
<pre><code>
from hashlib import md5
</code></pre>
<p>or you can use python < 2.5, <a href="http://docs.python.org/library/md5.html">http://docs.python.org/library/md5.html</a></p>
| 7 | 2010-01-18T07:17:22Z | [
"python",
"module",
"md5",
"ply"
] |
md5 module error | 2,084,407 | <p>I'm using an older version of PLY that uses the md5 module (among others):</p>
<pre><code>import re, types, sys, cStringIO, md5, os.path
</code></pre>
<p>... although the script runs but not without this error:</p>
<pre><code>DeprecationWarning: the md5 module is deprecated; use hashlib instead
</code></pre>
<p>... | 5 | 2010-01-18T07:13:23Z | 2,084,445 | <p>That's not an error, that's a warning.</p>
<p>If you still insist on getting rid of it then modify the code so that it uses <a href="http://docs.python.org/library/hashlib.html" rel="nofollow"><code>hashlib</code></a> instead.</p>
| 2 | 2010-01-18T07:22:10Z | [
"python",
"module",
"md5",
"ply"
] |
md5 module error | 2,084,407 | <p>I'm using an older version of PLY that uses the md5 module (among others):</p>
<pre><code>import re, types, sys, cStringIO, md5, os.path
</code></pre>
<p>... although the script runs but not without this error:</p>
<pre><code>DeprecationWarning: the md5 module is deprecated; use hashlib instead
</code></pre>
<p>... | 5 | 2010-01-18T07:13:23Z | 2,084,462 | <p>please see the docs <a href="http://docs.python.org/library/warnings.html" rel="nofollow">here</a> , 28.5.3 gives you a way to suppress deprecate warnings. Or on the command line when you run your script, issue <code>-W ignore::DeprecationWarning</code></p>
| 0 | 2010-01-18T07:24:35Z | [
"python",
"module",
"md5",
"ply"
] |
md5 module error | 2,084,407 | <p>I'm using an older version of PLY that uses the md5 module (among others):</p>
<pre><code>import re, types, sys, cStringIO, md5, os.path
</code></pre>
<p>... although the script runs but not without this error:</p>
<pre><code>DeprecationWarning: the md5 module is deprecated; use hashlib instead
</code></pre>
<p>... | 5 | 2010-01-18T07:13:23Z | 2,084,994 | <p>i think the warning is ok,still you can use the md5 module,or else hashlib module contains md5 class</p>
<pre><code>import hashlib
a=hashlib.md5("foo")
print a.hexdigest()
</code></pre>
<p>this would print the md5 checksum of the string "foo"</p>
| 0 | 2010-01-18T09:31:12Z | [
"python",
"module",
"md5",
"ply"
] |
md5 module error | 2,084,407 | <p>I'm using an older version of PLY that uses the md5 module (among others):</p>
<pre><code>import re, types, sys, cStringIO, md5, os.path
</code></pre>
<p>... although the script runs but not without this error:</p>
<pre><code>DeprecationWarning: the md5 module is deprecated; use hashlib instead
</code></pre>
<p>... | 5 | 2010-01-18T07:13:23Z | 2,087,118 | <p>As mentioned, the warning can be silenced. And hashlib.md5(my_string) should do the same as md5.md5(my_string).</p>
<pre><code>>>> import md5
__main__:1: DeprecationWarning: the md5 module is deprecated; use hashlib instead
>>> import hashlib
>>> s = 'abc'
>>> m = md5.new(s)
>... | 2 | 2010-01-18T15:36:30Z | [
"python",
"module",
"md5",
"ply"
] |
md5 module error | 2,084,407 | <p>I'm using an older version of PLY that uses the md5 module (among others):</p>
<pre><code>import re, types, sys, cStringIO, md5, os.path
</code></pre>
<p>... although the script runs but not without this error:</p>
<pre><code>DeprecationWarning: the md5 module is deprecated; use hashlib instead
</code></pre>
<p>... | 5 | 2010-01-18T07:13:23Z | 29,757,052 | <p>What about something like this? </p>
<pre><code>try:
import warnings
warnings.catch_warnings()
warnings.simplefilter("ignore")
import md5
except ImportError as imp_err:
raise type(imp_err), type(imp_err)("{0}{1}".format(
imp_err.message,"Custom import message"))
</code></pre>
| 0 | 2015-04-20T19:49:08Z | [
"python",
"module",
"md5",
"ply"
] |
clear terminal in python | 2,084,508 | <p>Does any standard "comes with batteries" method exist to clear the terminal screen from a python script, or do I have to go curses (the libraries, not the words) ?</p>
| 91 | 2010-01-18T07:34:58Z | 2,084,517 | <p>You could tear through the terminfo database, but the functions for doing so are in <code>curses</code> anyway.</p>
| 2 | 2010-01-18T07:37:21Z | [
"python"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.