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
Convert number to binary string
699,285
<p>Is this the best way to convert a Python number to a hex string? </p> <pre><code>number = 123456789 hex(number)[2:-1].decode('hex') </code></pre> <p>Sometimes it doesn't work and complains about Odd-length string when you do 1234567890.</p> <p>Clarification:</p> <p>I am going from int to hex.</p> <p>Also, I nee...
3
2009-03-30T22:26:23Z
6,222,300
<pre><code>'{0:b}'.format( number ) </code></pre> <p>refer to <a href="http://docs.python.org/library/string.html" rel="nofollow">http://docs.python.org/library/string.html</a></p>
1
2011-06-03T02:05:45Z
[ "python", "binary", "hex" ]
Suppress output in Python calls to executables
699,325
<p>I have a binary named <code>A</code> that generates output when called. If I call it from a Bash shell, most of the output is suppressed by <code>A &gt; /dev/null</code>. All of the output is suppressed by <code>A &amp;&gt; /dev/null</code></p> <p>I have a python script named <code>B</code> that needs to call <code...
44
2009-03-30T22:39:14Z
699,342
<p>As the os.system() docs mention, use the <a href="http://docs.python.org/library/subprocess.html">subprocess</a> module, and, if you like, set stdout=open(os.devnull, 'w') (and perhaps the same for stderr) when you open the subprocess.</p>
8
2009-03-30T22:44:20Z
[ "python", "redirect" ]
Suppress output in Python calls to executables
699,325
<p>I have a binary named <code>A</code> that generates output when called. If I call it from a Bash shell, most of the output is suppressed by <code>A &gt; /dev/null</code>. All of the output is suppressed by <code>A &amp;&gt; /dev/null</code></p> <p>I have a python script named <code>B</code> that needs to call <code...
44
2009-03-30T22:39:14Z
699,365
<p>If you have Python 2.4, you can use <a href="http://docs.python.org/library/subprocess.html">the subprocess module</a>:</p> <pre><code>&gt;&gt;&gt; import subprocess &gt;&gt;&gt; s = subprocess.Popen(['cowsay', 'hello'], \ stderr=subprocess.STDOUT, stdout=subprocess.PIPE).communicate()[0] &gt;&gt;&gt; print s...
57
2009-03-30T22:49:56Z
[ "python", "redirect" ]
Suppress output in Python calls to executables
699,325
<p>I have a binary named <code>A</code> that generates output when called. If I call it from a Bash shell, most of the output is suppressed by <code>A &gt; /dev/null</code>. All of the output is suppressed by <code>A &amp;&gt; /dev/null</code></p> <p>I have a python script named <code>B</code> that needs to call <code...
44
2009-03-30T22:39:14Z
699,374
<pre><code>import os import subprocess command = ["executable", "argument_1", "argument_2"] with open(os.devnull, "w") as fnull: result = subprocess.call(command, stdout = fnull, stderr = fnull) </code></pre> <p>If the command doesn't have any arguments, you can just provide it as a simple string.</p> <p>If you...
102
2009-03-30T22:53:27Z
[ "python", "redirect" ]
Suppress output in Python calls to executables
699,325
<p>I have a binary named <code>A</code> that generates output when called. If I call it from a Bash shell, most of the output is suppressed by <code>A &gt; /dev/null</code>. All of the output is suppressed by <code>A &amp;&gt; /dev/null</code></p> <p>I have a python script named <code>B</code> that needs to call <code...
44
2009-03-30T22:39:14Z
1,030,604
<p>I know it's late to the game, but why not simply redirect output to /dev/null from within os.system? E.g.:</p> <pre><code>tgt_file = "./bogus.txt" os.sytem("d2u '%s' &amp;&gt; /dev/null" % tgt_file) </code></pre> <p>This seems to work for those occasions when you don't want to deal with subprocess.STDOUT.</p>
1
2009-06-23T04:20:45Z
[ "python", "redirect" ]
Suppress output in Python calls to executables
699,325
<p>I have a binary named <code>A</code> that generates output when called. If I call it from a Bash shell, most of the output is suppressed by <code>A &gt; /dev/null</code>. All of the output is suppressed by <code>A &amp;&gt; /dev/null</code></p> <p>I have a python script named <code>B</code> that needs to call <code...
44
2009-03-30T22:39:14Z
2,728,111
<p>If your search engine lead you to this old question (like me), be aware that using PIPE may lead to <strong>deadlocks</strong>. Indeed, because pipes are buffered, you can write a certain number of bytes in a pipe, even if no one read it. However the size of buffer is finite. And consequently if your program A has a...
12
2010-04-28T09:15:37Z
[ "python", "redirect" ]
Suppress output in Python calls to executables
699,325
<p>I have a binary named <code>A</code> that generates output when called. If I call it from a Bash shell, most of the output is suppressed by <code>A &gt; /dev/null</code>. All of the output is suppressed by <code>A &amp;&gt; /dev/null</code></p> <p>I have a python script named <code>B</code> that needs to call <code...
44
2009-03-30T22:39:14Z
5,802,644
<p>I use:</p> <pre><code>call(command, stderr=subprocess.PIPE, stdout=subprocess.PIPE) </code></pre> <p>where command is the string of the command + arguments</p> <p>For this to work you must import subprocess</p>
0
2011-04-27T10:30:45Z
[ "python", "redirect" ]
Suppress output in Python calls to executables
699,325
<p>I have a binary named <code>A</code> that generates output when called. If I call it from a Bash shell, most of the output is suppressed by <code>A &gt; /dev/null</code>. All of the output is suppressed by <code>A &amp;&gt; /dev/null</code></p> <p>I have a python script named <code>B</code> that needs to call <code...
44
2009-03-30T22:39:14Z
6,396,573
<p>If you need to just capture STDOUT, doesn't assigning it to a variable do this? For example:</p> <pre><code>megabyte='' # Create a 1 MiB string of NULL characters. for i in range(1048576): megabyte += '\0' fh=open('zero.bin','w') # Write an 8 GiB file. for i in range(8192): print(i) # Suppress output o...
0
2011-06-18T14:06:45Z
[ "python", "redirect" ]
Suppress output in Python calls to executables
699,325
<p>I have a binary named <code>A</code> that generates output when called. If I call it from a Bash shell, most of the output is suppressed by <code>A &gt; /dev/null</code>. All of the output is suppressed by <code>A &amp;&gt; /dev/null</code></p> <p>I have a python script named <code>B</code> that needs to call <code...
44
2009-03-30T22:39:14Z
7,594,585
<p>In Python 3.3 and higher, <code>subprocess</code> supports <a href="http://docs.python.org/3.3/library/subprocess.html#subprocess.DEVNULL">an option for redirecting to <code>/dev/null</code></a>. To use it, when calling <code>.Popen</code> and friends, specify <code>stdout=subprocess.DEVNULL, stderr=subprocess.DEVNU...
21
2011-09-29T08:37:55Z
[ "python", "redirect" ]
Suppress output in Python calls to executables
699,325
<p>I have a binary named <code>A</code> that generates output when called. If I call it from a Bash shell, most of the output is suppressed by <code>A &gt; /dev/null</code>. All of the output is suppressed by <code>A &amp;&gt; /dev/null</code></p> <p>I have a python script named <code>B</code> that needs to call <code...
44
2009-03-30T22:39:14Z
17,251,275
<p>If you do not want to wait for the command to complete, such as starting a backup task, another option is to pass it through bash, doing which allows the redirect to operate normally.</p> <p>For example, starting a sound file using aplay:</p> <pre><code>import os def PlaySound(filename): command = 'bash -c "a...
0
2013-06-22T13:26:36Z
[ "python", "redirect" ]
What's the best way to tell if a Python program has anything to read from stdin?
699,390
<p>I want a program to do one thing if executed like this:</p> <pre><code>cat something | my_program.py </code></pre> <p>and do another thing if run like this</p> <pre><code>my_program.py </code></pre> <p>But if I read from stdin, then it will wait for user input, so I want to see if there is anything to read befor...
23
2009-03-30T22:58:26Z
699,440
<p>I do not know the Python commands off the top of my head, but you should be able to do something with poll or select to look for data ready to read on standard input.</p> <p>That might be Unix OS specific and different on Windows Python.</p>
-2
2009-03-30T23:13:45Z
[ "python" ]
What's the best way to tell if a Python program has anything to read from stdin?
699,390
<p>I want a program to do one thing if executed like this:</p> <pre><code>cat something | my_program.py </code></pre> <p>and do another thing if run like this</p> <pre><code>my_program.py </code></pre> <p>But if I read from stdin, then it will wait for user input, so I want to see if there is anything to read befor...
23
2009-03-30T22:58:26Z
699,446
<p>If you want to detect if someone is piping data into your program, or running it interactively you can use isatty to see if stdin is a terminal:</p> <pre><code>$ python -c 'import sys; print sys.stdin.isatty()' True $ echo | python -c 'import sys; print sys.stdin.isatty()' False </code></pre>
49
2009-03-30T23:16:13Z
[ "python" ]
What's the best way to tell if a Python program has anything to read from stdin?
699,390
<p>I want a program to do one thing if executed like this:</p> <pre><code>cat something | my_program.py </code></pre> <p>and do another thing if run like this</p> <pre><code>my_program.py </code></pre> <p>But if I read from stdin, then it will wait for user input, so I want to see if there is anything to read befor...
23
2009-03-30T22:58:26Z
699,459
<p>Bad news. From a Unix command-line perspective those two invocations of your program <em>are</em> identical.</p> <p>Unix can't easily distinguish them. What you're asking for isn't really sensible, and you need to think of another way of using your program.</p> <p>In the case where it's not in a pipeline, what's...
2
2009-03-30T23:22:20Z
[ "python" ]
What's the best way to tell if a Python program has anything to read from stdin?
699,390
<p>I want a program to do one thing if executed like this:</p> <pre><code>cat something | my_program.py </code></pre> <p>and do another thing if run like this</p> <pre><code>my_program.py </code></pre> <p>But if I read from stdin, then it will wait for user input, so I want to see if there is anything to read befor...
23
2009-03-30T22:58:26Z
699,772
<p>You want the select module (<code>man select</code> on unix) It will allow you to test if there is anything readable on stdin. Note that select won't work on Window with file objects. But from your pipe-laden question I'm assuming you're on a unix based os :)</p> <p><a href="http://docs.python.org/library/select.ht...
6
2009-03-31T02:12:08Z
[ "python" ]
Python/Django: Creating a simpler list from values_list()
699,462
<p>Consider:</p> <pre><code>&gt;&gt;&gt;jr.operators.values_list('id') [(1,), (2,), (3,)] </code></pre> <p>How does one simplify further to:</p> <pre><code>['1', '2', '3'] </code></pre> <p>The purpose:</p> <pre><code>class ActivityForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(Activi...
17
2009-03-30T23:24:00Z
699,469
<p>You can use a list comprehension:</p> <pre> >>> mylist = [(1,), (2,), (3,)] >>> [str(x[0]) for x in mylist] ['1', '2', '3'] </pre>
0
2009-03-30T23:26:22Z
[ "python", "django" ]
Python/Django: Creating a simpler list from values_list()
699,462
<p>Consider:</p> <pre><code>&gt;&gt;&gt;jr.operators.values_list('id') [(1,), (2,), (3,)] </code></pre> <p>How does one simplify further to:</p> <pre><code>['1', '2', '3'] </code></pre> <p>The purpose:</p> <pre><code>class ActivityForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(Activi...
17
2009-03-30T23:24:00Z
699,471
<p>Something like this?</p> <pre><code>x = [(1,), (2,), (3,)] y = [str(i[0]) for i in x] ['1', '2', '3'] </code></pre>
0
2009-03-30T23:27:07Z
[ "python", "django" ]
Python/Django: Creating a simpler list from values_list()
699,462
<p>Consider:</p> <pre><code>&gt;&gt;&gt;jr.operators.values_list('id') [(1,), (2,), (3,)] </code></pre> <p>How does one simplify further to:</p> <pre><code>['1', '2', '3'] </code></pre> <p>The purpose:</p> <pre><code>class ActivityForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(Activi...
17
2009-03-30T23:24:00Z
699,472
<p>Use the <code>flat=True</code> construct of the django queryset: <a href="https://docs.djangoproject.com/en/dev/ref/models/querysets/#django.db.models.query.QuerySet.values_list">https://docs.djangoproject.com/en/dev/ref/models/querysets/#django.db.models.query.QuerySet.values_list</a></p> <p>From the example in th...
56
2009-03-30T23:27:40Z
[ "python", "django" ]
Python/Django: Creating a simpler list from values_list()
699,462
<p>Consider:</p> <pre><code>&gt;&gt;&gt;jr.operators.values_list('id') [(1,), (2,), (3,)] </code></pre> <p>How does one simplify further to:</p> <pre><code>['1', '2', '3'] </code></pre> <p>The purpose:</p> <pre><code>class ActivityForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(Activi...
17
2009-03-30T23:24:00Z
32,327,721
<p>You need to do ..to get this output ['1', '2', '3']</p> <p><code>map(str, Entry.objects.values_list('id', flat=True).order_by('id'))</code></p>
2
2015-09-01T09:11:52Z
[ "python", "django" ]
Python HTML sanitizer / scrubber / filter
699,468
<p>I'm looking for a module that will remove any HTML tags from a string that are not found in a whitelist.</p>
60
2009-03-30T23:25:29Z
699,483
<p>Here's a simple solution using <a href="http://www.crummy.com/software/BeautifulSoup/" rel="nofollow">BeautifulSoup</a>:</p> <pre><code>from bs4 import BeautifulSoup VALID_TAGS = ['strong', 'em', 'p', 'ul', 'li', 'br'] def sanitize_html(value): soup = BeautifulSoup(value) for tag in soup.findAll(True): ...
40
2009-03-30T23:35:40Z
[ "python", "html", "filter" ]
Python HTML sanitizer / scrubber / filter
699,468
<p>I'm looking for a module that will remove any HTML tags from a string that are not found in a whitelist.</p>
60
2009-03-30T23:25:29Z
812,785
<p>The above solutions via Beautiful Soup will not work. You might be able to hack something with Beautiful Soup above and beyond them, because Beautiful Soup provides access to the parse tree. In a while, I think I'll try to solve the problem properly, but it's a week-long project or so, and I don't have a free week s...
34
2009-05-01T19:05:45Z
[ "python", "html", "filter" ]
Python HTML sanitizer / scrubber / filter
699,468
<p>I'm looking for a module that will remove any HTML tags from a string that are not found in a whitelist.</p>
60
2009-03-30T23:25:29Z
812,865
<p>Here is what i use in my own project. The acceptable_elements/attributes come from <a href="http://pythonhosted.org/feedparser/html-sanitization.html">feedparser</a> and BeautifulSoup does the work.</p> <pre><code>from BeautifulSoup import BeautifulSoup acceptable_elements = ['a', 'abbr', 'acronym', 'address', 'ar...
24
2009-05-01T19:26:54Z
[ "python", "html", "filter" ]
Python HTML sanitizer / scrubber / filter
699,468
<p>I'm looking for a module that will remove any HTML tags from a string that are not found in a whitelist.</p>
60
2009-03-30T23:25:29Z
2,702,587
<p>Use <a href="http://lxml.de/lxmlhtml.html#cleaning-up-html"><code>lxml.html.clean</code></a>! It's VERY easy!</p> <pre><code>from lxml.html.clean import clean_html print clean_html(html) </code></pre> <p>Suppose the following html:</p> <pre><code>html = '''\ &lt;html&gt; &lt;head&gt; &lt;script type="text/jav...
50
2010-04-23T23:43:24Z
[ "python", "html", "filter" ]
Python HTML sanitizer / scrubber / filter
699,468
<p>I'm looking for a module that will remove any HTML tags from a string that are not found in a whitelist.</p>
60
2009-03-30T23:25:29Z
4,633,880
<p>I prefer the <code>lxml.html.clean</code> solution, like <a href="http://stackoverflow.com/users/17160/nosklo">nosklo</a> <a href="http://stackoverflow.com/questions/699468/python-html-sanitizer-scrubber-filter/2702587#2702587">points out</a>. Here's to also remove some empty tags:</p> <pre><code>from lxml import e...
1
2011-01-08T12:38:25Z
[ "python", "html", "filter" ]
Python HTML sanitizer / scrubber / filter
699,468
<p>I'm looking for a module that will remove any HTML tags from a string that are not found in a whitelist.</p>
60
2009-03-30T23:25:29Z
5,246,109
<p>I modified <a href="http://stackoverflow.com/users/73049/bryan">Bryan</a>'s <a href="http://stackoverflow.com/questions/699468/python-html-sanitizer-scrubber-filter/699483#699483">solution with BeautifulSoup</a> to address the <a href="http://stackoverflow.com/questions/699468/python-html-sanitizer-scrubber-filter/8...
10
2011-03-09T12:56:43Z
[ "python", "html", "filter" ]
Python HTML sanitizer / scrubber / filter
699,468
<p>I'm looking for a module that will remove any HTML tags from a string that are not found in a whitelist.</p>
60
2009-03-30T23:25:29Z
14,927,866
<p>I use this:</p> <p><a href="https://github.com/dcollien/FilterHTML" rel="nofollow">FilterHTML</a></p> <p>It's simple and lets you define a well-controlled white-list, scrubs URLs and even matches attribute values against regex or have custom filtering functions per attribute.</p> <p>If used carefully it could be ...
2
2013-02-18T00:37:24Z
[ "python", "html", "filter" ]
Python HTML sanitizer / scrubber / filter
699,468
<p>I'm looking for a module that will remove any HTML tags from a string that are not found in a whitelist.</p>
60
2009-03-30T23:25:29Z
15,536,649
<p>You could use <a href="http://code.google.com/p/html5lib/" rel="nofollow">html5lib</a>, which uses a whitelist to sanitize.</p> <p>An example:</p> <pre><code>import html5lib from html5lib import sanitizer, treebuilders, treewalkers, serializer def clean_html(buf): """Cleans HTML of dangerous tags and content....
2
2013-03-20T23:21:02Z
[ "python", "html", "filter" ]
Python HTML sanitizer / scrubber / filter
699,468
<p>I'm looking for a module that will remove any HTML tags from a string that are not found in a whitelist.</p>
60
2009-03-30T23:25:29Z
19,605,146
<p><a href="https://github.com/jsocol/bleach">Bleach</a> does better with more useful options. It's built on html5lib and ready for production.</p> <p>Check this <a href="http://bleach.readthedocs.org/en/latest/clean.html">documents</a>.</p>
19
2013-10-26T09:41:36Z
[ "python", "html", "filter" ]
Is it possible to create a class that represents another type in Python, when directly referenced?
699,510
<p>So if I have a class like:</p> <pre><code>CustomVal </code></pre> <p>I want to be able to represent a literal value, so like setting it in the constructor:</p> <pre><code>val = CustomVal ( 5 ) val.SomeDefaultIntMethod </code></pre> <p>Basically I want the CustomVal to represent whatever is specified in the cons...
1
2009-03-30T23:52:10Z
699,527
<p>The usual way to wrap an object in Python is to override <code>__getattr__</code> in your class:</p> <pre><code>class CustomVal(object): def __init__(self, value): self.value = value def __getattr__(self, attr): return getattr(self.value, attr) </code></pre> <p>So then you can do</p> <pre...
7
2009-03-30T23:59:48Z
[ "python", "class", "object" ]
Is it possible to create a class that represents another type in Python, when directly referenced?
699,510
<p>So if I have a class like:</p> <pre><code>CustomVal </code></pre> <p>I want to be able to represent a literal value, so like setting it in the constructor:</p> <pre><code>val = CustomVal ( 5 ) val.SomeDefaultIntMethod </code></pre> <p>Basically I want the CustomVal to represent whatever is specified in the cons...
1
2009-03-30T23:52:10Z
699,531
<p>You just might be overthinking this... You can put anything you want into your <code>val</code>, then call whatever method of the object you want:</p> <pre><code>&gt;&gt;&gt; val = ThingaMoBob(123, {p:3.14}, flag=False) &gt;&gt;&gt; val.SomeCrazyMathod() </code></pre> <p>Am I missing something?</p>
2
2009-03-31T00:03:25Z
[ "python", "class", "object" ]
python decorators and methods
699,526
<p>New here. Also I'm (very) new to python and trying to understand the following behavior. Can someone explain to me why the two methods in this example have different output?</p> <pre><code>def map_children(method): def wrapper(self,*args,**kwargs): res = method(self,*args,**kwargs) for child i...
7
2009-03-30T23:59:12Z
699,549
<p>In the decorator, you are looping over the node's children and calling the <em>original</em>, non-recursive <code>method</code> on them</p> <pre><code>method(child, *args, **kwargs) </code></pre> <p>so you'll only go one level deep. Try replacing that line with</p> <pre><code>map_children(method)(child, *args, **...
7
2009-03-31T00:15:02Z
[ "python", "metaprogramming", "decorator" ]
navigating through different drive letters in python os.system
699,550
<p>I am having a problem with a bit of code on one windows machine but not all windows machines. i have the following code:</p> <pre><code>path = "F:/dir/" os.system(path[0:2] + " &amp;&amp; cd " + path + " &amp;&amp; git init") </code></pre> <p>On all but one of my windows systems it runs fine but on a windows 2003 ...
0
2009-03-31T00:15:04Z
699,637
<p><a href="http://docs.python.org/library/os.path.html" rel="nofollow">os.path</a> contains many usefull path manipulation functions. Probably just handling the path cleanly will resolve your problem.</p> <pre><code>&gt;&gt;&gt; import os &gt;&gt;&gt; &gt;&gt;&gt; &gt;&gt;&gt; path = "F:/dir/" &gt;&gt;&gt; &gt;&gt;&...
3
2009-03-31T00:52:25Z
[ "python", "windows", "cmd" ]
Python: Testing for unicode, and converting to time()
699,570
<p>Sometimes self.start is unicode:</p> <p>eg.</p> <pre><code>&gt;&gt;&gt;self.start u'07:30:00' </code></pre> <p>Which makes datetime.combine complain</p> <pre><code>start = datetime.combine(self.job_record.date, self.start) </code></pre> <p>How does one:</p> <ol> <li>Test for unicode?</li> <li>Convert from u'07...
1
2009-03-31T00:25:42Z
699,598
<p>Checking for unicode:</p> <pre><code>&gt;&gt;&gt; import types &gt;&gt;&gt; type(u'07:30:00') is types.UnicodeType True &gt;&gt;&gt; type('regular string') is types.UnicodeType False </code></pre> <p>Converting strings to time:</p> <pre><code>&gt;&gt;&gt; import time &gt;&gt;&gt; time.strptime(u'07:30:00', '%H:%M...
4
2009-03-31T00:36:40Z
[ "python", "django" ]
Python: Testing for unicode, and converting to time()
699,570
<p>Sometimes self.start is unicode:</p> <p>eg.</p> <pre><code>&gt;&gt;&gt;self.start u'07:30:00' </code></pre> <p>Which makes datetime.combine complain</p> <pre><code>start = datetime.combine(self.job_record.date, self.start) </code></pre> <p>How does one:</p> <ol> <li>Test for unicode?</li> <li>Convert from u'07...
1
2009-03-31T00:25:42Z
699,599
<p>Assuming that there won't be extended charset characters in '07:30:00', then use <code>str(self.start)</code>.</p> <p>If there is a possibility that the numbers in the time are charset-specific, use <code>encode()</code>, with an appropriate <code>error</code> argument specifier to convert to string.</p> <p>This m...
0
2009-03-31T00:36:46Z
[ "python", "django" ]
Python: Testing for unicode, and converting to time()
699,570
<p>Sometimes self.start is unicode:</p> <p>eg.</p> <pre><code>&gt;&gt;&gt;self.start u'07:30:00' </code></pre> <p>Which makes datetime.combine complain</p> <pre><code>start = datetime.combine(self.job_record.date, self.start) </code></pre> <p>How does one:</p> <ol> <li>Test for unicode?</li> <li>Convert from u'07...
1
2009-03-31T00:25:42Z
699,631
<p><code>datetime.combine</code> is complaining because it expects the second argument to be a <code>datetime.time</code> instance, not a string (or unicode string).</p> <p>There are a few ways to convert your string to a <code>datetime.time</code> instance. One way would be to use <code>datetime.strptime</code>:</p>...
2
2009-03-31T00:50:34Z
[ "python", "django" ]
Browser interface to command line python program
699,649
<p>I have a command line tool that I have written (in Python) that interfaces to a SQLite database (one DB per user). This program presents a lot of data to the user which can be cumbersome in a terminal.</p> <p>One option is to provide a wxPython interface, but another thought is to leverage Firefox or Webkit to prov...
0
2009-03-31T00:58:18Z
699,671
<p>The django <a href="http://docs.djangoproject.com/en/dev/ref/contrib/admin/#ref-contrib-admin" rel="nofollow">automatic admin interface</a> (you can use legacy DBs, and sqlite), or <a href="http://docs.djangoproject.com/en/dev/ref/contrib/databrowse/#ref-contrib-databrowse" rel="nofollow">databrowse</a> application ...
4
2009-03-31T01:08:15Z
[ "python", "firefox", "sqlite", "webkit" ]
Browser interface to command line python program
699,649
<p>I have a command line tool that I have written (in Python) that interfaces to a SQLite database (one DB per user). This program presents a lot of data to the user which can be cumbersome in a terminal.</p> <p>One option is to provide a wxPython interface, but another thought is to leverage Firefox or Webkit to prov...
0
2009-03-31T00:58:18Z
699,751
<p>You might also look at Qt's model/view framework. It's trivial to take a SQL result set and map it into a table view etc...</p> <p><a href="http://doc.trolltech.com/4.5/sql-tablemodel.html" rel="nofollow">http://doc.trolltech.com/4.5/sql-tablemodel.html</a></p> <p>This works quite well from PyQt4 also.</p>
1
2009-03-31T01:58:29Z
[ "python", "firefox", "sqlite", "webkit" ]
Python int to binary?
699,866
<p>Are there any canned Python methods to convert an Integer (or Long) into a binary string in Python?</p> <p>There are a myriad of dec2bin() functions out on Google... But I was hoping I could use a built-in function / library.</p>
183
2009-03-31T03:04:37Z
699,877
<p>Unless I'm misunderstanding what you mean by binary string I think the module you are looking for is <a href="http://www.python.org/doc/2.5.2/lib/module-struct.html" rel="nofollow">struct</a></p>
3
2009-03-31T03:08:37Z
[ "python" ]
Python int to binary?
699,866
<p>Are there any canned Python methods to convert an Integer (or Long) into a binary string in Python?</p> <p>There are a myriad of dec2bin() functions out on Google... But I was hoping I could use a built-in function / library.</p>
183
2009-03-31T03:04:37Z
699,891
<p>Python's string format method can take a format spec. </p> <pre><code>&gt;&gt;&gt; "{0:b}".format(10) '1010' </code></pre> <p><a href="https://docs.python.org/2/library/string.html#formatspec">Format spec docs for Python 2</a> </p> <p><a href="https://docs.python.org/3/library/string.html#formatspec">Format spec ...
235
2009-03-31T03:17:18Z
[ "python" ]
Python int to binary?
699,866
<p>Are there any canned Python methods to convert an Integer (or Long) into a binary string in Python?</p> <p>There are a myriad of dec2bin() functions out on Google... But I was hoping I could use a built-in function / library.</p>
183
2009-03-31T03:04:37Z
699,892
<p>If you're looking for <a href="http://docs.python.org/library/functions.html#bin"><code>bin()</code></a> as an equivalent to <code>hex()</code>, it was added in python 2.6.</p> <p>Example:</p> <pre><code>&gt;&gt;&gt; bin(10) '0b1010' </code></pre>
203
2009-03-31T03:17:30Z
[ "python" ]
Python int to binary?
699,866
<p>Are there any canned Python methods to convert an Integer (or Long) into a binary string in Python?</p> <p>There are a myriad of dec2bin() functions out on Google... But I was hoping I could use a built-in function / library.</p>
183
2009-03-31T03:04:37Z
699,901
<p>No language or library will give its user base <em>everything</em> that they desire. If you're working in an envronment that doesn't provide exactly what you need, you should be collecting snippets of code as you develop to ensure you never have to write the same thing twice. Such as, for example:</p> <pre><code>de...
32
2009-03-31T03:25:52Z
[ "python" ]
Python int to binary?
699,866
<p>Are there any canned Python methods to convert an Integer (or Long) into a binary string in Python?</p> <p>There are a myriad of dec2bin() functions out on Google... But I was hoping I could use a built-in function / library.</p>
183
2009-03-31T03:04:37Z
20,643,178
<p>As a reference:</p> <pre><code>def toBinary(n): return ''.join(str(1 &amp; int(n) &gt;&gt; i) for i in range(64)[::-1]) </code></pre> <p>This function can convert a positive integer as large as <code>18446744073709551615</code>, represented as string <code>'11111111111111111111111111111111111111111111111111111...
17
2013-12-17T19:39:08Z
[ "python" ]
Python int to binary?
699,866
<p>Are there any canned Python methods to convert an Integer (or Long) into a binary string in Python?</p> <p>There are a myriad of dec2bin() functions out on Google... But I was hoping I could use a built-in function / library.</p>
183
2009-03-31T03:04:37Z
21,732,313
<p>If you want a textual representation without the 0b-prefix, you could use this:</p> <pre class="lang-python prettyprint-override"><code>get_bin = lambda x: format(x, 'b') print(get_bin(3)) &gt;&gt;&gt; '11' print(get_bin(-3)) &gt;&gt;&gt; '-11' </code></pre> <p>When you want a n-bit representation:</p> <pre cla...
17
2014-02-12T15:33:28Z
[ "python" ]
Python int to binary?
699,866
<p>Are there any canned Python methods to convert an Integer (or Long) into a binary string in Python?</p> <p>There are a myriad of dec2bin() functions out on Google... But I was hoping I could use a built-in function / library.</p>
183
2009-03-31T03:04:37Z
22,424,319
<p>Here is the code I've just implemented. This is not a <strong>method</strong> but you can use it as a <strong>ready-to-use function</strong>!</p> <pre><code>def inttobinary(number): if number == 0: return str(0) result ="" while (number != 0): remainder = number%2 number = number/2 resul...
1
2014-03-15T13:18:44Z
[ "python" ]
Python int to binary?
699,866
<p>Are there any canned Python methods to convert an Integer (or Long) into a binary string in Python?</p> <p>There are a myriad of dec2bin() functions out on Google... But I was hoping I could use a built-in function / library.</p>
183
2009-03-31T03:04:37Z
23,307,130
<p>Along a similar line to Yusuf Yazici's answer</p> <pre><code>def intToBin(n): if(n &lt; 0): print "Sorry, invalid input." elif(n == 0): print n else: result = "" while(n != 0): result += str(n%2) n /= 2 print result[::-1] </code></pre> <p>...
-2
2014-04-26T05:41:26Z
[ "python" ]
Python int to binary?
699,866
<p>Are there any canned Python methods to convert an Integer (or Long) into a binary string in Python?</p> <p>There are a myriad of dec2bin() functions out on Google... But I was hoping I could use a built-in function / library.</p>
183
2009-03-31T03:04:37Z
23,311,042
<p>Somewhat similar solution</p> <pre><code>def to_bin(dec): flag = True bin_str = '' while flag: remainder = dec % 2 quotient = dec / 2 if quotient == 0: flag = False bin_str += str(remainder) dec = quotient bin_str = bin_str[::-1] # reverse the stri...
0
2014-04-26T12:42:23Z
[ "python" ]
Python int to binary?
699,866
<p>Are there any canned Python methods to convert an Integer (or Long) into a binary string in Python?</p> <p>There are a myriad of dec2bin() functions out on Google... But I was hoping I could use a built-in function / library.</p>
183
2009-03-31T03:04:37Z
24,827,567
<p>here is simple solution using the divmod() fucntion which returns the reminder and the result of a division without the fraction.</p> <pre><code>def dectobin(number): bin = '' while (number &gt;= 1): number, rem = divmod(number, 2) bin = bin + str(rem) return bin </code></pre>
1
2014-07-18T14:35:09Z
[ "python" ]
Python int to binary?
699,866
<p>Are there any canned Python methods to convert an Integer (or Long) into a binary string in Python?</p> <p>There are a myriad of dec2bin() functions out on Google... But I was hoping I could use a built-in function / library.</p>
183
2009-03-31T03:04:37Z
26,188,933
<pre><code>def binary(decimal) : otherBase = "" while decimal != 0 : otherBase = str(decimal % 2) + otherBase decimal /= 2 return otherBase print binary(10) </code></pre> <p>output:</p> <blockquote> <p>1010</p> </blockquote>
2
2014-10-04T02:07:16Z
[ "python" ]
Python int to binary?
699,866
<p>Are there any canned Python methods to convert an Integer (or Long) into a binary string in Python?</p> <p>There are a myriad of dec2bin() functions out on Google... But I was hoping I could use a built-in function / library.</p>
183
2009-03-31T03:04:37Z
26,445,311
<p>Yet another solution with another algorithm, by using bitwise operators. </p> <pre><code>def int2bin(val): res='' while val&gt;0: res += str(val&amp;1) val=val&gt;&gt;1 # val=val/2 return res[::-1] # reverse the string </code></pre> <p>A faster version without reversing the st...
2
2014-10-18T22:45:32Z
[ "python" ]
Python int to binary?
699,866
<p>Are there any canned Python methods to convert an Integer (or Long) into a binary string in Python?</p> <p>There are a myriad of dec2bin() functions out on Google... But I was hoping I could use a built-in function / library.</p>
183
2009-03-31T03:04:37Z
27,202,394
<pre><code>n=input() print(bin(n).replace("0b", "")) </code></pre>
-1
2014-11-29T12:45:04Z
[ "python" ]
Python int to binary?
699,866
<p>Are there any canned Python methods to convert an Integer (or Long) into a binary string in Python?</p> <p>There are a myriad of dec2bin() functions out on Google... But I was hoping I could use a built-in function / library.</p>
183
2009-03-31T03:04:37Z
29,997,703
<p>Summary of alternatives:</p> <pre><code>n=42 assert "-101010" == format(-n, 'b') assert "-101010" == "{0:b}".format(-n) assert "-101010" == (lambda x: x &gt;= 0 and str(bin(x))[2:] or "-" + str(bin(x))[3:])(-n) assert "0b101010" == bin(n) assert "101010" == bin(n)[2:] # But this won't work for negative numbe...
5
2015-05-02T02:27:09Z
[ "python" ]
Python int to binary?
699,866
<p>Are there any canned Python methods to convert an Integer (or Long) into a binary string in Python?</p> <p>There are a myriad of dec2bin() functions out on Google... But I was hoping I could use a built-in function / library.</p>
183
2009-03-31T03:04:37Z
30,836,520
<p>one-liner with <strong>lambda</strong>:</p> <pre><code>&gt;&gt;&gt; binary = lambda n: '' if n==0 else binary(n/2) + str(n%2) </code></pre> <p>test:</p> <pre><code>&gt;&gt;&gt; binary(5) '101' </code></pre> <p><br><br> <strong>EDIT</strong>: </p> <p>but then :( </p> <pre><code>t1 = time() for i in range(100000...
10
2015-06-15T02:12:19Z
[ "python" ]
Python int to binary?
699,866
<p>Are there any canned Python methods to convert an Integer (or Long) into a binary string in Python?</p> <p>There are a myriad of dec2bin() functions out on Google... But I was hoping I could use a built-in function / library.</p>
183
2009-03-31T03:04:37Z
32,240,298
<p>Using numpy pack/unpackbits, they are your best friends.</p> <pre><code>Examples -------- &gt;&gt;&gt; a = np.array([[2], [7], [23]], dtype=np.uint8) &gt;&gt;&gt; a array([[ 2], [ 7], [23]], dtype=uint8) &gt;&gt;&gt; b = np.unpackbits(a, axis=1) &gt;&gt;&gt; b array([[0, 0, 0, 0, 0, 0, 1, 0], [...
-1
2015-08-27T03:39:36Z
[ "python" ]
Python int to binary?
699,866
<p>Are there any canned Python methods to convert an Integer (or Long) into a binary string in Python?</p> <p>There are a myriad of dec2bin() functions out on Google... But I was hoping I could use a built-in function / library.</p>
183
2009-03-31T03:04:37Z
33,302,825
<p>Here's yet another way using regular math, no loops, only recursion. (Trivial case 0 returns nothing).</p> <pre><code>def toBin(num): if num == 0: return "" return toBin(num//2) + str(num%2) print ([(toBin(i)) for i in range(10)]) ['', '1', '10', '11', '100', '101', '110', '111', '1000', '1001'] </code><...
0
2015-10-23T12:53:23Z
[ "python" ]
Python int to binary?
699,866
<p>Are there any canned Python methods to convert an Integer (or Long) into a binary string in Python?</p> <p>There are a myriad of dec2bin() functions out on Google... But I was hoping I could use a built-in function / library.</p>
183
2009-03-31T03:04:37Z
34,887,286
<p>A simple way to do that is to use string format, see this <a href="https://docs.python.org/3/library/string.html#formatspec" rel="nofollow">page</a>.</p> <pre><code>&gt;&gt; "{0:b}".format(10) '1010' </code></pre> <p>And if you want to have a fixed length of the binary string, you can use this:</p> <pre><code>&gt...
2
2016-01-19T21:29:47Z
[ "python" ]
Format a number as a string
700,016
<p>How do you format a number as a string so that it takes a number of spaces in front of it? I want the shorter number 5 to have enough spaces in front of it so that the spaces plus the 5 have the same length as 52500. The procedure below works, but is there a built in way to do this?</p> <pre><code>a = str(52500) ...
3
2009-03-31T04:42:58Z
700,024
<p>Not sure exactly what you're after, but this looks close:</p> <pre><code>&gt;&gt;&gt; n = 50 &gt;&gt;&gt; print "%5d" % n 50 </code></pre> <p>If you want to be more dynamic, use something like <code>rjust</code>:</p> <pre><code>&gt;&gt;&gt; big_number = 52500 &gt;&gt;&gt; n = 50 &gt;&gt;&gt; print ("%d" % n).r...
0
2009-03-31T04:45:57Z
[ "python", "string", "integer", "format" ]
Format a number as a string
700,016
<p>How do you format a number as a string so that it takes a number of spaces in front of it? I want the shorter number 5 to have enough spaces in front of it so that the spaces plus the 5 have the same length as 52500. The procedure below works, but is there a built in way to do this?</p> <pre><code>a = str(52500) ...
3
2009-03-31T04:42:58Z
700,032
<p><a href="http://docs.python.org/library/stdtypes.html#string-formatting" rel="nofollow">Format operator</a>:</p> <pre><code>&gt;&gt;&gt; "%10d" % 5 ' 5' &gt;&gt;&gt; </code></pre> <p>Using <code>*</code> spec, the field length can be an argument:</p> <pre><code>&gt;&gt;&gt; "%*d" % (10,5) ' 5' &gt...
8
2009-03-31T04:49:27Z
[ "python", "string", "integer", "format" ]
Format a number as a string
700,016
<p>How do you format a number as a string so that it takes a number of spaces in front of it? I want the shorter number 5 to have enough spaces in front of it so that the spaces plus the 5 have the same length as 52500. The procedure below works, but is there a built in way to do this?</p> <pre><code>a = str(52500) ...
3
2009-03-31T04:42:58Z
700,033
<p>See <a href="http://docs.python.org/library/stdtypes.html#string-formatting-operations" rel="nofollow">String Formatting Operations</a>:</p> <pre><code>s = '%5i' % (5,) </code></pre> <p>You still have to dynamically build your formatting string by including the maximum length:</p> <pre><code>fmt = '%%%ii' % (len(...
1
2009-03-31T04:49:56Z
[ "python", "string", "integer", "format" ]
Format a number as a string
700,016
<p>How do you format a number as a string so that it takes a number of spaces in front of it? I want the shorter number 5 to have enough spaces in front of it so that the spaces plus the 5 have the same length as 52500. The procedure below works, but is there a built in way to do this?</p> <pre><code>a = str(52500) ...
3
2009-03-31T04:42:58Z
700,060
<p>You can just use the <code>%*d</code> formatter to give a width. <code>int(math.ceil(math.log(x, 10)))</code> will give you the number of digits. The <code>*</code> modifier consumes a number, that number is an integer that means how many spaces to space by. So by doing <code>'%*d'</code> % (width, num)` you can spe...
2
2009-03-31T05:02:34Z
[ "python", "string", "integer", "format" ]
Format a number as a string
700,016
<p>How do you format a number as a string so that it takes a number of spaces in front of it? I want the shorter number 5 to have enough spaces in front of it so that the spaces plus the 5 have the same length as 52500. The procedure below works, but is there a built in way to do this?</p> <pre><code>a = str(52500) ...
3
2009-03-31T04:42:58Z
700,066
<p>'%*s/%s' % (len(str(a)), b, a)</p>
2
2009-03-31T05:03:39Z
[ "python", "string", "integer", "format" ]
communication with long running tasks in python
700,073
<p>I have a python GUI app that uses a long running function from a .so/.dll it calls through ctypes.</p> <p>I'm looking for a way to communicate with the function while it's running in a separate thread or process, so that I can request it to terminate early (which requires some work on the C side before returning a ...
1
2009-03-31T05:06:06Z
700,088
<p>If you're on *nix register a signal handler for SIGUSR1 or SIGINT in your C program then from Python use os.kill to send the signal.</p>
0
2009-03-31T05:13:51Z
[ "python", "multithreading", "process", "ctypes" ]
communication with long running tasks in python
700,073
<p>I have a python GUI app that uses a long running function from a .so/.dll it calls through ctypes.</p> <p>I'm looking for a way to communicate with the function while it's running in a separate thread or process, so that I can request it to terminate early (which requires some work on the C side before returning a ...
1
2009-03-31T05:06:06Z
700,089
<p>You said it: signals and pipes.</p> <p>It doesn't have to be too complex, but it will be a heck of a lot easier if you use an existing structure than if you try to roll your own.</p>
0
2009-03-31T05:14:03Z
[ "python", "multithreading", "process", "ctypes" ]
communication with long running tasks in python
700,073
<p>I have a python GUI app that uses a long running function from a .so/.dll it calls through ctypes.</p> <p>I'm looking for a way to communicate with the function while it's running in a separate thread or process, so that I can request it to terminate early (which requires some work on the C side before returning a ...
1
2009-03-31T05:06:06Z
700,142
<p>There's two parts you'll need to answer here: one if how to communicate between the two processes (your GUI and the process executing the function), and the other is how to change your function so it responds to asynchronous requests ("oh, I've been told to just return whatever I've got").</p> <p>Working out the an...
2
2009-03-31T05:32:01Z
[ "python", "multithreading", "process", "ctypes" ]
communication with long running tasks in python
700,073
<p>I have a python GUI app that uses a long running function from a .so/.dll it calls through ctypes.</p> <p>I'm looking for a way to communicate with the function while it's running in a separate thread or process, so that I can request it to terminate early (which requires some work on the C side before returning a ...
1
2009-03-31T05:06:06Z
700,146
<p>You mention that you can change both the C and Python sides. To avoid having to write any sockets or signal code in C, it might be easiest to break up the large C function into 3 smaller separate functions that perform setup, a small parcel of work, and cleanup. The work parcel should be between about 1 ms and 1 sec...
2
2009-03-31T05:33:50Z
[ "python", "multithreading", "process", "ctypes" ]
Is there a Python library to interact with Genesys?
700,350
<p>I work within a contact center and we use Genesys with an Alcatel PBX. We currently use .NET libraries to wrap the DLL's provided to us, but I'm wondering if there are any Python libraries out there before I attempt to write my own?</p> <p>Thanks</p> <p>Edit:</p> <p>Jython with the Java SDK library works a treat....
1
2009-03-31T07:07:40Z
700,425
<p>If they are providing a C library, you can use ctypes to interact with it.</p>
2
2009-03-31T07:36:48Z
[ "python", "pbx", "pabx" ]
Is there a Python library to interact with Genesys?
700,350
<p>I work within a contact center and we use Genesys with an Alcatel PBX. We currently use .NET libraries to wrap the DLL's provided to us, but I'm wondering if there are any Python libraries out there before I attempt to write my own?</p> <p>Thanks</p> <p>Edit:</p> <p>Jython with the Java SDK library works a treat....
1
2009-03-31T07:07:40Z
4,862,326
<p>What do you need to interact with exacly? The GIS provides soap calls for a lot of functions.</p>
0
2011-02-01T12:06:22Z
[ "python", "pbx", "pabx" ]
Is there a Python library to interact with Genesys?
700,350
<p>I work within a contact center and we use Genesys with an Alcatel PBX. We currently use .NET libraries to wrap the DLL's provided to us, but I'm wondering if there are any Python libraries out there before I attempt to write my own?</p> <p>Thanks</p> <p>Edit:</p> <p>Jython with the Java SDK library works a treat....
1
2009-03-31T07:07:40Z
7,123,654
<p>There is neither a native C nor a Python library. Best bet is to use GIS as suggested.</p>
0
2011-08-19T15:12:12Z
[ "python", "pbx", "pabx" ]
How to add a Python import path using a .pth file
700,375
<p>If I put a *.pth file in site-packages it's giving an <code>ImportError</code>. I'm not getting how to import by creating a *.pth file.</p> <p><em>(Refers to <a href="http://stackoverflow.com/questions/697281/importing-in-python">importing in python</a>)</em></p>
10
2009-03-31T07:15:05Z
700,394
<p>If you put a <code>.pth</code> file in the <code>site-packages</code> directory containing a path, python searches this path for imports. So I have a <code>sth.pth</code> file there that simply contains:</p> <pre><code>K:\Source\Python\lib </code></pre> <p>In that directory there are some normal Python modules:</p...
30
2009-03-31T07:23:40Z
[ "python", "python-import" ]
How to add a Python import path using a .pth file
700,375
<p>If I put a *.pth file in site-packages it's giving an <code>ImportError</code>. I'm not getting how to import by creating a *.pth file.</p> <p><em>(Refers to <a href="http://stackoverflow.com/questions/697281/importing-in-python">importing in python</a>)</em></p>
10
2009-03-31T07:15:05Z
700,512
<pre><code>/tmp/$ mkdir test; cd test /tmp/test/$ mkdir foo; mkdir bar /tmp/test/$ echo -e "foo\nbar" &gt; foobar.pth /tmp/test/$ cd .. /tmp/$ python Python 2.6 (r26:66714, Feb 3 2009, 20:52:03) [GCC 4.3.2 [gcc-4_3-branch revision 141291]] on linux2 Type "help", "copyright", "credits" or "license" for more information...
22
2009-03-31T08:11:16Z
[ "python", "python-import" ]
Control access to WebDav/Apache using Python
700,480
<p>I want to give users access to WebDav using Apache, but I want to autenticate them first and give each user access to a specific folder. All authentication must be done against a Django-based database. I can get the Django-authentication working myself, but I need help with the part where I authenticate each user an...
1
2009-03-31T07:58:05Z
700,876
<p>You might find that the apache <a href="http://httpd.apache.org/docs/2.2/mod/mod%5Fauthn%5Fdbd.html" rel="nofollow">mod_authn_dbd</a> module gives you what you want. This module lets apache check an SQL database for authentication and authorization. You would use this directive in the <code>&lt;Location&gt;</code>, ...
0
2009-03-31T13:13:34Z
[ "python", "django", "apache", "webdav" ]
Control access to WebDav/Apache using Python
700,480
<p>I want to give users access to WebDav using Apache, but I want to autenticate them first and give each user access to a specific folder. All authentication must be done against a Django-based database. I can get the Django-authentication working myself, but I need help with the part where I authenticate each user an...
1
2009-03-31T07:58:05Z
963,350
<p>I know this question is old, but just as an addition... If you are using mod_python, you may also be interested in "<a href="http://docs.djangoproject.com/en/dev/howto/apache-auth/#howto-apache-auth" rel="nofollow">Authenticating against Django’s user database from Apache</a>" section of Django documentation.</p>
0
2009-06-08T03:34:34Z
[ "python", "django", "apache", "webdav" ]
Control access to WebDav/Apache using Python
700,480
<p>I want to give users access to WebDav using Apache, but I want to autenticate them first and give each user access to a specific folder. All authentication must be done against a Django-based database. I can get the Django-authentication working myself, but I need help with the part where I authenticate each user an...
1
2009-03-31T07:58:05Z
5,005,073
<p>First, for you other readers, my authentication was done against Django using a <a href="http://www.davidfischer.name/2009/10/django-authentication-and-mod_wsgi/" rel="nofollow">WSGI authentication script</a>.</p> <p>Then, there's the meat of the question, giving each Django user, in this case, their own WebDav dir...
1
2011-02-15T14:47:45Z
[ "python", "django", "apache", "webdav" ]
How to detect changed and new items in an RSS feed?
700,607
<p>Using <a href="http://packages.python.org/feedparser/" rel="nofollow">feedparser</a> or some other Python library to download and parse RSS feeds; how can I reliably detect <code>new</code> items and <code>modified</code> items?</p> <p>So far I have seen new items in feeds with publication dates earlier than the la...
2
2009-03-31T08:39:38Z
703,693
<p>It depends on how much you trust the feed source. feedparser provides an .id attribute for feed items -- this attribute should be unique for both RSS and ATOM sources. For an example, see eg feedparser's <a href="http://feedparser.org/docs/common-atom-elements.html" rel="nofollow">ATOM docs</a>. Though .id will cove...
3
2009-04-01T01:22:33Z
[ "python", "rss", "feeds" ]
EOFError in Python script
700,873
<p>I have the following code fragment:</p> <pre><code>def database(self): databasename="" host="" user="" password="" try: self.fp=file("detailing.dat","rb") except IOError: self.fp=file("detailing.dat","wb") pickle.dump([databasename,host,user,password],self.fp,-1) ...
4
2009-03-31T13:12:33Z
700,914
<p>Unless you've got a typo, the issue may be in this line where you assign the file handle to <code>selffp</code> not <code>self.fp</code>:</p> <pre><code>selffp=file("detailing.dat","rb") </code></pre> <p>If that is a typo, and your code actually opens the file to <code>self.fp</code>, then you may wish to verify t...
14
2009-03-31T13:21:31Z
[ "python", "pickle", "raw-input", "eoferror" ]
EOFError in Python script
700,873
<p>I have the following code fragment:</p> <pre><code>def database(self): databasename="" host="" user="" password="" try: self.fp=file("detailing.dat","rb") except IOError: self.fp=file("detailing.dat","wb") pickle.dump([databasename,host,user,password],self.fp,-1) ...
4
2009-03-31T13:12:33Z
701,050
<p>Here's the version that I would recommend using:</p> <pre><code>def database(self): databasename="" host="" user="" password="" try: self.fp=open("detailing.dat","rb") except IOError: with open("detailing.dat", "wb") as fp: pickle.dump([databasename,host,user,pass...
5
2009-03-31T13:48:23Z
[ "python", "pickle", "raw-input", "eoferror" ]
EOFError in Python script
700,873
<p>I have the following code fragment:</p> <pre><code>def database(self): databasename="" host="" user="" password="" try: self.fp=file("detailing.dat","rb") except IOError: self.fp=file("detailing.dat","wb") pickle.dump([databasename,host,user,password],self.fp,-1) ...
4
2009-03-31T13:12:33Z
38,357,978
<p>While this is not a direct answer to the OP's question -- I happened upon this answer while searching for a reason for an <code>EOFError</code> when trying to unpickle a binary file with : <code>pickle.load(open(filename, "r"))</code>.</p> <pre><code>import cPickle as pickle A = dict((v, i) for i, v in enumerate(w...
0
2016-07-13T17:17:19Z
[ "python", "pickle", "raw-input", "eoferror" ]
EOFError in Python script
700,873
<p>I have the following code fragment:</p> <pre><code>def database(self): databasename="" host="" user="" password="" try: self.fp=file("detailing.dat","rb") except IOError: self.fp=file("detailing.dat","wb") pickle.dump([databasename,host,user,password],self.fp,-1) ...
4
2009-03-31T13:12:33Z
38,613,161
<p>I got this error when I didn't chose the correct mode to read the file (<code>wb</code> instead of <code>rb</code>). Changing back to <code>rb</code> was not sufficient to solve the issue. However, generating again a new clean pickle file solved the issue. It seems that not choosing the correct mode to open the bina...
0
2016-07-27T12:35:28Z
[ "python", "pickle", "raw-input", "eoferror" ]
How to design multi-threaded GUI-network application?
700,905
<p>I'm working on a small utility application in Python.</p> <p>The networking is gonna send and recieve messages. The GUI is gonna display the messages from the GUI and provide user input for entering messages to be sent. There's also a <em>storage</em> part as I call it, which is gonna get all the network messages ...
1
2009-03-31T13:18:43Z
701,010
<p>I think that you could use a <a href="http://docs.python.org/library/queue.html" rel="nofollow">Queue</a> for passing messages between the GUI and the network threads.</p> <p>As for GUI and threads in general, you might find the <a href="http://www.oreillynet.com/onlamp/blog/2006/07/pygtk%5Fand%5Fthreading.html" re...
1
2009-03-31T13:40:48Z
[ "python", "multithreading", "user-interface" ]
How to design multi-threaded GUI-network application?
700,905
<p>I'm working on a small utility application in Python.</p> <p>The networking is gonna send and recieve messages. The GUI is gonna display the messages from the GUI and provide user input for entering messages to be sent. There's also a <em>storage</em> part as I call it, which is gonna get all the network messages ...
1
2009-03-31T13:18:43Z
701,171
<p>One, probably the best, solution for this problem is to use <a href="http://twistedmatrix.com/" rel="nofollow">Twisted</a>. It supports all the GUI toolkits.</p>
2
2009-03-31T14:14:38Z
[ "python", "multithreading", "user-interface" ]
Py3k memory conservation by returning iterators rather than lists
701,088
<p>Many methods that used to return lists in Python 2.x now seem to return iterators in Py3k</p> <p>Are iterators also generator expressions? Lazy evaluation?</p> <p>Thus, with this the memory footprint of python is going to reduce drastically. Isn't it?</p> <p>What about for the programs converted from 2to3 using t...
2
2009-03-31T13:55:17Z
701,889
<p>Many of them are not exactly iterators, but special view objects. For instance range() now returns something similar to the old xrange object - it can still be indexed, but lazily constructs the integers as needed.</p> <p>Similarly dict.keys() gives a dict_keys object implementing a view on the dict, rather than c...
7
2009-03-31T16:27:59Z
[ "python", "memory", "list", "iterator", "python-3.x" ]
Py3k memory conservation by returning iterators rather than lists
701,088
<p>Many methods that used to return lists in Python 2.x now seem to return iterators in Py3k</p> <p>Are iterators also generator expressions? Lazy evaluation?</p> <p>Thus, with this the memory footprint of python is going to reduce drastically. Isn't it?</p> <p>What about for the programs converted from 2to3 using t...
2
2009-03-31T13:55:17Z
701,936
<blockquote> <p>Are iterators also generator expressions? Lazy evaluation?</p> </blockquote> <p>An iterator is just an object with a next method. What the documentation means most of the time when saying that a function returns an iterator is that its result is lazily loaded.</p> <blockquote> <p>Thus, with this ...
1
2009-03-31T16:39:11Z
[ "python", "memory", "list", "iterator", "python-3.x" ]
Py3k memory conservation by returning iterators rather than lists
701,088
<p>Many methods that used to return lists in Python 2.x now seem to return iterators in Py3k</p> <p>Are iterators also generator expressions? Lazy evaluation?</p> <p>Thus, with this the memory footprint of python is going to reduce drastically. Isn't it?</p> <p>What about for the programs converted from 2to3 using t...
2
2009-03-31T13:55:17Z
28,639,917
<p>One of the biggest benefits of iterators over lists isn't memory, it is actually computation time. For instance, in Python 2:</p> <pre><code>for i in range(1000000): # spend a bunch of time making a big list if i == 0: break # Building the list was a waste since we only looped once </code></pre> <p>N...
0
2015-02-20T23:21:10Z
[ "python", "memory", "list", "iterator", "python-3.x" ]
Is there a standard 3rd party Python caching class?
701,264
<p>I'm working on a client class which needs to load data from a networked database. It's been suggested that adding a standard caching service to the client could improve it's performance. </p> <p>I'd dearly like not to have to build my own caching class - it's well known that these provide common points of failure. ...
5
2009-03-31T14:33:38Z
701,341
<p>I'd recommend using <a href="http://www.danga.com/memcached/" rel="nofollow">memcached</a> and using <a href="http://gijsbert.org/cmemcache/" rel="nofollow">cmemcache</a> to access it. You can't necessarily limit the number of objects in the cache, but you can set an expiration time and limit the amount of memory i...
4
2009-03-31T14:47:58Z
[ "python", "design-patterns" ]
Best way to choose a random file from a directory
701,402
<p>What is the best way to choose a random file from a directory in Python?</p> <p><em>Edit:</em> Here is what I am doing:</p> <pre><code>import os import random import dircache dir = 'some/directory' filename = random.choice(dircache.listdir(dir)) path = os.path.join(dir, filename) </code></pre> <p>Is this particu...
10
2009-03-31T14:58:41Z
701,424
<p>Independant from the language used, you can read all references to the files in a directory into a datastructure like an array (something like 'listFiles'), get the length of the array. calculate a random number in the range of '0' to 'arrayLength-1' and access the file at the certain index. This should work, not on...
1
2009-03-31T15:01:49Z
[ "python", "file", "random" ]
Best way to choose a random file from a directory
701,402
<p>What is the best way to choose a random file from a directory in Python?</p> <p><em>Edit:</em> Here is what I am doing:</p> <pre><code>import os import random import dircache dir = 'some/directory' filename = random.choice(dircache.listdir(dir)) path = os.path.join(dir, filename) </code></pre> <p>Is this particu...
10
2009-03-31T14:58:41Z
701,425
<p>Check out <a href="http://lost-theory.org/python/randomimg.html" rel="nofollow">this page</a>, it might help you achieve what you're trying to do.</p>
0
2009-03-31T15:01:50Z
[ "python", "file", "random" ]
Best way to choose a random file from a directory
701,402
<p>What is the best way to choose a random file from a directory in Python?</p> <p><em>Edit:</em> Here is what I am doing:</p> <pre><code>import os import random import dircache dir = 'some/directory' filename = random.choice(dircache.listdir(dir)) path = os.path.join(dir, filename) </code></pre> <p>Is this particu...
10
2009-03-31T14:58:41Z
701,428
<p>If you don't know before hand what files are there, you will need to get a list, then just pick a random index in the list.</p> <p>Here's one attempt:</p> <pre><code>import os import random def getRandomFile(path): """ Returns a random filename, chosen among the files of the given path. """ files = os.lis...
1
2009-03-31T15:02:11Z
[ "python", "file", "random" ]
Best way to choose a random file from a directory
701,402
<p>What is the best way to choose a random file from a directory in Python?</p> <p><em>Edit:</em> Here is what I am doing:</p> <pre><code>import os import random import dircache dir = 'some/directory' filename = random.choice(dircache.listdir(dir)) path = os.path.join(dir, filename) </code></pre> <p>Is this particu...
10
2009-03-31T14:58:41Z
701,430
<pre><code>import os, random random.choice(os.listdir("C:\\")) #change dir name to whatever </code></pre> <p><hr></p> <p>Regarding your edited question: first, I assume you know the risks of using a <code>dircache</code>, as well as the fact that it is <a href="http://docs.python.org/library/dircache.html">deprecated...
31
2009-03-31T15:02:21Z
[ "python", "file", "random" ]
Best way to choose a random file from a directory
701,402
<p>What is the best way to choose a random file from a directory in Python?</p> <p><em>Edit:</em> Here is what I am doing:</p> <pre><code>import os import random import dircache dir = 'some/directory' filename = random.choice(dircache.listdir(dir)) path = os.path.join(dir, filename) </code></pre> <p>Is this particu...
10
2009-03-31T14:58:41Z
701,448
<p>Language agnostic solution:</p> <p>1) Get the total no. of files in specified directory.</p> <p>2) Pick a random number from 0 to [total no. of files - 1].</p> <p>3) Get the list of filenames as a suitably indexed collection or such.</p> <p>4) Pick the nth element, where n is the random number.</p>
4
2009-03-31T15:04:36Z
[ "python", "file", "random" ]
Best way to choose a random file from a directory
701,402
<p>What is the best way to choose a random file from a directory in Python?</p> <p><em>Edit:</em> Here is what I am doing:</p> <pre><code>import os import random import dircache dir = 'some/directory' filename = random.choice(dircache.listdir(dir)) path = os.path.join(dir, filename) </code></pre> <p>Is this particu...
10
2009-03-31T14:58:41Z
701,488
<p>If you want directories included, Yuval A's answer. Otherwise:</p> <pre><code>import os, random random.choice([x for x in os.listdir("C:\\") if os.path.isfile(os.path.join("C:\\", x))]) </code></pre>
2
2009-03-31T15:10:40Z
[ "python", "file", "random" ]
Nested try statements in python?
701,466
<p>Is there a nicer way of doing the following:</p> <pre><code>try: a.method1() except AttributeError: try: a.method2() except AttributeError: try: a.method3() except AttributeError: raise </code></pre> <p>It looks pretty nasty and I'd rather not do:</p> <p...
28
2009-03-31T15:07:16Z
701,539
<p>How about encapsulating the calls in a function?</p> <pre><code>def method_1_2_or_3(): try: a.method1() return except AttributeError: pass try: a.method2() return except AttributeError: pass try: a.method3() except AttributeError: ...
4
2009-03-31T15:17:52Z
[ "python", "try-catch" ]
Nested try statements in python?
701,466
<p>Is there a nicer way of doing the following:</p> <pre><code>try: a.method1() except AttributeError: try: a.method2() except AttributeError: try: a.method3() except AttributeError: raise </code></pre> <p>It looks pretty nasty and I'd rather not do:</p> <p...
28
2009-03-31T15:07:16Z
701,542
<p>Perhaps you could try something like this:</p> <pre><code>def call_attrs(obj, attrs_list, *args): for attr in attrs_list: if hasattr(obj, attr): bound_method = getattr(obj, attr) return bound_method(*args) raise AttributeError </code></pre> <p>You would call it like this:</...
21
2009-03-31T15:19:15Z
[ "python", "try-catch" ]
Nested try statements in python?
701,466
<p>Is there a nicer way of doing the following:</p> <pre><code>try: a.method1() except AttributeError: try: a.method2() except AttributeError: try: a.method3() except AttributeError: raise </code></pre> <p>It looks pretty nasty and I'd rather not do:</p> <p...
28
2009-03-31T15:07:16Z
701,555
<p>If you are using new-style object:</p> <pre><code>methods = ('method1','method2','method3') for method in methods: try: b = a.__getattribute__(method) except AttributeError: continue else: b() break else: # re-raise the AttributeError if nothing has worked raise A...
1
2009-03-31T15:21:54Z
[ "python", "try-catch" ]
Nested try statements in python?
701,466
<p>Is there a nicer way of doing the following:</p> <pre><code>try: a.method1() except AttributeError: try: a.method2() except AttributeError: try: a.method3() except AttributeError: raise </code></pre> <p>It looks pretty nasty and I'd rather not do:</p> <p...
28
2009-03-31T15:07:16Z
701,682
<p>A slight change to the second looks pretty nice and simple. I really doubt you'll notice any performance difference between the two, and this is a bit nicer than a nested try/excepts</p> <pre><code>def something(a): for methodname in ['method1', 'method2', 'method3']: try: m = getattr(a, met...
20
2009-03-31T15:50:14Z
[ "python", "try-catch" ]
Nested try statements in python?
701,466
<p>Is there a nicer way of doing the following:</p> <pre><code>try: a.method1() except AttributeError: try: a.method2() except AttributeError: try: a.method3() except AttributeError: raise </code></pre> <p>It looks pretty nasty and I'd rather not do:</p> <p...
28
2009-03-31T15:07:16Z
5,256,525
<p>A compact solution:</p> <pre><code>getattr(a, 'method1', getattr(a, 'method2', getattr(a, 'method3')))() </code></pre>
3
2011-03-10T07:07:14Z
[ "python", "try-catch" ]
Nested try statements in python?
701,466
<p>Is there a nicer way of doing the following:</p> <pre><code>try: a.method1() except AttributeError: try: a.method2() except AttributeError: try: a.method3() except AttributeError: raise </code></pre> <p>It looks pretty nasty and I'd rather not do:</p> <p...
28
2009-03-31T15:07:16Z
7,971,414
<pre><code>method = ( getattr(a, 'method1', None) or getattr(a, 'method2', None) or getattr(a, 'method3') ) method() </code></pre> <p>This will first look for <code>method1</code>, then <code>method2</code>, then <code>method3</code>. The search will stop as soon as one of them is foun...
5
2011-11-01T18:53:37Z
[ "python", "try-catch" ]
Convert HTML entities to Unicode and vice versa
701,704
<blockquote> <p><strong>Possible duplicates:</strong></p> <ul> <li><a href="http://stackoverflow.com/questions/57708/convert-xml-html-entities-into-unicode-string-in-python">Convert XML/HTML Entities into Unicode String in Python</a></li> <li><a href="http://stackoverflow.com/questions/663058/html-entity-cod...
36
2009-03-31T15:54:25Z
701,722
<p>You need to have <a href="http://www.crummy.com/software/BeautifulSoup/">BeautifulSoup</a>.</p> <pre><code>from BeautifulSoup import BeautifulStoneSoup import cgi def HTMLEntitiesToUnicode(text): """Converts HTML entities to unicode. For example '&amp;amp;' becomes '&amp;'.""" text = unicode(BeautifulSton...
20
2009-03-31T15:57:56Z
[ "python", "html", "html-entities" ]
Convert HTML entities to Unicode and vice versa
701,704
<blockquote> <p><strong>Possible duplicates:</strong></p> <ul> <li><a href="http://stackoverflow.com/questions/57708/convert-xml-html-entities-into-unicode-string-in-python">Convert XML/HTML Entities into Unicode String in Python</a></li> <li><a href="http://stackoverflow.com/questions/663058/html-entity-cod...
36
2009-03-31T15:54:25Z
2,657,467
<p>As to the "vice versa" (which I needed myself, leading me to find this question, which didn't help, and subsequently <a href="http://www.megasolutions.net/python/Unicode-to-HTML-entities-78703.aspx">another site which had the answer</a>):</p> <pre><code>u'some string'.encode('ascii', 'xmlcharrefreplace') </code></p...
67
2010-04-17T06:13:38Z
[ "python", "html", "html-entities" ]
Convert HTML entities to Unicode and vice versa
701,704
<blockquote> <p><strong>Possible duplicates:</strong></p> <ul> <li><a href="http://stackoverflow.com/questions/57708/convert-xml-html-entities-into-unicode-string-in-python">Convert XML/HTML Entities into Unicode String in Python</a></li> <li><a href="http://stackoverflow.com/questions/663058/html-entity-cod...
36
2009-03-31T15:54:25Z
24,643,425
<p>As <em>hekevintran</em> answer suggests, you may use <code>cgi.escape(s)</code> for encoding stings, but notice that encoding of quote is false by default in that function and it may be a good idea to pass the <code>quote=True</code> keyword argument alongside your string. But even by passing <code>quote=True</code>...
2
2014-07-09T00:02:40Z
[ "python", "html", "html-entities" ]
Convert HTML entities to Unicode and vice versa
701,704
<blockquote> <p><strong>Possible duplicates:</strong></p> <ul> <li><a href="http://stackoverflow.com/questions/57708/convert-xml-html-entities-into-unicode-string-in-python">Convert XML/HTML Entities into Unicode String in Python</a></li> <li><a href="http://stackoverflow.com/questions/663058/html-entity-cod...
36
2009-03-31T15:54:25Z
28,827,374
<p>There are standard lib means for unescaping unicode HTML (documented as of <code>Python 2.7</code>). </p> <p>Also, the <code>BeautifulSoup</code> API (can be used for both escaping and unescaping unicode HTML) has changed as of BeautifulSoup4 ("<code>bs4</code>").</p> <p>Given non-HTML unicode like: </p> <pre><co...
6
2015-03-03T08:43:24Z
[ "python", "html", "html-entities" ]
Is there a python library that implements both sides of the AWS authentication protocol?
701,789
<p>I am writing a REST service in python and django and wanted to use Amazon's AWS authentication protocol. I was wondering if anyone knew of a python library that implemented formation of the header for sending and the validation of the header for recieving?</p>
3
2009-03-31T16:09:48Z
712,439
<p>Try this Library. I think it is the library you are searching for..</p> <p><a href="https://calnet.berkeley.edu/developers/downloads/CalNetAwsPython.html" rel="nofollow">CalNet</a></p> <p>You can find some Python Code Samples <a href="https://calnet.berkeley.edu/news/entry/2005/11/10/01.html" rel="nofollow">Here</...
2
2009-04-03T03:20:12Z
[ "python", "amazon-web-services" ]
Is there a python library that implements both sides of the AWS authentication protocol?
701,789
<p>I am writing a REST service in python and django and wanted to use Amazon's AWS authentication protocol. I was wondering if anyone knew of a python library that implemented formation of the header for sending and the validation of the header for recieving?</p>
3
2009-03-31T16:09:48Z
712,827
<p><a href="http://code.google.com/p/boto/" rel="nofollow">boto</a> is a Python library for AWS. I don't know however if it supports what you are asking for.</p>
1
2009-04-03T07:09:18Z
[ "python", "amazon-web-services" ]