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 need it to be escaped.</p> <p>IE: 1234567890 -> '\x49\x96\x02\xd2' not '499602D2'</p> <p>Also, it needs to be able to take any Python integer. IE. something larger than an Int.</p> <p><strong>Edit:</strong></p> <p>Here is the best solution so far I have cobbled together from Paolo and Devin's post.</p> <pre><code>def hexify(num): num = "%x" % num if len(num) % 2: num = '0'+num return num.decode('hex') </code></pre>
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>A</code>. I want to be able to generate output from <code>B</code>, while suppressing all the output from <code>A</code>.</p> <p>From within <code>B</code>, I've tried <code>os.system('A')</code>, <code>os.system('A &gt; /dev/null')</code>, and <code>os.system('A &amp;&gt; /dev/null')</code>, <code>os.execvp('...')</code>, etc. but none of those suppress all the output from A.</p> <p>I could run <code>B &amp;&gt; /dev/null</code>, but that suppresses all of <code>B</code>'s output too and I don't want that.</p> <p>Anyone have suggestions?</p>
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>A</code>. I want to be able to generate output from <code>B</code>, while suppressing all the output from <code>A</code>.</p> <p>From within <code>B</code>, I've tried <code>os.system('A')</code>, <code>os.system('A &gt; /dev/null')</code>, and <code>os.system('A &amp;&gt; /dev/null')</code>, <code>os.execvp('...')</code>, etc. but none of those suppress all the output from A.</p> <p>I could run <code>B &amp;&gt; /dev/null</code>, but that suppresses all of <code>B</code>'s output too and I don't want that.</p> <p>Anyone have suggestions?</p>
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 _______ &lt; hello &gt; ------- \ ^__^ \ (oo)\_______ (__)\ )\/\ ||----w | || || </code></pre>
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>A</code>. I want to be able to generate output from <code>B</code>, while suppressing all the output from <code>A</code>.</p> <p>From within <code>B</code>, I've tried <code>os.system('A')</code>, <code>os.system('A &gt; /dev/null')</code>, and <code>os.system('A &amp;&gt; /dev/null')</code>, <code>os.execvp('...')</code>, etc. but none of those suppress all the output from A.</p> <p>I could run <code>B &amp;&gt; /dev/null</code>, but that suppresses all of <code>B</code>'s output too and I don't want that.</p> <p>Anyone have suggestions?</p>
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 your command relies on shell features like wildcards, pipes, or environment variables, you'll need to provide the whole command as a string, and also specify <code>shell = True</code>. This should be avoided, though, since it represents a security hazard if the contents of the string aren't carefully validated.</p>
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>A</code>. I want to be able to generate output from <code>B</code>, while suppressing all the output from <code>A</code>.</p> <p>From within <code>B</code>, I've tried <code>os.system('A')</code>, <code>os.system('A &gt; /dev/null')</code>, and <code>os.system('A &amp;&gt; /dev/null')</code>, <code>os.execvp('...')</code>, etc. but none of those suppress all the output from A.</p> <p>I could run <code>B &amp;&gt; /dev/null</code>, but that suppresses all of <code>B</code>'s output too and I don't want that.</p> <p>Anyone have suggestions?</p>
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>A</code>. I want to be able to generate output from <code>B</code>, while suppressing all the output from <code>A</code>.</p> <p>From within <code>B</code>, I've tried <code>os.system('A')</code>, <code>os.system('A &gt; /dev/null')</code>, and <code>os.system('A &amp;&gt; /dev/null')</code>, <code>os.execvp('...')</code>, etc. but none of those suppress all the output from A.</p> <p>I could run <code>B &amp;&gt; /dev/null</code>, but that suppresses all of <code>B</code>'s output too and I don't want that.</p> <p>Anyone have suggestions?</p>
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 an output larger than the buffer, A will be blocked on writing, while the calling program B awaits the termination of A. <strong>But not, in this particular case... see comments below.</strong></p> <p>Still, I recommend using Devin Jeanpierre and DNS' solution.</p>
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>A</code>. I want to be able to generate output from <code>B</code>, while suppressing all the output from <code>A</code>.</p> <p>From within <code>B</code>, I've tried <code>os.system('A')</code>, <code>os.system('A &gt; /dev/null')</code>, and <code>os.system('A &amp;&gt; /dev/null')</code>, <code>os.execvp('...')</code>, etc. but none of those suppress all the output from A.</p> <p>I could run <code>B &amp;&gt; /dev/null</code>, but that suppresses all of <code>B</code>'s output too and I don't want that.</p> <p>Anyone have suggestions?</p>
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>A</code>. I want to be able to generate output from <code>B</code>, while suppressing all the output from <code>A</code>.</p> <p>From within <code>B</code>, I've tried <code>os.system('A')</code>, <code>os.system('A &gt; /dev/null')</code>, and <code>os.system('A &amp;&gt; /dev/null')</code>, <code>os.execvp('...')</code>, etc. but none of those suppress all the output from A.</p> <p>I could run <code>B &amp;&gt; /dev/null</code>, but that suppresses all of <code>B</code>'s output too and I don't want that.</p> <p>Anyone have suggestions?</p>
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 of 'write()' by assigning to a variable. discard=fh.write(megabyte) fh.close() </code></pre> <p>I was creating a large zero-filled file to zero free space on my hard drive and discovered that each call to handle.write(string) spit out the number of bytes written. Assigning it to a vairable suppressed that output.</p>
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>A</code>. I want to be able to generate output from <code>B</code>, while suppressing all the output from <code>A</code>.</p> <p>From within <code>B</code>, I've tried <code>os.system('A')</code>, <code>os.system('A &gt; /dev/null')</code>, and <code>os.system('A &amp;&gt; /dev/null')</code>, <code>os.execvp('...')</code>, etc. but none of those suppress all the output from A.</p> <p>I could run <code>B &amp;&gt; /dev/null</code>, but that suppresses all of <code>B</code>'s output too and I don't want that.</p> <p>Anyone have suggestions?</p>
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.DEVNULL,</code> as keyword arguments.</p> <p>So DNS's answer, rewritten for Python 3.3+, becomes</p> <pre><code>import subprocess command = ["executable", "argument_1", "argument_2"] result = subprocess.call(command, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) </code></pre> <p>From the documentation:</p> <blockquote> <p>subprocess.DEVNULL¶</p> <p>Special value that can be used as the stdin, stdout or stderr argument to Popen and indicates that the special file os.devnull will be used.</p> <p>New in version 3.3.</p> </blockquote> <p>For Python 3.0 to 3.2, you have to manually open the null device using <code>open(os.devnull)</code>, as DNS wrote.</p>
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>A</code>. I want to be able to generate output from <code>B</code>, while suppressing all the output from <code>A</code>.</p> <p>From within <code>B</code>, I've tried <code>os.system('A')</code>, <code>os.system('A &gt; /dev/null')</code>, and <code>os.system('A &amp;&gt; /dev/null')</code>, <code>os.execvp('...')</code>, etc. but none of those suppress all the output from A.</p> <p>I could run <code>B &amp;&gt; /dev/null</code>, but that suppresses all of <code>B</code>'s output too and I don't want that.</p> <p>Anyone have suggestions?</p>
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 "aplay %s &amp;&gt; /dev/null &amp;"' % (filename) os.system(command) </code></pre> <p>This way I can spawn a new process, not wait for it to finish and stop it from printing to the terminal. The only catch is that it will load a bash instance as well as the process you are running, providing a slight overhead.</p>
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 before trying to read from stdin.</p>
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 before trying to read from stdin.</p>
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 before trying to read from stdin.</p>
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 it supposed to read if it doesn't read stdin?</p> <p>Is it supposed to launch a GUI? If so, you might want to have a "-i" (--interactive) option to indicate you want a GUI, not reading of stdin.</p> <p>You can, sometimes, distinguish pipes from the console because the console device is "/dev/tty", but this is not portable.</p>
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 before trying to read from stdin.</p>
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.html">http://docs.python.org/library/select.html</a></p> <pre><code>root::2832 jobs:0 [~] # cat stdin_test.py #!/usr/bin/env python import sys import select r, w, x = select.select([sys.stdin], [], [], 0) if r: print "READABLES:", r else: print "no pipe" root::2832 jobs:0 [~] # ./stdin_test.py no pipe root::2832 jobs:0 [~] # echo "foo" | ./stdin_test.py READABLES: [&lt;open file '&lt;stdin&gt;', mode 'r' at 0xb7d79020&gt;] </code></pre>
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(ActivityForm, self).__init__(*args, **kwargs) if self.initial['job_record']: jr = JobRecord.objects.get(pk=self.initial['job_record']) # Operators self.fields['operators'].queryset = jr.operators # select all operators by default self.initial['operators'] = jr.operators.values_list('id') # refined as above. </code></pre>
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(ActivityForm, self).__init__(*args, **kwargs) if self.initial['job_record']: jr = JobRecord.objects.get(pk=self.initial['job_record']) # Operators self.fields['operators'].queryset = jr.operators # select all operators by default self.initial['operators'] = jr.operators.values_list('id') # refined as above. </code></pre>
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(ActivityForm, self).__init__(*args, **kwargs) if self.initial['job_record']: jr = JobRecord.objects.get(pk=self.initial['job_record']) # Operators self.fields['operators'].queryset = jr.operators # select all operators by default self.initial['operators'] = jr.operators.values_list('id') # refined as above. </code></pre>
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 the docs:</p> <pre><code>&gt;&gt;&gt; Entry.objects.values_list('id', flat=True).order_by('id') [1, 2, 3, ...] </code></pre>
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(ActivityForm, self).__init__(*args, **kwargs) if self.initial['job_record']: jr = JobRecord.objects.get(pk=self.initial['job_record']) # Operators self.fields['operators'].queryset = jr.operators # select all operators by default self.initial['operators'] = jr.operators.values_list('id') # refined as above. </code></pre>
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): if tag.name not in VALID_TAGS: tag.hidden = True return soup.renderContents() </code></pre> <p>If you want to remove the contents of the invalid tags as well, substitute <code>tag.extract()</code> for <code>tag.hidden</code>.</p> <p>You might also look into using <a href="http://codespeak.net/lxml/" rel="nofollow">lxml</a> and <a href="http://utidylib.berlios.de/" rel="nofollow">Tidy</a>.</p>
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 soon. </p> <p>Just to be specific, not only will Beautiful Soup throw exceptions for some parsing errors which the above code doesn't catch; but also, there are plenty of very real XSS vulnerabilities that aren't caught, like:</p> <pre><code>&lt;&lt;script&gt;script&gt; alert("Haha, I hacked your page."); &lt;/&lt;/script&gt;script&gt; </code></pre> <p>Probably the best thing that you can do is instead to strip out the <code>&lt;</code> element as <code>&amp;lt;</code>, to prohibit <em>all</em> HTML, and then use a restricted subset like Markdown to render formatting properly. In particular, you can also go back and re-introduce common bits of HTML with a regex. Here's what the process looks like, roughly:</p> <pre><code>_lt_ = re.compile('&lt;') _tc_ = '~(lt)~' # or whatever, so long as markdown doesn't mangle it. _ok_ = re.compile(_tc_ + '(/?(?:u|b|i|em|strong|sup|sub|p|br|q|blockquote|code))&gt;', re.I) _sqrt_ = re.compile(_tc_ + 'sqrt&gt;', re.I) #just to give an example of extending _endsqrt_ = re.compile(_tc_ + '/sqrt&gt;', re.I) #html syntax with your own elements. _tcre_ = re.compile(_tc_) def sanitize(text): text = _lt_.sub(_tc_, text) text = markdown(text) text = _ok_.sub(r'&lt;\1&gt;', text) text = _sqrt_.sub(r'&amp;radic;&lt;span style="text-decoration:overline;"&gt;', text) text = _endsqrt_.sub(r'&lt;/span&gt;', text) return _tcre_.sub('&amp;lt;', text) </code></pre> <p>I haven't tested that code yet, so there may be bugs. But you see the general idea: you have to blacklist all HTML in general before you whitelist the ok stuff.</p>
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', 'area', 'b', 'big', 'blockquote', 'br', 'button', 'caption', 'center', 'cite', 'code', 'col', 'colgroup', 'dd', 'del', 'dfn', 'dir', 'div', 'dl', 'dt', 'em', 'font', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hr', 'i', 'img', 'ins', 'kbd', 'label', 'legend', 'li', 'map', 'menu', 'ol', 'p', 'pre', 'q', 's', 'samp', 'small', 'span', 'strike', 'strong', 'sub', 'sup', 'table', 'tbody', 'td', 'tfoot', 'th', 'thead', 'tr', 'tt', 'u', 'ul', 'var'] acceptable_attributes = ['abbr', 'accept', 'accept-charset', 'accesskey', 'action', 'align', 'alt', 'axis', 'border', 'cellpadding', 'cellspacing', 'char', 'charoff', 'charset', 'checked', 'cite', 'clear', 'cols', 'colspan', 'color', 'compact', 'coords', 'datetime', 'dir', 'enctype', 'for', 'headers', 'height', 'href', 'hreflang', 'hspace', 'id', 'ismap', 'label', 'lang', 'longdesc', 'maxlength', 'method', 'multiple', 'name', 'nohref', 'noshade', 'nowrap', 'prompt', 'rel', 'rev', 'rows', 'rowspan', 'rules', 'scope', 'shape', 'size', 'span', 'src', 'start', 'summary', 'tabindex', 'target', 'title', 'type', 'usemap', 'valign', 'value', 'vspace', 'width'] def clean_html( fragment ): while True: soup = BeautifulSoup( fragment ) removed = False for tag in soup.findAll(True): # find all tags if tag.name not in acceptable_elements: tag.extract() # remove the bad ones removed = True else: # it might have bad attributes # a better way to get all attributes? for attr in tag._getAttrMap().keys(): if attr not in acceptable_attributes: del tag[attr] # turn it back to html fragment = unicode(soup) if removed: # we removed tags and tricky can could exploit that! # we need to reparse the html until it stops changing continue # next round return fragment </code></pre> <p>Some small tests to make sure this behaves correctly:</p> <pre><code>tests = [ #text should work ('&lt;p&gt;this is text&lt;/p&gt;but this too', '&lt;p&gt;this is text&lt;/p&gt;but this too'), # make sure we cant exploit removal of tags ('&lt;&lt;script&gt;&lt;/script&gt;script&gt; alert("Haha, I hacked your page."); &lt;&lt;script&gt;&lt;/script&gt;/script&gt;', ''), # try the same trick with attributes, gives an Exception ('&lt;div on&lt;script&gt;&lt;/script&gt;load="alert("Haha, I hacked your page.");"&gt;1&lt;/div&gt;', Exception), # no tags should be skipped ('&lt;script&gt;bad&lt;/script&gt;&lt;script&gt;bad&lt;/script&gt;&lt;script&gt;bad&lt;/script&gt;', ''), # leave valid tags but remove bad attributes ('&lt;a href="good" onload="bad" onclick="bad" alt="good"&gt;1&lt;/div&gt;', '&lt;a href="good" alt="good"&gt;1&lt;/a&gt;'), ] for text, out in tests: try: res = clean_html(text) assert res == out, "%s =&gt; %s != %s" % (text, res, out) except out, e: assert isinstance(e, out), "Wrong exception %r" % e </code></pre>
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/javascript" src="evil-site"&gt;&lt;/script&gt; &lt;link rel="alternate" type="text/rss" src="evil-rss"&gt; &lt;style&gt; body {background-image: url(javascript:do_evil)}; div {color: expression(evil)}; &lt;/style&gt; &lt;/head&gt; &lt;body onload="evil_function()"&gt; &lt;!-- I am interpreted for EVIL! --&gt; &lt;a href="javascript:evil_function()"&gt;a link&lt;/a&gt; &lt;a href="#" onclick="evil_function()"&gt;another link&lt;/a&gt; &lt;p onclick="evil_function()"&gt;a paragraph&lt;/p&gt; &lt;div style="display: none"&gt;secret EVIL!&lt;/div&gt; &lt;object&gt; of EVIL! &lt;/object&gt; &lt;iframe src="evil-site"&gt;&lt;/iframe&gt; &lt;form action="evil-site"&gt; Password: &lt;input type="password" name="password"&gt; &lt;/form&gt; &lt;blink&gt;annoying EVIL!&lt;/blink&gt; &lt;a href="evil-site"&gt;spam spam SPAM!&lt;/a&gt; &lt;image src="evil!"&gt; &lt;/body&gt; &lt;/html&gt;''' </code></pre> <p>The results...</p> <pre><code>&lt;html&gt; &lt;body&gt; &lt;div&gt; &lt;style&gt;/* deleted */&lt;/style&gt; &lt;a href=""&gt;a link&lt;/a&gt; &lt;a href="#"&gt;another link&lt;/a&gt; &lt;p&gt;a paragraph&lt;/p&gt; &lt;div&gt;secret EVIL!&lt;/div&gt; of EVIL! Password: annoying EVIL! &lt;a href="evil-site"&gt;spam spam SPAM!&lt;/a&gt; &lt;img src="evil!"&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>You can customize the elements you want to clean and whatnot.</p>
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 etree from lxml.html import clean, fromstring, tostring remove_attrs = ['class'] remove_tags = ['table', 'tr', 'td'] nonempty_tags = ['a', 'p', 'span', 'div'] cleaner = clean.Cleaner(remove_tags=remove_tags) def squeaky_clean(html): clean_html = cleaner.clean_html(html) # now remove the useless empty tags root = fromstring(clean_html) context = etree.iterwalk(root) # just the end tag event for action, elem in context: clean_text = elem.text and elem.text.strip(' \t\r\n') if elem.tag in nonempty_tags and \ not (len(elem) or clean_text): # no children nor text elem.getparent().remove(elem) continue elem.text = clean_text # if you want # and if you also wanna remove some attrs: for badattr in remove_attrs: if elem.attrib.has_key(badattr): del elem.attrib[badattr] return tostring(root) </code></pre>
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/812785#812785">problem raised by Chris Drost</a>. A little crude, but does the job:</p> <pre><code>from BeautifulSoup import BeautifulSoup, Comment VALID_TAGS = {'strong': [], 'em': [], 'p': [], 'ol': [], 'ul': [], 'li': [], 'br': [], 'a': ['href', 'title'] } def sanitize_html(value, valid_tags=VALID_TAGS): soup = BeautifulSoup(value) comments = soup.findAll(text=lambda text:isinstance(text, Comment)) [comment.extract() for comment in comments] # Some markup can be crafted to slip through BeautifulSoup's parser, so # we run this repeatedly until it generates the same output twice. newoutput = soup.renderContents() while 1: oldoutput = newoutput soup = BeautifulSoup(newoutput) for tag in soup.findAll(True): if tag.name not in valid_tags: tag.hidden = True else: tag.attrs = [(attr, value) for attr, value in tag.attrs if attr in valid_tags[tag.name]] newoutput = soup.renderContents() if oldoutput == newoutput: break return newoutput </code></pre> <p><strong>Edit:</strong> Updated to support valid attributes.</p>
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 a safe solution.</p>
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.""" buf = buf.strip() if not buf: return buf p = html5lib.HTMLParser(tree=treebuilders.getTreeBuilder("dom"), tokenizer=sanitizer.HTMLSanitizer) dom_tree = p.parseFragment(buf) walker = treewalkers.getTreeWalker("dom") stream = walker(dom_tree) s = serializer.htmlserializer.HTMLSerializer( omit_optional_tags=False, quote_attr_values=True) return s.render(stream) </code></pre>
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 constructor.</p> <p>I am not talking about custom methods that know how to deal with CustomVal, but rather making it another value that I need.</p> <p>Is this possible?</p> <p>Btw 5 is just an example, in reality it's a custom COM type that I want to instance easily.</p> <p>So by referencing CustomVal, I will have access to int related functionality (for 5), or the functionality of the object that I want to represent (for COM).</p> <p>So if the COM object is RasterizedImage, then I will have access to its methods directly:</p> <pre><code>CustomVal.Raster () ... </code></pre> <p>EDIT: This is what I mean: I don't want to access as an attribute, but the object itself:</p> <pre><code>CustomVal </code></pre> <p>instead of:</p> <pre><code>CustomVal.SomeAttribute </code></pre> <p>The reason I want this is because, the COM object is too involved to initialize and by doing it this way, it will look like the original internal implementation that app offers.</p>
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><code>&gt;&gt;&gt; obj = CustomVal(wrapped_obj) &gt;&gt;&gt; obj.SomeAttributeOfWrappedObj </code></pre> <p>You can also override <code>__setattr__</code> and <code>__delattr__</code> to enable setting and deleting attributes, respectively (see <a href="http://docs.python.org/reference/datamodel.html#object.%5F%5Fgetattr%5F%5F" rel="nofollow">the Python library documentation</a>).</p>
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 constructor.</p> <p>I am not talking about custom methods that know how to deal with CustomVal, but rather making it another value that I need.</p> <p>Is this possible?</p> <p>Btw 5 is just an example, in reality it's a custom COM type that I want to instance easily.</p> <p>So by referencing CustomVal, I will have access to int related functionality (for 5), or the functionality of the object that I want to represent (for COM).</p> <p>So if the COM object is RasterizedImage, then I will have access to its methods directly:</p> <pre><code>CustomVal.Raster () ... </code></pre> <p>EDIT: This is what I mean: I don't want to access as an attribute, but the object itself:</p> <pre><code>CustomVal </code></pre> <p>instead of:</p> <pre><code>CustomVal.SomeAttribute </code></pre> <p>The reason I want this is because, the COM object is too involved to initialize and by doing it this way, it will look like the original internal implementation that app offers.</p>
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 in self._children: method(child,*args,**kwargs) return res return wrapper class Node(object): def __init__(self,name,parent=None): self._namestring = name if parent: self._parent = parent self._children = [] @map_children def decorated(self): if hasattr(self,'_parent'): print '%s (child of %s)'%(self._namestring,self._parent._namestring) else: print '%s'% self._namestring def undecorated(self): if hasattr(self,'_parent'): print '%s (child of %s)'%(self._namestring,self._parent._namestring) else: print '%s'% self._namestring for child in self._children: child.undecorated() def runme(): parent = Node('parent') child1 = Node('child1',parent) child2 = Node('child2',parent) grandchild = Node('grandchild',child1) child1._children.append(grandchild) parent._children.append(child1) parent._children.append(child2) print '**********result from decorator**********' parent.decorated() print '**********result by hand**********' parent.undecorated() </code></pre> <p>Here is the output on my system:</p> <pre> In[]:testcase.runme() **********result from decorator********** parent child1 (child of parent) child2 (child of parent) **********result by hand********** parent child1 (child of parent) grandchild (child of child1) child2 (child of parent) </pre> <p>So why does the decorated call never descend to the grandchild node? I'm obviously missing something about the syntax...</p>
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, **kwargs) </code></pre> <p>and you'll get the same output as the manual recursive version. </p>
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 server it gives a "directory not found" error but if i run the same command flat from the command prompt than it works.</p> <p>I'm sorry if my question comes off as vague but I'm totally stumped </p>
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;&gt; clean_path = os.path.normpath(path) &gt;&gt;&gt; clean_path 'F:\\dir' &gt;&gt;&gt; drive, directory = os.path.splitdrive(clean_path) &gt;&gt;&gt; drive 'F:' &gt;&gt;&gt; directory '\\dir' </code></pre> <p>Also, you might want to look into using the <a href="http://docs.python.org/library/subprocess.html" rel="nofollow">subprocess</a> module, it gives you more control over processes.</p> <p><a href="http://docs.python.org/library/subprocess.html#subprocess-replacements" rel="nofollow">Replacing Older Functions with the subprocess Module</a></p>
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:30:00' to datetime.time?</li> </ol>
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:%S') (1900, 1, 1, 7, 30, 0, 0, 1, -1) </code></pre>
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:30:00' to datetime.time?</li> </ol>
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 may be a cases where it is more pythonic to try <code>str()</code> first and use <code>except</code> to handle cases that can't be converted (ask forgiveness rather than permission). If most of the values you are trying to convert fail, on the other hand, convert them first before applying the function.</p> <p>As an unwanted aside: the <code>combine</code> function expects a datetime.date object and a datetime.time object. If you really want to avoid unpredictable behaviour, then meet the requirements of the API and pass <code>date</code> and <code>time</code> objects, rather than trying to short-circuit the contract specified by the documentation: convert the arguments <strong>before</strong> you call <code>combine</code>, rather than asking <code>combine</code> to guess for you.</p>
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:30:00' to datetime.time?</li> </ol>
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> <pre><code>t = datetime.strptime(self.start, "%H:%M:%S").time() start = datetime.combine(self.job_record.date, t) </code></pre>
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 provide an interface.</p> <p>Anyone ever go about something like this? Or else any very easy ways to add graphical interfaces to manipulate large amounts of data in python programs? Thanks!</p>
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 are worth considering as easy, (almost) no-coding web interfaces.</p>
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 provide an interface.</p> <p>Anyone ever go about something like this? Or else any very easy ways to add graphical interfaces to manipulate large amounts of data in python programs? Thanks!</p>
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 docs for Python 3</a></p>
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>def int2bin(i): if i == 0: return "0" s = '' while i: if i &amp; 1 == 1: s = "1" + s else: s = "0" + s i /= 2 return s </code></pre> <p>which will construct your binary string based on the decimal value.</p> <p>Fortunately, however, Python has something already built in, the ability to do operations such as <code>'{0:b}'.format(42)</code>, which will give you the bit pattern for <code>42</code>, or <code>101010</code>.</p> <p>The general idea is to use code from (in order of preference):</p> <ul> <li>the language or built-in libraries.</li> <li>third-party libraries with suitable licenses.</li> <li>your own collection.</li> <li>something new you need to write (and save in your own collection for later).</li> </ul>
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>'1111111111111111111111111111111111111111111111111111111111111111'</code>.</p> <p>It can be modified to serve a much larger integer, though it may not be as handy as <code>"{0:b}".format()</code> or <code>bin()</code>.</p>
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 class="lang-python prettyprint-override"><code>get_bin = lambda x, n: format(x, 'b').zfill(n) &gt;&gt;&gt; get_bin(12, 32) '00000000000000000000000000001100' &gt;&gt;&gt; get_bin(-12, 32) '-00000000000000000000000000001100' </code></pre>
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 result += str(remainder) return result[::-1] # to invert the string </code></pre>
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>I adjusted it so that the only variable being mutated is result (and n of course).</p> <p>If you need to use this function elsewhere (i.e., have the result used by another module), consider the following adjustment:</p> <pre><code>def intToBin(n): if(n &lt; 0): return -1 elif(n == 0): return str(n) else: result = "" while(n != 0): result += str(n%2) n /= 2 return result[::-1] </code></pre> <p>So -1 will be your <em>sentinel value</em> indicating the conversion failed. (This is assuming you are converting ONLY positive numbers, whether they be integers or longs).</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 string return bin_str </code></pre>
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 string.</p> <pre><code>def int2bin(val): res='' while val&gt;0: res = chr((val&amp;1) + 0x30) + res val=val&gt;&gt;1 return res </code></pre>
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 numbers. </code></pre> <p>Contributors include <a href="//stackoverflow.com/a/699892/673991" rel="nofollow">John Fouhy</a>, <a href="//stackoverflow.com/a/699891/673991" rel="nofollow">Tung Nguyen</a>, <a href="//stackoverflow.com/questions/699866#comment-29223504" rel="nofollow">mVChr</a>, <a href="http://stackoverflow.com/a/21732313/673991">Martin Thoma</a>. and Martijn Pieters.</p>
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(1000000): binary(i) t2 = time() print(t2 - t1) # 6.57236599922 </code></pre> <p>in compare to </p> <pre><code>t1 = time() for i in range(1000000): '{0:b}'.format(i) t2 = time() print(t2 - t1) # 0.68017411232 </code></pre>
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], [0, 0, 0, 0, 0, 1, 1, 1], [0, 0, 0, 1, 0, 1, 1, 1]], dtype=uint8) </code></pre>
-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></pre>
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;&gt; "{0:{fill}8b}".format(10, fill='0') '00001010' </code></pre> <p>If two's complement is required, then the following line can be used:</p> <pre><code>'{0:{fill}{width}b}'.format((x + 2**n) % 2**n, fill='0', width=n) </code></pre> <p>where n is the width of the binary string.</p>
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) b = str(5) lengthDiff = len(a) - len(b) formatted = '%s/%s' % (' '*lengthDiff + b, a) # formatted looks like:' 5/52500' </code></pre>
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).rjust(len(str(52500))) 50 </code></pre> <p>Or even:</p> <pre><code>&gt;&gt;&gt; n = 50 &gt;&gt;&gt; width = str(len(str(52500))) &gt;&gt;&gt; ('%' + width + 'd') % n ' 50' </code></pre>
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) b = str(5) lengthDiff = len(a) - len(b) formatted = '%s/%s' % (' '*lengthDiff + b, a) # formatted looks like:' 5/52500' </code></pre>
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;&gt;&gt; </code></pre>
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) b = str(5) lengthDiff = len(a) - len(b) formatted = '%s/%s' % (' '*lengthDiff + b, a) # formatted looks like:' 5/52500' </code></pre>
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('52500'),) s = fmt % (5,) </code></pre>
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) b = str(5) lengthDiff = len(a) - len(b) formatted = '%s/%s' % (' '*lengthDiff + b, a) # formatted looks like:' 5/52500' </code></pre>
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 specify the width AND render the number without any further python string manipulation. </p> <p>Here is a solution using math.log to ascertain the length of the 'outof' number.</p> <pre><code>import math num = 5 outof = 52500 formatted = '%*d/%d' % (int(math.ceil(math.log(outof, 10))), num, outof) </code></pre> <p>Another solution involves casting the outof number as a string and using len(), you can do that if you prefer:</p> <pre><code>num = 5 outof = 52500 formatted = '%*d/%d' % (len(str(outof)), num, outof) </code></pre>
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) b = str(5) lengthDiff = len(a) - len(b) formatted = '%s/%s' % (' '*lengthDiff + b, a) # formatted looks like:' 5/52500' </code></pre>
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 partial result). I suppose this will need some kind of signal receiving or reading from pipes, but I want to keep it as simple as possible.</p> <p>What would you consider the best approach to solve this kind of problem? I am able to change the code on both the python and C sides.</p>
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 partial result). I suppose this will need some kind of signal receiving or reading from pipes, but I want to keep it as simple as possible.</p> <p>What would you consider the best approach to solve this kind of problem? I am able to change the code on both the python and C sides.</p>
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 partial result). I suppose this will need some kind of signal receiving or reading from pipes, but I want to keep it as simple as possible.</p> <p>What would you consider the best approach to solve this kind of problem? I am able to change the code on both the python and C sides.</p>
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 answer to the second question will probably dictate the answer to the first. You could do it by signals (in which case you get a signal handler that gets control of the process, can look for more detailed instructions elsewhere, and change your internal data structures before returning control to your function), or you could have your function monitor a control interface for commands (every millisecond, check to see if there's a command waiting, and if there is, see what it is).</p> <p>In the first case, you'd want ANSI C signal handling (signal(), sighandler_t), in the second you'd probably want a pipe or similar (pipe() and select()).</p>
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 partial result). I suppose this will need some kind of signal receiving or reading from pipes, but I want to keep it as simple as possible.</p> <p>What would you consider the best approach to solve this kind of problem? I am able to change the code on both the python and C sides.</p>
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 second run time to strike a balance between responsiveness and low overhead. It can be tough to break up calculations into even chunks like this in the face of changing data sizes, but you would have the same challenge in a single big function that also did I/O.</p> <p>Write a worker process in Python that calls those 3 functions through ctypes. Have the worker process check a <a href="http://docs.python.org/library/queue.html" rel="nofollow">Queue</a> object for a message from the GUI to stop the calculation early. Make sure to use the non-blocking Queue.get_nowait call instead of Queue.get. If the worker process finds a message to quit early, call the C clean up code and return the partial result. </p>
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.</p>
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.</p>
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.</p>
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> <pre><code>logger.py fstools.py ... </code></pre> <p>This allows to directly import these modules from other scripts:</p> <pre><code>import logger log = logger.Log() ... </code></pre>
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. &gt;&gt;&gt; import site, sys &gt;&gt;&gt; site.addsitedir('test') &gt;&gt;&gt; sys.path[-3:] ['/tmp/test', '/tmp/test/foo', '/tmp/test/bar'] </code></pre>
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 and provide them with a dedicated webdav user-specific area.</p> <p>Any hints?</p>
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>, <code>&lt;Directory&gt;</code> (etc) area that you are trying to protect:</p> <pre><code>&lt;Directory /usr/www/myhost/private&gt; # other config ere # mod_authn_dbd SQL query to authenticate a user AuthDBDUserPWQuery \ "SELECT password FROM authn WHERE user = %s" &lt;/Directory&gt; </code></pre> <p>Strictly speaking, this means you're authenticating against Django's database, not against the Django app itself. Note that you have full control over the query, so you CAN combine it with other parameters in any tables to make sure the user is in good standing, or in certain groups, or whatever, before allowing the authentication.</p> <p>You may need to fuss around a bit to make sure the hashing mechanisms used are the same in both apache and django.</p> <p>If this doesn't suit, consider moving your authentication out of the django database into, say, an LDAP server. With a custom authentication backend (there are existing LDAP implementations for django out there), django will happily use LDAP... and LDAP auth/auth support in Apache is quite robust.</p>
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 and provide them with a dedicated webdav user-specific area.</p> <p>Any hints?</p>
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 and provide them with a dedicated webdav user-specific area.</p> <p>Any hints?</p>
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 separated from other users. Assuming the following WebDAV setup in the Apache virtual sites configuration (customarily in <em>/etc/apache2/sites-enabled/</em>)</p> <pre><code>&lt;Directory /webdav/root/on/server&gt; DAV On # No .htaccess allowed AllowOverride None Options Indexes AuthType Basic AuthName "Login to your webdav area" Require valid-user AuthBasicProvider wsgi WSGIAuthUserScript /where/is/the/authentication-script.wsgi &lt;/Directory&gt; </code></pre> <p>Note how there's no public address for WebDav set up yet. This, and the user area thing, is fixed in two lines in the same config file (put these after the ending clause):</p> <pre><code>RewriteEngine On RewriteRule ^/webdav-url/(.*?)$ /webdav/root/on/server/%{LA-U:REMOTE_USER}/$1 </code></pre> <p>Now, webdav is accessed on <a href="http://my-server.com/webdav-url/" rel="nofollow">http://my-server.com/webdav-url/</a> The user gets a login prompt and will then land in a subdirectory to the webdav root, having the same name as their username. <em>LA-U:</em> makes Apache "look ahead" and let the user sign in <em>before</em> determining the mounting path, which is crucial since that path depends on the user name. Without some rewrite-rule there will be no URL, and the user won't get a login prompt. In other words, LA-U avoids a catch-22 for this type of login handling.</p> <p><strong>Precautions</strong>: requires mod_rewrite to be enabled, and user names must be valid as dir names without any modification. Also, the user dirs won't be created automatically by these commands, so their existence must be assured in some other way.</p>
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 latest item. Also I have seen feed readers displaying the same item published with slightly different content as seperate items. I am not implementing a feed reader application, I just want a sane strategy for archiving feed data.</p>
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 cover most cases, it's conceivable that a source might publish multiple items with the same id. In that case, you don't have much choice but to hash the item's content.</p>
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) self.fp.close() selffp=file("detailing.dat","rb") [databasename,host,user,password]=pickle.load(self.fp) return </code></pre> <p>It has the error:</p> <pre><code>Traceback (most recent call last): File "detailing.py", line 91, in ? app=myApp() File "detailing.py", line 20, in __init__ wx.App.__init__(self,redirect,filename,useBestVisual,clearSigInt) File "/usr/lib64/python2.4/site-packages/wx-2.6-gtk2-unicode/wx/_core.py", line 7473, in __init__ self._BootstrapApp() File "/usr/lib64/python2.4/site-packages/wx-2.6-gtk2-unicode/wx/_core.py", line 7125, in _BootstrapApp return _core_.PyApp__BootstrapApp(*args, **kwargs) File "detailing.py", line 33, in OnInit self.database() File "detailing.py", line 87, in database [databasename,host,user,password]=pickle.load(self.fp) File "/usr/lib64/python2.4/pickle.py", line 1390, in load return Unpickler(file).load() File "/usr/lib64/python2.4/pickle.py", line 872, in load dispatch[key](self) File "/usr/lib64/python2.4/pickle.py", line 894, in load_eof raise EOFError EOFError </code></pre> <p>What am I doing wrong?</p>
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 that the file actually has contents (ie: that the previous pickle worked)... the error suggests that the file is empty.</p> <p>Edit: In the comments to this answer, S. Lott has a nice summary of why the typo generated the error you saw that I'm pasting here for completeness of the answer: "selffp will be the unused opened file, and self.fp (the old closed file) will be used for the load".</p>
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) self.fp.close() selffp=file("detailing.dat","rb") [databasename,host,user,password]=pickle.load(self.fp) return </code></pre> <p>It has the error:</p> <pre><code>Traceback (most recent call last): File "detailing.py", line 91, in ? app=myApp() File "detailing.py", line 20, in __init__ wx.App.__init__(self,redirect,filename,useBestVisual,clearSigInt) File "/usr/lib64/python2.4/site-packages/wx-2.6-gtk2-unicode/wx/_core.py", line 7473, in __init__ self._BootstrapApp() File "/usr/lib64/python2.4/site-packages/wx-2.6-gtk2-unicode/wx/_core.py", line 7125, in _BootstrapApp return _core_.PyApp__BootstrapApp(*args, **kwargs) File "detailing.py", line 33, in OnInit self.database() File "detailing.py", line 87, in database [databasename,host,user,password]=pickle.load(self.fp) File "/usr/lib64/python2.4/pickle.py", line 1390, in load return Unpickler(file).load() File "/usr/lib64/python2.4/pickle.py", line 872, in load dispatch[key](self) File "/usr/lib64/python2.4/pickle.py", line 894, in load_eof raise EOFError EOFError </code></pre> <p>What am I doing wrong?</p>
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,password],fp,-1) self.fp=open("detailing.dat","rb") [databasename,host,user,password]=pickle.load(self.fp) return </code></pre> <p>As has been pointed out, there was a typo on self.fp. But here are a few other things that I notice that can cause problems.</p> <p>First of all, you <a href="http://docs.python.org/library/functions.html#file">shouldn't be using the file constructor directly</a>. You should instead use the built-in open function.</p> <p>Secondly, you should avoid calling a file's close method outside a finally block. In this case, I've used python 2.6's with block. You can use this in Python 2.5 with the following command:</p> <pre><code>from __future__ import with_statement </code></pre> <p>This will prevent the file from being stuck open if an exception is thrown anywhere (as it will close the file when the with block is exited). Although this isn't the cause of your problem, it is an important thing to remember because if one of the file object's methods throws an exception, the file will get held open in sys.traceback indefinitely.</p> <p>(note that you should probably accept Jarret Hardie's answer though, he caught the bug :-) )</p>
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) self.fp.close() selffp=file("detailing.dat","rb") [databasename,host,user,password]=pickle.load(self.fp) return </code></pre> <p>It has the error:</p> <pre><code>Traceback (most recent call last): File "detailing.py", line 91, in ? app=myApp() File "detailing.py", line 20, in __init__ wx.App.__init__(self,redirect,filename,useBestVisual,clearSigInt) File "/usr/lib64/python2.4/site-packages/wx-2.6-gtk2-unicode/wx/_core.py", line 7473, in __init__ self._BootstrapApp() File "/usr/lib64/python2.4/site-packages/wx-2.6-gtk2-unicode/wx/_core.py", line 7125, in _BootstrapApp return _core_.PyApp__BootstrapApp(*args, **kwargs) File "detailing.py", line 33, in OnInit self.database() File "detailing.py", line 87, in database [databasename,host,user,password]=pickle.load(self.fp) File "/usr/lib64/python2.4/pickle.py", line 1390, in load return Unpickler(file).load() File "/usr/lib64/python2.4/pickle.py", line 872, in load dispatch[key](self) File "/usr/lib64/python2.4/pickle.py", line 894, in load_eof raise EOFError EOFError </code></pre> <p>What am I doing wrong?</p>
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(words)) with open("words.pkl", "wb") as f: pickle.dump(A, f) #...later open the file -- mistake:trying to read a binary with non-binary method with open("words.pkl", "r") as f: A =pickle.load(f) # EOFError # change that to with open ("words.pkl", "rb") as f: # notice the "rb" instead of "r" A = pickle.load(f) </code></pre>
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) self.fp.close() selffp=file("detailing.dat","rb") [databasename,host,user,password]=pickle.load(self.fp) return </code></pre> <p>It has the error:</p> <pre><code>Traceback (most recent call last): File "detailing.py", line 91, in ? app=myApp() File "detailing.py", line 20, in __init__ wx.App.__init__(self,redirect,filename,useBestVisual,clearSigInt) File "/usr/lib64/python2.4/site-packages/wx-2.6-gtk2-unicode/wx/_core.py", line 7473, in __init__ self._BootstrapApp() File "/usr/lib64/python2.4/site-packages/wx-2.6-gtk2-unicode/wx/_core.py", line 7125, in _BootstrapApp return _core_.PyApp__BootstrapApp(*args, **kwargs) File "detailing.py", line 33, in OnInit self.database() File "detailing.py", line 87, in database [databasename,host,user,password]=pickle.load(self.fp) File "/usr/lib64/python2.4/pickle.py", line 1390, in load return Unpickler(file).load() File "/usr/lib64/python2.4/pickle.py", line 872, in load dispatch[key](self) File "/usr/lib64/python2.4/pickle.py", line 894, in load_eof raise EOFError EOFError </code></pre> <p>What am I doing wrong?</p>
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 binary file somehow "damages" the file which is then not openable whatsoever afterward.</p> <p>But I am quite a beginner with Python so I may have miss something too.</p>
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 and save them in some kind of database to provide some kind of search later.</p> <p>What my question is, what would be the best way to desing this? For sure all them have to happen in saperate threads, but what I'm wondering is how to pass information between them the best way? What kind of signal passing / thread locking available in Python should I use to avoid possible problems?</p>
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" rel="nofollow">PyGTK and Threading</a> article interesting.</p>
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 and save them in some kind of database to provide some kind of search later.</p> <p>What my question is, what would be the best way to desing this? For sure all them have to happen in saperate threads, but what I'm wondering is how to pass information between them the best way? What kind of signal passing / thread locking available in Python should I use to avoid possible problems?</p>
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 the builtin script?</p> <p>Does the builtin tool explicitly convert all the returned iterators into lists, for compatibility? If so then the lower memory footprint benefit of Py3k is not really apparent in the converted programs. Is it?</p>
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 creating a new list with a copy of the keys.</p> <p>How this affects memory footprints probably depends on the program. Certainly there's more of an emphasis towards using iterators unless you really need lists, whereas using lists was generally the default case in python2. That will cause the average program to probably be more memory efficient. Cases where there are really big savings are probably going to already be implemented as iterators in python2 programs however, as really large memory usage will stand out, and is more likely to be already addressed. (eg. the file iterator is already much more memory efficient than the older <code>file.readlines()</code> method)</p> <p>Converting is done by the 2to3 tool, and will generally convert things like range() to iterators where it can safely determine a real list isn't needed, so code like:</p> <pre><code>for x in range(10): print x </code></pre> <p>will switch to the new range() object, no longer creating a list, and so will obtain the reduced memory benefit, but code like:</p> <pre><code>x = range(20) </code></pre> <p>will be converted as:</p> <pre><code>x = list(range(20)) </code></pre> <p>as the converter can't know if the code expects a <em>real</em> list object in x.</p>
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 the builtin script?</p> <p>Does the builtin tool explicitly convert all the returned iterators into lists, for compatibility? If so then the lower memory footprint benefit of Py3k is not really apparent in the converted programs. Is it?</p>
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 the memory footprint of python is going to reduce drastically. Isn't it?</p> </blockquote> <p>It depends. I'd guess that the average program wouldn't notice a <em>huge</em> difference though. The performance advantages of iterators over lists is really only significant if you have a large dataset. You may want to see <a href="http://stackoverflow.com/questions/628903/performance-advantages-to-iterators">this question</a>.</p>
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 the builtin script?</p> <p>Does the builtin tool explicitly convert all the returned iterators into lists, for compatibility? If so then the lower memory footprint benefit of Py3k is not really apparent in the converted programs. Is it?</p>
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>Now take for instance:</p> <pre><code>for i in xrange(1000000): # starts loop almost immediately if i == 0: break # we did't waste time even if we break early </code></pre> <p>Although the example is contrived, the use case isn't: loops are often broken out of mid-way. Building an entire list to only use part of it is a waste unless you are going to use it more than once. If that is the case, you can explicitly build a list: <code>r = list(range(100))</code>. This is why iterators are the default in more places in Python 3; you aren't out anything since you can still explicitly create lists (or other containers) when you need. But you aren't forced to when all you plan to do is iterate over an iterable once (which I would argue is the much more common case).</p>
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. It would be far better to use a class that somebody else has developed rather than spend a huge amount of my own time debugging a home-made caching system.</p> <p>Java developers have this: <a href="http://ehcache.sourceforge.net/" rel="nofollow">http://ehcache.sourceforge.net/</a></p> <p>It's a general purpose high-performance caching class which can support all kinds of storage. It's got options for time-based expiry and other methods for garbage-collecting. It looks really good. Unfortunately I cannot find anything this good for Python.</p> <p>So, can somebody suggest a cache-class that's ready for me to use. My wish-list is:</p> <ul> <li>Ability to limit the number of objects in the cache.</li> <li>Ability to limit the maximum age of objects in the cache.</li> <li>LRU object expirey</li> <li>Ability to select multiple forms of storage ( e.g. memory, disk )</li> <li>Well debugged, well maintained, in use by at least one well-known application.</li> <li>Good performance.</li> </ul> <p>So, any suggestions?</p> <p>UPDATE: I'm looking for LOCAL caching of objects. The server which I connect to is already heavily cached. Memcached is not appropriate because it requires an additional network traffic between the Windows client and the server. </p>
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 it uses. And memcached is used by a lot of big names. In fact, I'd call it kind of the industry standard.</p> <p><strong>UPDATE</strong>:</p> <blockquote> <p>I'm looking for LOCAL caching of objects.</p> </blockquote> <p>You can run memcached locally and access it via localhost. I've done this a few times.</p> <p>Other than that, the only solution that I can think of is <a href="http://docs.djangoproject.com/en/1.0/topics/cache/" rel="nofollow">django's caching system</a>. It offers several backends and some other configuration options. But that may be a little bit heavyweight if you're not using django.</p> <p><strong>UPDATE 2:</strong> I suppose as a last resort, you can also use <a href="http://www.jython.org/Project/" rel="nofollow">jython</a> and access the java caching system. This may be a little difficult to do if you've already got clients using CPython though.</p> <p><strong>UPDATE 3:</strong> It's probably a bit late to be of use to you, but a previous employer of mine used <a href="http://www.zodb.org/" rel="nofollow">ZODB</a> for this kind of thing. It's an actual database, but its read performance is fast enough to make it useful for caching.</p>
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 particularly bad, or is there a particularly better way?</p>
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 only in python.</p>
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 particularly bad, or is there a particularly better way?</p>
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 particularly bad, or is there a particularly better way?</p>
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.listdir(path) index = random.randrange(0, len(files)) return files[index] </code></pre> <p><strong>EDIT</strong>: The question now mentions a fear of a "race condition", which I can only assume is the typical problem of files being added/removed while you are in the process of trying to pick a random file.</p> <p>I don't believe there is a way around that, other than keeping in mind that any I/O operation is inherently "unsafe", i.e. it can fail. So, the algorithm to open a randomly chosen file in a given directory should:</p> <ul> <li>Actually <code>open()</code> the file selected, and handle a failure, since the file might no longer be there</li> <li>Probably limit itself to a set number of tries, so it doesn't die if the directory is empty or if none of the files are readable</li> </ul>
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 particularly bad, or is there a particularly better way?</p>
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 since 2.6, and removed in 3.0</a>.</p> <p>Second of all, I don't see where any race condition exists here. Your <code>dircache</code> object is basically immutable (after directory listing is cached, it is never read again), so no harm in concurrent reads from it.</p> <p>Other than that, I do not understand why you see any problem with this solution. It is fine.</p>
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 particularly bad, or is there a particularly better way?</p>
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 particularly bad, or is there a particularly better way?</p>
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> <pre><code>if hasattr(a, 'method1'): a.method1() else if hasattr(a, 'method2'): a.method2() else if hasattr(a, 'method3'): a.method3() else: raise AttributeError </code></pre> <p>to maintain maximum efficiency.</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: raise </code></pre>
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> <pre><code>if hasattr(a, 'method1'): a.method1() else if hasattr(a, 'method2'): a.method2() else if hasattr(a, 'method3'): a.method3() else: raise AttributeError </code></pre> <p>to maintain maximum efficiency.</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:</p> <pre><code>call_attrs(a, ['method1', 'method2', 'method3']) </code></pre> <p>This will try to call the methods in the order they are in in the list. If you wanted to pass any arguments, you could just pass them along after the list like so:</p> <pre><code>call_attrs(a, ['method1', 'method2', 'method3'], arg1, arg2) </code></pre>
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> <pre><code>if hasattr(a, 'method1'): a.method1() else if hasattr(a, 'method2'): a.method2() else if hasattr(a, 'method3'): a.method3() else: raise AttributeError </code></pre> <p>to maintain maximum efficiency.</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 AttributeError </code></pre> <p>Of course, if you aren't using a new-style object, you may try <code>__dict__</code> instead of <code>__getattribute__</code>.</p> <p>EDIT: This code might prove to be a screaming mess. If <code>__getattribute__</code> or <code>__dict__</code> is not found, take a wild guess what kind of error is raised.</p>
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> <pre><code>if hasattr(a, 'method1'): a.method1() else if hasattr(a, 'method2'): a.method2() else if hasattr(a, 'method3'): a.method3() else: raise AttributeError </code></pre> <p>to maintain maximum efficiency.</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, methodname) except AttributeError: pass else: return m() raise AttributeError </code></pre> <p>The other very readable way is to do..</p> <pre><code>def something(a): try: return a.method1() except: pass try: return a.method2() except: pass try: return a.method3() except: pass raise AttributeError </code></pre> <p>While long, it's very obvious what the function is doing.. Performance really shouldn't be an issue (if a few try/except statements slow your script down noticeably, there is probably a bigger issue with the script structure)</p>
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> <pre><code>if hasattr(a, 'method1'): a.method1() else if hasattr(a, 'method2'): a.method2() else if hasattr(a, 'method3'): a.method3() else: raise AttributeError </code></pre> <p>to maintain maximum efficiency.</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> <pre><code>if hasattr(a, 'method1'): a.method1() else if hasattr(a, 'method2'): a.method2() else if hasattr(a, 'method3'): a.method3() else: raise AttributeError </code></pre> <p>to maintain maximum efficiency.</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 found. If none of the methods are found the last <code>getattr</code> will raise an exception.</p>
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-codes-to-text">HTML Entity Codes to Text</a></li> </ul> </blockquote> <p>How do you convert HTML entities to Unicode and vice versa in Python?</p>
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(BeautifulStoneSoup(text, convertEntities=BeautifulStoneSoup.ALL_ENTITIES)) return text def unicodeToHTMLEntities(text): """Converts unicode to HTML entities. For example '&amp;' becomes '&amp;amp;'.""" text = cgi.escape(text).encode('ascii', 'xmlcharrefreplace') return text text = "&amp;amp;, &amp;reg;, &amp;lt;, &amp;gt;, &amp;cent;, &amp;pound;, &amp;yen;, &amp;euro;, &amp;sect;, &amp;copy;" uni = HTMLEntitiesToUnicode(text) htmlent = unicodeToHTMLEntities(uni) print uni print htmlent # &amp;, ®, &lt;, &gt;, ¢, £, ¥, €, §, © # &amp;amp;, &amp;#174;, &amp;lt;, &amp;gt;, &amp;#162;, &amp;#163;, &amp;#165;, &amp;#8364;, &amp;#167;, &amp;#169; </code></pre>
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-codes-to-text">HTML Entity Codes to Text</a></li> </ul> </blockquote> <p>How do you convert HTML entities to Unicode and vice versa in Python?</p>
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></pre> <p>will return a plain string with any non-ascii characters turned into XML (HTML) entities.</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-codes-to-text">HTML Entity Codes to Text</a></li> </ul> </blockquote> <p>How do you convert HTML entities to Unicode and vice versa in Python?</p>
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>, the function won't escape single quotes (<code>"'"</code>) (Because of these issues the function has been <a href="https://docs.python.org/dev/library/cgi.html#cgi.escape" rel="nofollow">deprecated</a> since version 3.2)</p> <p>It's been suggested to use <code>html.escape(s)</code> instead of <code>cgi.escape(s)</code>. (New in version 3.2)</p> <p>Also <code>html.unescape(s)</code> has been <a href="https://docs.python.org/dev/library/html.html#html.unescape" rel="nofollow">introduced in version 3.4</a>.</p> <p>So in python 3.4 you can:</p> <ul> <li>Use <code>html.escape(text).encode('ascii', 'xmlcharrefreplace').decode()</code> to convert special characters to HTML entities.</li> <li>And <code>html.unescape(text)</code> for converting HTML entities back to plain-text representations.</li> </ul>
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-codes-to-text">HTML Entity Codes to Text</a></li> </ul> </blockquote> <p>How do you convert HTML entities to Unicode and vice versa in Python?</p>
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><code>unsubbed = u'Monsieur le Curé of the «Notre-Dame-de-Grâce» neighborhood' </code></pre> <p>Unicode to unicode HTML ('escaped') with <code>bs4</code>:</p> <pre><code>&gt;&gt;&gt; from bs4.dammit import EntitySubstitution &gt;&gt;&gt; esub = EntitySubstitution() &gt;&gt;&gt; subbed = esub.substitute_html(unsubbed) &gt;&gt;&gt; subbed u'Monsieur le Cur&amp;eacute; of the &amp;laquo;Notre-Dame-de-Gr&amp;acirc;ce&amp;raquo; neighborhood' </code></pre> <p>Unicode HTML to unicode ('unescaped') with <code>htmlparser</code> (standard lib):</p> <pre><code>&gt;&gt;&gt; from HTMLParser import HTMLParser &gt;&gt;&gt; htmlparser = HTMLParser() &gt;&gt;&gt; unsubbed = htmlparser.unescape(subbed) &gt;&gt;&gt; unsubbed u'Monsieur le Cur\xe9 of the \xabNotre-Dame-de-Gr\xe2ce\xbb neighborhood' &gt;&gt;&gt; print unsubbed Monsieur le Curé of the «Notre-Dame-de-Grâce» neighborhood </code></pre> <p>Unicode HTML to unicode ('unescaped') with <code>bs4</code>:</p> <pre><code>&gt;&gt;&gt; from bs4 import BeautifulSoup &gt;&gt;&gt; soup = BeautifulSoup(subbed) &gt;&gt;&gt; soup.text u'Monsieur le Cur\xe9 of the \xabNotre-Dame-de-Gr\xe2ce\xbb neighborhood' &gt;&gt;&gt; print soup.text Monsieur le Curé of the «Notre-Dame-de-Grâce» neighborhood </code></pre>
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</a></p>
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" ]