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
sequence |
---|---|---|---|---|---|---|---|---|---|
Scrape a dynamic website | 206,855 | <p>What is the best method to scrape a dynamic website where most of the content is generated by what appears to be ajax requests? I have previous experience with a Mechanize, BeautifulSoup, and python combo, but I am up for something new.</p>
<p>--Edit--
For more detail: I'm trying to scrape the CNN <a href="http://www.cnn.com/ELECTION/2008/primaries/results/state/">primary database</a>. There is a wealth of information there, but there doesn't appear to be an api.</p>
| 12 | 2008-10-15T23:04:13Z | 216,143 | <p>The best solution that I found was to use Firebug to monitor XmlHttpRequests, and then to use a script to resend them.</p>
| 7 | 2008-10-19T07:38:59Z | [
"python",
"ajax",
"screen-scraping",
"beautifulsoup"
] |
Scrape a dynamic website | 206,855 | <p>What is the best method to scrape a dynamic website where most of the content is generated by what appears to be ajax requests? I have previous experience with a Mechanize, BeautifulSoup, and python combo, but I am up for something new.</p>
<p>--Edit--
For more detail: I'm trying to scrape the CNN <a href="http://www.cnn.com/ELECTION/2008/primaries/results/state/">primary database</a>. There is a wealth of information there, but there doesn't appear to be an api.</p>
| 12 | 2008-10-15T23:04:13Z | 216,161 | <p>Probably the easiest way is to use IE webbrowser control in C# (or any other language). You have access to all the stuff inside browser out of the box + you dont need to care about cookies, SSL and so on.</p>
| 1 | 2008-10-19T08:03:11Z | [
"python",
"ajax",
"screen-scraping",
"beautifulsoup"
] |
Scrape a dynamic website | 206,855 | <p>What is the best method to scrape a dynamic website where most of the content is generated by what appears to be ajax requests? I have previous experience with a Mechanize, BeautifulSoup, and python combo, but I am up for something new.</p>
<p>--Edit--
For more detail: I'm trying to scrape the CNN <a href="http://www.cnn.com/ELECTION/2008/primaries/results/state/">primary database</a>. There is a wealth of information there, but there doesn't appear to be an api.</p>
| 12 | 2008-10-15T23:04:13Z | 219,990 | <p>There is a bit of a learning curve, but tools like Pamie (Python) or Watir (Ruby) will let you latch into the IE web browser and get at the elements. This turns out to be easier than Mechanize and other HTTP level tools since you don't have to emulate the browser, you just ask the browser for the html elements. And it's going to be way easier than reverse engineering the Javascript/Ajax calls. If needed you can also use tools like beatiful soup in conjunction with Pamie.</p>
| 2 | 2008-10-20T21:22:06Z | [
"python",
"ajax",
"screen-scraping",
"beautifulsoup"
] |
Scrape a dynamic website | 206,855 | <p>What is the best method to scrape a dynamic website where most of the content is generated by what appears to be ajax requests? I have previous experience with a Mechanize, BeautifulSoup, and python combo, but I am up for something new.</p>
<p>--Edit--
For more detail: I'm trying to scrape the CNN <a href="http://www.cnn.com/ELECTION/2008/primaries/results/state/">primary database</a>. There is a wealth of information there, but there doesn't appear to be an api.</p>
| 12 | 2008-10-15T23:04:13Z | 642,138 | <p>i found the IE Webbrowser control have all kinds of quirks and workarounds that would justify some high quality software to take care of all those inconsistencies, layered around the shvwdoc.dll api and mshtml and provide a framework. </p>
| 1 | 2009-03-13T10:47:39Z | [
"python",
"ajax",
"screen-scraping",
"beautifulsoup"
] |
Scrape a dynamic website | 206,855 | <p>What is the best method to scrape a dynamic website where most of the content is generated by what appears to be ajax requests? I have previous experience with a Mechanize, BeautifulSoup, and python combo, but I am up for something new.</p>
<p>--Edit--
For more detail: I'm trying to scrape the CNN <a href="http://www.cnn.com/ELECTION/2008/primaries/results/state/">primary database</a>. There is a wealth of information there, but there doesn't appear to be an api.</p>
| 12 | 2008-10-15T23:04:13Z | 8,997,123 | <p>The first question I have: can you confirm that the site absolutely doesn't work without Javascript? You'd be surprised how many sites are still usable if you turn javascript off. You'll probably be directed to a slightly different set of urls. </p>
| 0 | 2012-01-25T02:21:13Z | [
"python",
"ajax",
"screen-scraping",
"beautifulsoup"
] |
Help with <key> event in python Entry widget | 206,916 | <p>I'm writing some code in python and I'm having trouble when trying to retrieve content of an Entry widget.
The thing is: I want to limit the characters that can be typed, so I'm trying to clear the Entry widget when I reach the specific number of characters (2 in this case), but it looks like I always miss the last typed character. I added the lost character in a print to show.</p>
<p>Here's the sample code:</p>
<pre><code>from Tkinter import *
class sampleFrame:
def __init__(self, master):
self.__frame = Frame(master)
self.__frame.pack()
def get_frame(self):
return self.__frame
class sampleClass:
def __init__(self, master):
self.__aLabel = Label(master,text="aLabel", width=10)
self.__aLabel.pack(side=LEFT)
self.__aEntry = Entry (master, width=2)
self.__aEntry.bind('<Key>', lambda event: self.callback(event, self.__aEntry))
self.__aEntry.pack(side=LEFT)
def callback(self, event, widgetName):
self.__value = widgetName.get()+event.char
print self.__value
if len(self.__value)>2:
widgetName.delete(2,4)
root = Tk()
aSampleFrame = sampleFrame(root)
aSampleClass = sampleClass(aSampleFrame.get_frame())
root.mainloop()
</code></pre>
<p>Any help will be much appreciated!</p>
<p>Thanks in advance</p>
| 1 | 2008-10-15T23:35:52Z | 207,018 | <p>At first, after you do the deletion, the event goes on with its normal processing, i.e. the character gets inserted. You need to signal to Tkinter that the event should be ignored.</p>
<p>So in your code above, add the marked line:</p>
<pre><code>if len(self.__value) > 2:
widgetName.delete(2,4)
return "break" # add this line
</code></pre>
<p>On the other hand, why do you go through the lambda? An event has a .widget attribute which you can use. So you can change your code into:</p>
<pre><code> self.__aEntry.bind('<Key>', self.callback) # â» here!
self.__aEntry.pack(side=LEFT)
def callback(self, event):
self.__value = event.widget.get()+event.char # â» here!
print self.__value
if len(self.__value)>2:
event.widget.delete(2,4) # â» here!
return "break"
</code></pre>
<p>All the changed lines are marked with "here!"</p>
| 3 | 2008-10-16T00:30:58Z | [
"python",
"events",
"widget",
"tkinter"
] |
Help with <key> event in python Entry widget | 206,916 | <p>I'm writing some code in python and I'm having trouble when trying to retrieve content of an Entry widget.
The thing is: I want to limit the characters that can be typed, so I'm trying to clear the Entry widget when I reach the specific number of characters (2 in this case), but it looks like I always miss the last typed character. I added the lost character in a print to show.</p>
<p>Here's the sample code:</p>
<pre><code>from Tkinter import *
class sampleFrame:
def __init__(self, master):
self.__frame = Frame(master)
self.__frame.pack()
def get_frame(self):
return self.__frame
class sampleClass:
def __init__(self, master):
self.__aLabel = Label(master,text="aLabel", width=10)
self.__aLabel.pack(side=LEFT)
self.__aEntry = Entry (master, width=2)
self.__aEntry.bind('<Key>', lambda event: self.callback(event, self.__aEntry))
self.__aEntry.pack(side=LEFT)
def callback(self, event, widgetName):
self.__value = widgetName.get()+event.char
print self.__value
if len(self.__value)>2:
widgetName.delete(2,4)
root = Tk()
aSampleFrame = sampleFrame(root)
aSampleClass = sampleClass(aSampleFrame.get_frame())
root.mainloop()
</code></pre>
<p>Any help will be much appreciated!</p>
<p>Thanks in advance</p>
| 1 | 2008-10-15T23:35:52Z | 225,872 | <p>To be a bit more specific, Tk widgets have what are called "bindtags". When an event is processed, each bindtag on the widget is considered in order to see if it has a binding. A widget by default will have as its bindtags the widget, the widget class, the root widget, and "all". Thus, bindings to the widget will occur before the default bindings. Once your binding has been processed you can prevent any further bindtags from being considered by returning a "break".</p>
<p>The ramifications are this: if you make a binding on the widget, the class, root window and "all" bindings may fire as well. In addition, any binding you attach to the widget fires <em>before</em> the class binding which is where the default behavior (eg: the insertion of a character) happens. It is important to be aware of that in situations where you may want to handle the event after the default behavior rather than before.</p>
| 1 | 2008-10-22T14:06:30Z | [
"python",
"events",
"widget",
"tkinter"
] |
Python: Difference between class and instance attributes | 207,000 | <p>Is there any meaningful distinction between:</p>
<pre><code>class A(object):
foo = 5 # some default value
</code></pre>
<p>vs.</p>
<pre><code>class B(object):
def __init__(self, foo=5):
self.foo = foo
</code></pre>
<p>If you're creating a lot of instances, is there any difference in performance or space requirements for the two styles? When you read the code, do you consider the meaning of the two styles to be significantly different?</p>
| 84 | 2008-10-16T00:23:41Z | 207,128 | <p>Beyond performance considerations, there is a significant <em>semantic</em> difference. In the class attribute case, there is just one object referred to. In the instance-attribute-set-at-instantiation, there can be multiple objects referred to. For instance</p>
<pre><code>>>> class A: foo = []
>>> a, b = A(), A()
>>> a.foo.append(5)
>>> b.foo
[5]
>>> class A:
... def __init__(self): self.foo = []
>>> a, b = A(), A()
>>> a.foo.append(5)
>>> b.foo
[]
</code></pre>
| 100 | 2008-10-16T01:26:53Z | [
"python",
"attributes"
] |
Python: Difference between class and instance attributes | 207,000 | <p>Is there any meaningful distinction between:</p>
<pre><code>class A(object):
foo = 5 # some default value
</code></pre>
<p>vs.</p>
<pre><code>class B(object):
def __init__(self, foo=5):
self.foo = foo
</code></pre>
<p>If you're creating a lot of instances, is there any difference in performance or space requirements for the two styles? When you read the code, do you consider the meaning of the two styles to be significantly different?</p>
| 84 | 2008-10-16T00:23:41Z | 207,478 | <p>Just an elaboration on what Alex Coventry said, another Alex (Martelli) addressed a similar question on the <code>comp.lang.python</code> newsgroup years back. He examines the semantic difference of what a person intended vs. what he got (by using instance variables).</p>
<p><a href="http://groups.google.com/group/comp.lang.python/msg/5914d297aff35fae?hl=en" rel="nofollow">http://groups.google.com/group/comp.lang.python/msg/5914d297aff35fae?hl=en</a></p>
| 1 | 2008-10-16T04:52:22Z | [
"python",
"attributes"
] |
Python: Difference between class and instance attributes | 207,000 | <p>Is there any meaningful distinction between:</p>
<pre><code>class A(object):
foo = 5 # some default value
</code></pre>
<p>vs.</p>
<pre><code>class B(object):
def __init__(self, foo=5):
self.foo = foo
</code></pre>
<p>If you're creating a lot of instances, is there any difference in performance or space requirements for the two styles? When you read the code, do you consider the meaning of the two styles to be significantly different?</p>
| 84 | 2008-10-16T00:23:41Z | 207,759 | <p>The difference is that the attribute on the class is shared by all instances. The attribute on an instance is unique to that instance.</p>
<p>If coming from C++, attributes on the class are more like static member variables.</p>
| 22 | 2008-10-16T08:16:28Z | [
"python",
"attributes"
] |
Python: Difference between class and instance attributes | 207,000 | <p>Is there any meaningful distinction between:</p>
<pre><code>class A(object):
foo = 5 # some default value
</code></pre>
<p>vs.</p>
<pre><code>class B(object):
def __init__(self, foo=5):
self.foo = foo
</code></pre>
<p>If you're creating a lot of instances, is there any difference in performance or space requirements for the two styles? When you read the code, do you consider the meaning of the two styles to be significantly different?</p>
| 84 | 2008-10-16T00:23:41Z | 26,642,476 | <p>Since people in the comments here and in two other questions marked as dups all appear to be confused about this in the same way, I think it's worth adding an additional answer on top of <a href="http://stackoverflow.com/a/207128/908494">Alex Coventry's</a>.</p>
<p>The fact that Alex is assigning a value of a mutable type, like a list, has nothing to do with whether things are shared or not. We can see this with the <code>id</code> function or the <code>is</code> operator:</p>
<pre><code>>>> class A: foo = object()
>>> a, b = A(), A()
>>> a.foo is b.foo
True
>>> class A:
... def __init__(self): self.foo = object()
>>> a, b = A(), A()
>>> a.foo is b.foo
False
</code></pre>
<p><sub>(If you're wondering why I used <code>object()</code> instead of, say, <code>5</code>, that's to avoid running into two whole other issues which I don't want to get into here; for two different reasons, entirely separately-created <code>5</code>s can end up being the same instance of the number <code>5</code>. But entirely separately-created <code>object()</code>s cannot.)</sub></p>
<hr>
<p>So, why is it that <code>a.foo.append(5)</code> in Alex's example affects <code>b.foo</code>, but <code>a.foo = 5</code> in my example doesn't? Well, try <code>a.foo = 5</code> in Alex's example, and notice that it doesn't affect <code>b.foo</code> there <em>either</em>. </p>
<p><code>a.foo = 5</code> is just making <code>a.foo</code> into a name for <code>5</code>. That doesn't affect <code>b.foo</code>, or any other name for the old value that <code>a.foo</code> used to refer to.* It's a little tricky that we're creating an instance attribute that hides a class attribute,** but once you get that, nothing complicated is happening here.</p>
<hr>
<p>Hopefully it's now obvious why Alex used a list: the fact that you can mutate a list means it's easier to show that two variables name the same list, and also means it's more important in real-life code to know whether you have two lists or two names for the same list.</p>
<hr>
<p><sub>* The confusion for people coming from a language like C++ is that in Python, values aren't stored in variables. Values live off in value-land, on their own, variables are just names for values, and assignment just creates a new name for a value. If it helps, think of each Python variable as a <code>shared_ptr<T></code> instead of a <code>T</code>.</sub></p>
<p><sub>** Some people take advantage of this by using a class attribute as a "default value" for an instance attribute that instances may or may not set. This can be useful in some cases, but it can also be confusing, so be careful with it.</sub></p>
| 11 | 2014-10-29T23:32:51Z | [
"python",
"attributes"
] |
Python: Difference between class and instance attributes | 207,000 | <p>Is there any meaningful distinction between:</p>
<pre><code>class A(object):
foo = 5 # some default value
</code></pre>
<p>vs.</p>
<pre><code>class B(object):
def __init__(self, foo=5):
self.foo = foo
</code></pre>
<p>If you're creating a lot of instances, is there any difference in performance or space requirements for the two styles? When you read the code, do you consider the meaning of the two styles to be significantly different?</p>
| 84 | 2008-10-16T00:23:41Z | 34,126,204 | <p>Here is a very good <a href="http://www.toptal.com/python/python-class-attributes-an-overly-thorough-guide" rel="nofollow">post</a>, and summary it as below.</p>
<pre><code>class Bar(object):
## No need for dot syntax
class_var = 1
def __init__(self, i_var):
self.i_var = i_var
## Need dot syntax as we've left scope of class namespace
Bar.class_var
## 1
foo = MyClass(2)
## Finds i_var in foo's instance namespace
foo.i_var
## 2
## Doesn't find class_var in instance namespaceâ¦
## So look's in class namespace (Bar.__dict__)
foo.class_var
## 1
</code></pre>
<p>And in visual form</p>
<p><a href="http://i.stack.imgur.com/zRHzx.png" rel="nofollow"><img src="http://i.stack.imgur.com/zRHzx.png" alt="enter image description here"></a></p>
<p><strong>Class attribute assignment</strong></p>
<ul>
<li><p>If a class attribute is set by accessing the class, it will override the value for <em>all instances</em></p>
<pre><code>foo = Bar(2)
foo.class_var
## 1
Bar.class_var = 2
foo.class_var
## 2
</code></pre></li>
<li><p>If a class variable is set by accessing an instance, it will override the value <em>only for that instance</em>. This essentially overrides the class variable and turns it into an instance variable available, intuitively, <em>only for that instance</em>.</p>
<pre><code>foo = Bar(2)
foo.class_var
## 1
foo.class_var = 2
foo.class_var
## 2
Bar.class_var
## 1
</code></pre></li>
</ul>
<p><strong>When would you use class attribute?</strong></p>
<ul>
<li><p><em>Storing constants</em>. As class attributes can be accessed as attributes of the class itself, itâs often nice to use them for storing Class-wide, Class-specific constants</p>
<pre><code>class Circle(object):
pi = 3.14159
def __init__(self, radius):
self.radius = radius
def area(self):
return Circle.pi * self.radius * self.radius
Circle.pi
## 3.14159
c = Circle(10)
c.pi
## 3.14159
c.area()
## 314.159
</code></pre></li>
<li><p><em>Defining default values</em>. As a trivial example, we might create a bounded list (i.e., a list that can only hold a certain number of elements or fewer) and choose to have a default cap of 10 items</p>
<pre><code>class MyClass(object):
limit = 10
def __init__(self):
self.data = []
def item(self, i):
return self.data[i]
def add(self, e):
if len(self.data) >= self.limit:
raise Exception("Too many elements")
self.data.append(e)
MyClass.limit
## 10
</code></pre></li>
</ul>
| 4 | 2015-12-07T03:59:08Z | [
"python",
"attributes"
] |
Hooking up GUI interface with asynchronous (s)ftp operation | 207,230 | <p>Trying to implement a progress dialog window for file uploads that look like a cross between <a href="http://www.codinghorror.com/blog/images/ie6-download-ui.png" rel="nofollow">IE download dialog</a> and <a href="http://www.codinghorror.com/blog/images/firefox2-download-ui.png" rel="nofollow">Firefox download dialog</a> with a python GUI library on Windows.</p>
<ol>
<li>What asynchronous (S)FTP libraries are there for python? Ideally I should be able to do file upload resumes and track the progress of each parallel file uploads.</li>
<li>If I'm running each file upload in a separate process each, how would I get the upload status and display it in a progress bar dialog?</li>
</ol>
| 1 | 2008-10-16T02:30:34Z | 207,365 | <p>"ftplib" is the standard ftp library built in to Python. In Python 2.6, it had a callback parameter added to the method used for uploading.</p>
<p>That callback is a function you provide to the library; it is called once for every block that is completed.</p>
<p>Your function can send a message to the GUI (perhaps on a different thread/process, using standard inter-thread or inter-process communications) to tell it to update its progress bar.</p>
<p><a href="http://docs.python.org/library/ftplib.html" rel="nofollow" title="Python 2.6 ftplib manual">Reference</a></p>
| 1 | 2008-10-16T03:42:07Z | [
"python",
"windows",
"user-interface",
"ftp",
"sftp"
] |
Hooking up GUI interface with asynchronous (s)ftp operation | 207,230 | <p>Trying to implement a progress dialog window for file uploads that look like a cross between <a href="http://www.codinghorror.com/blog/images/ie6-download-ui.png" rel="nofollow">IE download dialog</a> and <a href="http://www.codinghorror.com/blog/images/firefox2-download-ui.png" rel="nofollow">Firefox download dialog</a> with a python GUI library on Windows.</p>
<ol>
<li>What asynchronous (S)FTP libraries are there for python? Ideally I should be able to do file upload resumes and track the progress of each parallel file uploads.</li>
<li>If I'm running each file upload in a separate process each, how would I get the upload status and display it in a progress bar dialog?</li>
</ol>
| 1 | 2008-10-16T02:30:34Z | 207,794 | <p>If you want a complete example of how to use threads and events to update your GUI with long running tasks using WxPython have a look at this <a href="http://wiki.wxpython.org/LongRunningTasks" rel="nofollow">page</a>. This tutorial is quite useful and helped me perform a similar program than yours.</p>
| 1 | 2008-10-16T08:38:06Z | [
"python",
"windows",
"user-interface",
"ftp",
"sftp"
] |
Hooking up GUI interface with asynchronous (s)ftp operation | 207,230 | <p>Trying to implement a progress dialog window for file uploads that look like a cross between <a href="http://www.codinghorror.com/blog/images/ie6-download-ui.png" rel="nofollow">IE download dialog</a> and <a href="http://www.codinghorror.com/blog/images/firefox2-download-ui.png" rel="nofollow">Firefox download dialog</a> with a python GUI library on Windows.</p>
<ol>
<li>What asynchronous (S)FTP libraries are there for python? Ideally I should be able to do file upload resumes and track the progress of each parallel file uploads.</li>
<li>If I'm running each file upload in a separate process each, how would I get the upload status and display it in a progress bar dialog?</li>
</ol>
| 1 | 2008-10-16T02:30:34Z | 207,934 | <p>If you data transfer runs in a separate thread from the GUI, you can use wx.CallAfter() whenever you have to update you progress bar from the data transfer thread. </p>
<p>First, using CallAfter() is mandatory as wxPython function cannot be called from child threads.</p>
<p>Second, this will decouple the execution of the data transfer from the GUI in the main thread.</p>
<p>Note that CallAfter() only works for threads, not for separate processes. In that case, using the multiprocessing package should help.</p>
| 1 | 2008-10-16T09:31:54Z | [
"python",
"windows",
"user-interface",
"ftp",
"sftp"
] |
Hooking up GUI interface with asynchronous (s)ftp operation | 207,230 | <p>Trying to implement a progress dialog window for file uploads that look like a cross between <a href="http://www.codinghorror.com/blog/images/ie6-download-ui.png" rel="nofollow">IE download dialog</a> and <a href="http://www.codinghorror.com/blog/images/firefox2-download-ui.png" rel="nofollow">Firefox download dialog</a> with a python GUI library on Windows.</p>
<ol>
<li>What asynchronous (S)FTP libraries are there for python? Ideally I should be able to do file upload resumes and track the progress of each parallel file uploads.</li>
<li>If I'm running each file upload in a separate process each, how would I get the upload status and display it in a progress bar dialog?</li>
</ol>
| 1 | 2008-10-16T02:30:34Z | 216,467 | <p>If you can't use Python 2.6's ftplib, there is a company offering a <em>commercial</em> solution.</p>
<p>Chilkat's <a href="http://www.chilkatsoft.com/refdoc/pythonCkFtp2Ref.html" rel="nofollow" title="CKFTP2 Manual">CKFTP2</a> costs several hundreds of dollars, but promises to work with Python 2.5, and offers a function call get_AsyncBytesSent() which returns the information you need. (I didn't see a callback, but it may offer that too.)</p>
<p>I haven't used this product.</p>
<p>Also consider that if FTP proves to be too hard/expensive, you could always switch to HTTP uploads instead. Chilkat have a free HTTP/HTTPS upload library.</p>
| 0 | 2008-10-19T14:14:17Z | [
"python",
"windows",
"user-interface",
"ftp",
"sftp"
] |
List of IP addresses/hostnames from local network in Python | 207,234 | <p>How can I get a list of the IP addresses or host names from a local network easily in Python?</p>
<p>It would be best if it was multi-platform, but it needs to work on Mac OS X first, then others follow.</p>
<p><strong>Edit:</strong> By local I mean all <strong>active</strong> addresses within a local network, such as <code>192.168.xxx.xxx</code>.</p>
<p>So, if the IP address of my computer (within the local network) is <code>192.168.1.1</code>, and I have three other connected computers, I would want it to return the IP addresses <code>192.168.1.2</code>, <code>192.168.1.3</code>, <code>192.168.1.4</code>, and possibly their hostnames.</p>
| 23 | 2008-10-16T02:32:33Z | 207,242 | <p>One of the answers in <a href="http://stackoverflow.com/questions/166506/finding-local-ip-addresses-in-python">this question</a> might help you. There seems to be a platform agnostic version for python, but I haven't tried it yet.</p>
| 0 | 2008-10-16T02:36:34Z | [
"python",
"networking"
] |
List of IP addresses/hostnames from local network in Python | 207,234 | <p>How can I get a list of the IP addresses or host names from a local network easily in Python?</p>
<p>It would be best if it was multi-platform, but it needs to work on Mac OS X first, then others follow.</p>
<p><strong>Edit:</strong> By local I mean all <strong>active</strong> addresses within a local network, such as <code>192.168.xxx.xxx</code>.</p>
<p>So, if the IP address of my computer (within the local network) is <code>192.168.1.1</code>, and I have three other connected computers, I would want it to return the IP addresses <code>192.168.1.2</code>, <code>192.168.1.3</code>, <code>192.168.1.4</code>, and possibly their hostnames.</p>
| 23 | 2008-10-16T02:32:33Z | 207,246 | <p>If by "local" you mean on the same network segment, then you have to perform the following steps:</p>
<ol>
<li>Determine your own IP address</li>
<li>Determine your own netmask</li>
<li>Determine the network range</li>
<li>Scan all the addresses (except the lowest, which is your network address and the highest, which is your broadcast address).</li>
<li>Use your DNS's reverse lookup to determine the hostname for IP addresses which respond to your scan.</li>
</ol>
<p>Or you can just let Python execute nmap externally and pipe the results back into your program.</p>
| 12 | 2008-10-16T02:38:02Z | [
"python",
"networking"
] |
List of IP addresses/hostnames from local network in Python | 207,234 | <p>How can I get a list of the IP addresses or host names from a local network easily in Python?</p>
<p>It would be best if it was multi-platform, but it needs to work on Mac OS X first, then others follow.</p>
<p><strong>Edit:</strong> By local I mean all <strong>active</strong> addresses within a local network, such as <code>192.168.xxx.xxx</code>.</p>
<p>So, if the IP address of my computer (within the local network) is <code>192.168.1.1</code>, and I have three other connected computers, I would want it to return the IP addresses <code>192.168.1.2</code>, <code>192.168.1.3</code>, <code>192.168.1.4</code>, and possibly their hostnames.</p>
| 23 | 2008-10-16T02:32:33Z | 207,775 | <p>If you know the names of your computers you can use:</p>
<pre><code>import socket
IP1 = socket.gethostbyname(socket.gethostname()) # local IP adress of your computer
IP2 = socket.gethostbyname('name_of_your_computer') # IP adress of remote computer
</code></pre>
<p>Otherwise you will have to scan for all the IP addresses that follow the same mask as your local computer (IP1), as stated in another answer.</p>
| 5 | 2008-10-16T08:27:41Z | [
"python",
"networking"
] |
List of IP addresses/hostnames from local network in Python | 207,234 | <p>How can I get a list of the IP addresses or host names from a local network easily in Python?</p>
<p>It would be best if it was multi-platform, but it needs to work on Mac OS X first, then others follow.</p>
<p><strong>Edit:</strong> By local I mean all <strong>active</strong> addresses within a local network, such as <code>192.168.xxx.xxx</code>.</p>
<p>So, if the IP address of my computer (within the local network) is <code>192.168.1.1</code>, and I have three other connected computers, I would want it to return the IP addresses <code>192.168.1.2</code>, <code>192.168.1.3</code>, <code>192.168.1.4</code>, and possibly their hostnames.</p>
| 23 | 2008-10-16T02:32:33Z | 602,965 | <p><strong>Update</strong>: The script is now located on <a href="http://github.com/bwaldvogel/neighbourhood">github</a>.</p>
<p>I wrote a <a href="https://github.com/bwaldvogel/neighbourhood/blob/master/neighbourhood.py">small python script</a>, that leverages <a href="http://www.secdev.org/projects/scapy/">scapy</a>'s <code>arping()</code>.</p>
| 14 | 2009-03-02T16:27:29Z | [
"python",
"networking"
] |
List of IP addresses/hostnames from local network in Python | 207,234 | <p>How can I get a list of the IP addresses or host names from a local network easily in Python?</p>
<p>It would be best if it was multi-platform, but it needs to work on Mac OS X first, then others follow.</p>
<p><strong>Edit:</strong> By local I mean all <strong>active</strong> addresses within a local network, such as <code>192.168.xxx.xxx</code>.</p>
<p>So, if the IP address of my computer (within the local network) is <code>192.168.1.1</code>, and I have three other connected computers, I would want it to return the IP addresses <code>192.168.1.2</code>, <code>192.168.1.3</code>, <code>192.168.1.4</code>, and possibly their hostnames.</p>
| 23 | 2008-10-16T02:32:33Z | 12,027,431 | <p>Try:</p>
<pre><code>import socket
print [ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith("127.")][:1]
</code></pre>
| 1 | 2012-08-19T14:52:13Z | [
"python",
"networking"
] |
List of IP addresses/hostnames from local network in Python | 207,234 | <p>How can I get a list of the IP addresses or host names from a local network easily in Python?</p>
<p>It would be best if it was multi-platform, but it needs to work on Mac OS X first, then others follow.</p>
<p><strong>Edit:</strong> By local I mean all <strong>active</strong> addresses within a local network, such as <code>192.168.xxx.xxx</code>.</p>
<p>So, if the IP address of my computer (within the local network) is <code>192.168.1.1</code>, and I have three other connected computers, I would want it to return the IP addresses <code>192.168.1.2</code>, <code>192.168.1.3</code>, <code>192.168.1.4</code>, and possibly their hostnames.</p>
| 23 | 2008-10-16T02:32:33Z | 36,821,146 | <p>Here is a small tool <strong>scanip</strong> that will help you to get all ip addresses and their corresponding mac addresses in the network (Works on Linux).
This is the link for <strong>scanip</strong> (Ip and Mac scanner) written in python.
<a href="https://pypi.python.org/pypi/scanip/1.0" rel="nofollow">https://pypi.python.org/pypi/scanip/1.0</a></p>
<p>You can also download it using <strong>pip install scanip</strong> on linux and to use it , create a test file in python and use it like this-</p>
<pre><code>import scanip.scanip
scanip.scanip.start_scan()
</code></pre>
<p>and run this program . All the ip and their corresponding mac addresses in the LAN will be shown in the terminal.</p>
| -1 | 2016-04-24T09:03:01Z | [
"python",
"networking"
] |
extracting a parenthesized Python expression from a string | 207,290 | <p>I've been wondering about how hard it would be to write some Python code to search a string for the index of a substring of the form <code>${</code><em>expr</em><code>}</code>, for example, where <em>expr</em> is meant to be a Python expression or something resembling one. Given such a thing, one could easily imagine going on to check the expression's syntax with <code>compile()</code>, evaluate it against a particular scope with <code>eval()</code>, and perhaps even substitute the result into the original string. People must do very similar things all the time.</p>
<p>I could imagine solving such a problem using a third-party parser generator [oof], or by hand-coding some sort of state machine [eek], or perhaps by convincing Python's own parser to do the heavy lifting somehow [hmm]. Maybe there's a third-party templating library somewhere that can be made to do exactly this. Maybe restricting the syntax of <em>expr</em> is likely to be a worthwhile compromise in terms of simplicity or execution time or cutting down on external dependencies -- for example, maybe all I really need is something that matches any <em>expr</em> that has balanced curly braces.</p>
<p>What's your sense?</p>
<h2>Update:</h2>
<p>Thanks very much for your responses so far! Looking back at what I wrote yesterday, I'm not sure I was sufficiently clear about what I'm asking. Template substitution is indeed an interesting problem, and probably much more useful to many more people than the expression extraction subproblem I'm wondering about, but I brought it up only as a simple example of how the answer to my question might be useful in real life. Some other potential applications might include passing the extracted expressions to a syntax highlighter; passing the result to a real Python parser and looking at or monkeying with the parse tree; or using the sequence of extracted expressions to build up a larger Python program, perhaps in conjunction with some information taken from the surrounding text.</p>
<p>The <code>${</code><em>expr</em><code>}</code> syntax I mentioned is also intended as an example, and in fact I wonder if I shouldn't have used <code>$(</code><em>expr</em><code>)</code> as my example instead, because it makes the potential drawbacks of the obvious approach, along the lines of <code>re.finditer(r'$\{([^}]+)\}', s)</code>, a bit easier to see. Python expressions can (and often do) contain the <code>)</code> (or <code>}</code>) character. It seems possible that handling any of those cases might be much more trouble than it's worth, but I'm not convinced of that yet. Please feel free to try to make this case!</p>
<p>Prior to posting this question, I spent quite a bit of time looking at Python template engines hoping that one might expose the sort of low-level functionality I'm asking about -- namely, something that can find expressions in a variety of contexts and tell me where they are rather than being limited to finding expressions embedded using a single hard-coded syntax, always evaluating them, and always substituting the results back into the original string. I haven't figured out how to use any of them to solve my problem yet, but I do very much appreciate the suggestions regarding more to look at (can't believe I missed that wonderful list on the wiki!). The API documentation for these things tends to be pretty high-level, and I'm not too familiar with the internals of any of them, so I'm sure I could use help looking at those and figuring out how to get them to do this sort of thing.</p>
<p>Thanks for your patience!</p>
| 1 | 2008-10-16T03:02:27Z | 207,310 | <p>I think your best bet is to match for all curly braced entries, and then check against Python itself whether or not it's valid Python, for which <a href="http://www.python.org/doc/2.5.2/lib/compiler.html" rel="nofollow">compiler</a> would be helpful.</p>
| 1 | 2008-10-16T03:09:11Z | [
"python",
"parsing"
] |
extracting a parenthesized Python expression from a string | 207,290 | <p>I've been wondering about how hard it would be to write some Python code to search a string for the index of a substring of the form <code>${</code><em>expr</em><code>}</code>, for example, where <em>expr</em> is meant to be a Python expression or something resembling one. Given such a thing, one could easily imagine going on to check the expression's syntax with <code>compile()</code>, evaluate it against a particular scope with <code>eval()</code>, and perhaps even substitute the result into the original string. People must do very similar things all the time.</p>
<p>I could imagine solving such a problem using a third-party parser generator [oof], or by hand-coding some sort of state machine [eek], or perhaps by convincing Python's own parser to do the heavy lifting somehow [hmm]. Maybe there's a third-party templating library somewhere that can be made to do exactly this. Maybe restricting the syntax of <em>expr</em> is likely to be a worthwhile compromise in terms of simplicity or execution time or cutting down on external dependencies -- for example, maybe all I really need is something that matches any <em>expr</em> that has balanced curly braces.</p>
<p>What's your sense?</p>
<h2>Update:</h2>
<p>Thanks very much for your responses so far! Looking back at what I wrote yesterday, I'm not sure I was sufficiently clear about what I'm asking. Template substitution is indeed an interesting problem, and probably much more useful to many more people than the expression extraction subproblem I'm wondering about, but I brought it up only as a simple example of how the answer to my question might be useful in real life. Some other potential applications might include passing the extracted expressions to a syntax highlighter; passing the result to a real Python parser and looking at or monkeying with the parse tree; or using the sequence of extracted expressions to build up a larger Python program, perhaps in conjunction with some information taken from the surrounding text.</p>
<p>The <code>${</code><em>expr</em><code>}</code> syntax I mentioned is also intended as an example, and in fact I wonder if I shouldn't have used <code>$(</code><em>expr</em><code>)</code> as my example instead, because it makes the potential drawbacks of the obvious approach, along the lines of <code>re.finditer(r'$\{([^}]+)\}', s)</code>, a bit easier to see. Python expressions can (and often do) contain the <code>)</code> (or <code>}</code>) character. It seems possible that handling any of those cases might be much more trouble than it's worth, but I'm not convinced of that yet. Please feel free to try to make this case!</p>
<p>Prior to posting this question, I spent quite a bit of time looking at Python template engines hoping that one might expose the sort of low-level functionality I'm asking about -- namely, something that can find expressions in a variety of contexts and tell me where they are rather than being limited to finding expressions embedded using a single hard-coded syntax, always evaluating them, and always substituting the results back into the original string. I haven't figured out how to use any of them to solve my problem yet, but I do very much appreciate the suggestions regarding more to look at (can't believe I missed that wonderful list on the wiki!). The API documentation for these things tends to be pretty high-level, and I'm not too familiar with the internals of any of them, so I'm sure I could use help looking at those and figuring out how to get them to do this sort of thing.</p>
<p>Thanks for your patience!</p>
| 1 | 2008-10-16T03:02:27Z | 207,502 | <p>I think what you're asking about is being able to insert Python code into text files to be evaluated. There are several modules that already exist to provide this kind of functionality. You can check the Python.org <a href="http://wiki.python.org/moin/Templating" rel="nofollow"><strong>Templating wiki page</strong></a> for a comprehensive list.</p>
<p>Some google searching also turned up a few other modules you might be interested in:</p>
<ul>
<li><a href="http://py-templates.sourceforge.net/texttemplate/index.html" rel="nofollow">texttemplate</a> (part of py-templates project)</li>
<li><a href="http://www.embl-heidelberg.de/~chenna/pythonpages/template.html" rel="nofollow">template module</a></li>
</ul>
<p>If you're really looking just into writing this yourself for whatever reason, you can also dig into this Python cookbook solution <a href="http://code.activestate.com/recipes/52305/" rel="nofollow">Yet Another Python Templating Utility (YAPTU) </a>:</p>
<blockquote>
<p><em>"Templating" (copying an input file to output, on the fly inserting Python
expressions and statements) is a frequent need, and YAPTU is a small but
complete Python module for that; expressions and statements are identified
by arbitrary user-chosen regular-expressions.</em></p>
</blockquote>
<p><strong>EDIT</strong>: Just for the heck of it, I whipped up a severely simplistic code sample for this. I'm sure it has bugs but it illustrates a simplified version of the concept at least: </p>
<pre><code>#!/usr/bin/env python
import sys
import re
FILE = sys.argv[1]
handle = open(FILE)
fcontent = handle.read()
handle.close()
for myexpr in re.finditer(r'\${([^}]+)}', fcontent, re.M|re.S):
text = myexpr.group(1)
try:
exec text
except SyntaxError:
print "ERROR: unable to compile expression '%s'" % (text)
</code></pre>
<p>Tested against the following text: </p>
<pre><code>This is some random text, with embedded python like
${print "foo"} and some bogus python like
${any:thing}.
And a multiline statement, just for kicks:
${
def multiline_stmt(foo):
print foo
multiline_stmt("ahem")
}
More text here.
</code></pre>
<p>Output: </p>
<pre><code>[user@host]$ ./exec_embedded_python.py test.txt
foo
ERROR: unable to compile expression 'any:thing'
ahem
</code></pre>
| 2 | 2008-10-16T05:10:29Z | [
"python",
"parsing"
] |
extracting a parenthesized Python expression from a string | 207,290 | <p>I've been wondering about how hard it would be to write some Python code to search a string for the index of a substring of the form <code>${</code><em>expr</em><code>}</code>, for example, where <em>expr</em> is meant to be a Python expression or something resembling one. Given such a thing, one could easily imagine going on to check the expression's syntax with <code>compile()</code>, evaluate it against a particular scope with <code>eval()</code>, and perhaps even substitute the result into the original string. People must do very similar things all the time.</p>
<p>I could imagine solving such a problem using a third-party parser generator [oof], or by hand-coding some sort of state machine [eek], or perhaps by convincing Python's own parser to do the heavy lifting somehow [hmm]. Maybe there's a third-party templating library somewhere that can be made to do exactly this. Maybe restricting the syntax of <em>expr</em> is likely to be a worthwhile compromise in terms of simplicity or execution time or cutting down on external dependencies -- for example, maybe all I really need is something that matches any <em>expr</em> that has balanced curly braces.</p>
<p>What's your sense?</p>
<h2>Update:</h2>
<p>Thanks very much for your responses so far! Looking back at what I wrote yesterday, I'm not sure I was sufficiently clear about what I'm asking. Template substitution is indeed an interesting problem, and probably much more useful to many more people than the expression extraction subproblem I'm wondering about, but I brought it up only as a simple example of how the answer to my question might be useful in real life. Some other potential applications might include passing the extracted expressions to a syntax highlighter; passing the result to a real Python parser and looking at or monkeying with the parse tree; or using the sequence of extracted expressions to build up a larger Python program, perhaps in conjunction with some information taken from the surrounding text.</p>
<p>The <code>${</code><em>expr</em><code>}</code> syntax I mentioned is also intended as an example, and in fact I wonder if I shouldn't have used <code>$(</code><em>expr</em><code>)</code> as my example instead, because it makes the potential drawbacks of the obvious approach, along the lines of <code>re.finditer(r'$\{([^}]+)\}', s)</code>, a bit easier to see. Python expressions can (and often do) contain the <code>)</code> (or <code>}</code>) character. It seems possible that handling any of those cases might be much more trouble than it's worth, but I'm not convinced of that yet. Please feel free to try to make this case!</p>
<p>Prior to posting this question, I spent quite a bit of time looking at Python template engines hoping that one might expose the sort of low-level functionality I'm asking about -- namely, something that can find expressions in a variety of contexts and tell me where they are rather than being limited to finding expressions embedded using a single hard-coded syntax, always evaluating them, and always substituting the results back into the original string. I haven't figured out how to use any of them to solve my problem yet, but I do very much appreciate the suggestions regarding more to look at (can't believe I missed that wonderful list on the wiki!). The API documentation for these things tends to be pretty high-level, and I'm not too familiar with the internals of any of them, so I'm sure I could use help looking at those and figuring out how to get them to do this sort of thing.</p>
<p>Thanks for your patience!</p>
| 1 | 2008-10-16T03:02:27Z | 209,420 | <p>If you want to handle arbitrary expressions like <code>{'{spam': 42}["spam}"]</code>, you can't get away without full-blown parser.</p>
| 1 | 2008-10-16T16:56:42Z | [
"python",
"parsing"
] |
extracting a parenthesized Python expression from a string | 207,290 | <p>I've been wondering about how hard it would be to write some Python code to search a string for the index of a substring of the form <code>${</code><em>expr</em><code>}</code>, for example, where <em>expr</em> is meant to be a Python expression or something resembling one. Given such a thing, one could easily imagine going on to check the expression's syntax with <code>compile()</code>, evaluate it against a particular scope with <code>eval()</code>, and perhaps even substitute the result into the original string. People must do very similar things all the time.</p>
<p>I could imagine solving such a problem using a third-party parser generator [oof], or by hand-coding some sort of state machine [eek], or perhaps by convincing Python's own parser to do the heavy lifting somehow [hmm]. Maybe there's a third-party templating library somewhere that can be made to do exactly this. Maybe restricting the syntax of <em>expr</em> is likely to be a worthwhile compromise in terms of simplicity or execution time or cutting down on external dependencies -- for example, maybe all I really need is something that matches any <em>expr</em> that has balanced curly braces.</p>
<p>What's your sense?</p>
<h2>Update:</h2>
<p>Thanks very much for your responses so far! Looking back at what I wrote yesterday, I'm not sure I was sufficiently clear about what I'm asking. Template substitution is indeed an interesting problem, and probably much more useful to many more people than the expression extraction subproblem I'm wondering about, but I brought it up only as a simple example of how the answer to my question might be useful in real life. Some other potential applications might include passing the extracted expressions to a syntax highlighter; passing the result to a real Python parser and looking at or monkeying with the parse tree; or using the sequence of extracted expressions to build up a larger Python program, perhaps in conjunction with some information taken from the surrounding text.</p>
<p>The <code>${</code><em>expr</em><code>}</code> syntax I mentioned is also intended as an example, and in fact I wonder if I shouldn't have used <code>$(</code><em>expr</em><code>)</code> as my example instead, because it makes the potential drawbacks of the obvious approach, along the lines of <code>re.finditer(r'$\{([^}]+)\}', s)</code>, a bit easier to see. Python expressions can (and often do) contain the <code>)</code> (or <code>}</code>) character. It seems possible that handling any of those cases might be much more trouble than it's worth, but I'm not convinced of that yet. Please feel free to try to make this case!</p>
<p>Prior to posting this question, I spent quite a bit of time looking at Python template engines hoping that one might expose the sort of low-level functionality I'm asking about -- namely, something that can find expressions in a variety of contexts and tell me where they are rather than being limited to finding expressions embedded using a single hard-coded syntax, always evaluating them, and always substituting the results back into the original string. I haven't figured out how to use any of them to solve my problem yet, but I do very much appreciate the suggestions regarding more to look at (can't believe I missed that wonderful list on the wiki!). The API documentation for these things tends to be pretty high-level, and I'm not too familiar with the internals of any of them, so I'm sure I could use help looking at those and figuring out how to get them to do this sort of thing.</p>
<p>Thanks for your patience!</p>
| 1 | 2008-10-16T03:02:27Z | 210,716 | <p>After posting this, reading the replies so far (thanks everyone!), and thinking about the problem for a while, here is the best approach I've been able to come up with:</p>
<ol>
<li>Find the first <code>${</code>.</li>
<li>Find the next <code>}</code> after that.</li>
<li>Feed whatever's in between to <code>compile()</code>. If it works, stick a fork in it and we're done.</li>
<li>Otherwise, keep extending the string by looking for subsequent occurences of <code>}</code>. As soon as something compiles, return it.</li>
<li>If we run out of <code>}</code> without being able to compile anything, use the results of the last compilation attempt to give information about where the problem lies.</li>
</ol>
<p>Advantages of this approach:</p>
<ul>
<li>The code is quite short and easy to understand.</li>
<li>It's pretty efficient -- optimal, even, in the case where the expression contains no <code>}</code>. Worst-case seems like it wouldn't be too bad either.</li>
<li>It works on many expressions that contain <code>${</code> and/or <code>}</code>.</li>
<li>No external dependencies. No need to import <em>anything</em>, in fact. (This surprised me.)</li>
</ul>
<p>Disadvantages:</p>
<ul>
<li>Sometimes it grabs too much or too little. See below for an example of the latter. I could imagine a scary example where you have two expressions and the first one is subtly wrong and the algorithm ends up mistakenly grabbing the whole thing and everything in between and returning it as valid, though I haven't been able to demonstrate this. Perhaps things are not so bad as I fear. I don't think misunderstandings can be avoided in general -- the problem definition is kind of slippery -- but it seems like it ought to be possible to do better, especially if one were willing to trade simplicity or execution time.</li>
<li>I haven't done any benchmarks, but I could imagine there being faster alternatives, especially in cases that involve lots of <code>}</code> in the expression. That could be a big deal if one wanted to apply this technique to sizable blocks of Python code rather than just very short expressions.</li>
</ul>
<p>Here is my implementation.</p>
<pre><code>def findExpr(s, i0=0, begin='${', end='}', compArgs=('<string>', 'eval')):
assert '\n' not in s, 'line numbers not implemented'
i0 = s.index(begin, i0) + len(begin)
i1 = s.index(end, i0)
code = errMsg = None
while code is None and errMsg is None:
expr = s[i0:i1]
try: code = compile(expr, *compArgs)
except SyntaxError, e:
i1 = s.find(end, i1 + 1)
if i1 < 0: errMsg, i1 = e.msg, i0 + e.offset
return i0, i1, code, errMsg
</code></pre>
<p>And here's the docstring with some illustrations in doctest format, which I didn't insert into the middle of the function above only because it's long and I feel like the code is easier to read without it.</p>
<pre><code>'''
Search s for a (possibly invalid) Python expression bracketed by begin
and end, which default to '${' and '}'. Return a 4-tuple.
>>> s = 'foo ${a*b + c*d} bar'
>>> i0, i1, code, errMsg = findExpr(s)
>>> i0, i1, s[i0:i1], errMsg
(6, 15, 'a*b + c*d', None)
>>> ' '.join('%02x' % ord(byte) for byte in code.co_code)
'65 00 00 65 01 00 14 65 02 00 65 03 00 14 17 53'
>>> code.co_names
('a', 'b', 'c', 'd')
>>> eval(code, {'a': 1, 'b': 2, 'c': 3, 'd': 4})
14
>>> eval(code, {'a': 'a', 'b': 2, 'c': 'c', 'd': 4})
'aacccc'
>>> eval(code, {'a': None})
Traceback (most recent call last):
...
NameError: name 'b' is not defined
Expressions containing start and/or end are allowed.
>>> s = '{foo ${{"}": "${"}["}"]} bar}'
>>> i0, i1, code, errMsg = findExpr(s)
>>> i0, i1, s[i0:i1], errMsg
(7, 23, '{"}": "${"}["}"]', None)
If the first match is syntactically invalid Python, i0 points to the
start of the match, i1 points to the parse error, code is None and
errMsg contains a message from the compiler.
>>> s = '{foo ${qwerty asdf zxcvbnm!!!} ${7} bar}'
>>> i0, i1, code, errMsg = findExpr(s)
>>> i0, i1, s[i0:i1], errMsg
(7, 18, 'qwerty asdf', 'invalid syntax')
>>> print code
None
If a second argument is given, start searching there.
>>> i0, i1, code, errMsg = findExpr(s, i1)
>>> i0, i1, s[i0:i1], errMsg
(33, 34, '7', None)
Raise ValueError if there are no further matches.
>>> i0, i1, code, errMsg = findExpr(s, i1)
Traceback (most recent call last):
...
ValueError: substring not found
In ambiguous cases, match the shortest valid expression. This is not
always ideal behavior.
>>> s = '{foo ${x or {} # return {} instead of None} bar}'
>>> i0, i1, code, errMsg = findExpr(s)
>>> i0, i1, s[i0:i1], errMsg
(7, 25, 'x or {} # return {', None)
This implementation must not be used with multi-line strings. It does
not adjust line number information in the returned code object, and it
does not take the line number into account when computing the offset
of a parse error.
'''
</code></pre>
| 0 | 2008-10-17T00:09:51Z | [
"python",
"parsing"
] |
Are there any IDE's that support Python 3 syntax? | 207,763 | <p>I recently saw an announcement and <a href="http://www.linux.com/feature/150399" rel="nofollow">article</a> outlining the release of the first <a href="http://www.python.org/download/releases/3.0/" rel="nofollow">Python 3.0</a> release candidate. I was wondering whether there were any commercial, free, open source etc. IDE's that support its syntax.</p>
| 6 | 2008-10-16T08:21:22Z | 207,772 | <p>Can get <strong>PyDev.</strong> from <a href="http://pydev.sourceforge.net" rel="nofollow">http://pydev.sourceforge.net</a>. Its a plugin for Eclipse and is more than handy. Not to mention benefits of the old and trusted Eclipse.</p>
| 1 | 2008-10-16T08:27:02Z | [
"python",
"syntax",
"ide",
"python-3.x"
] |
Are there any IDE's that support Python 3 syntax? | 207,763 | <p>I recently saw an announcement and <a href="http://www.linux.com/feature/150399" rel="nofollow">article</a> outlining the release of the first <a href="http://www.python.org/download/releases/3.0/" rel="nofollow">Python 3.0</a> release candidate. I was wondering whether there were any commercial, free, open source etc. IDE's that support its syntax.</p>
| 6 | 2008-10-16T08:21:22Z | 207,788 | <p>Komodo 5 beta 1 was released in October 2008 and has initial support for Python 3 but I don't think I'd be using it for production code yet.</p>
<p>Given that Python 3 is still a very early release candidate, you may have some trouble finding mature support in IDEs.</p>
| 5 | 2008-10-16T08:34:56Z | [
"python",
"syntax",
"ide",
"python-3.x"
] |
Are there any IDE's that support Python 3 syntax? | 207,763 | <p>I recently saw an announcement and <a href="http://www.linux.com/feature/150399" rel="nofollow">article</a> outlining the release of the first <a href="http://www.python.org/download/releases/3.0/" rel="nofollow">Python 3.0</a> release candidate. I was wondering whether there were any commercial, free, open source etc. IDE's that support its syntax.</p>
| 6 | 2008-10-16T08:21:22Z | 209,303 | <p>Python 3 is just <strong>not that different</strong> from Python 2.x. In terms of syntax <em>per se</em>, things that will actually need to be handled differently by the parser, the only major change is in the replacement of the <code>print</code> statement with the <code>print</code> function.</p>
<p>Most of the features of Python can be easily probed via introspection (online help, method completion, function signatures, etc.), so there's no reason why any Python IDE will require major changes to work with Python 3.0. I expect IDLE and SPE and the other open-source IDEs will be support it before the final release.</p>
| 5 | 2008-10-16T16:23:17Z | [
"python",
"syntax",
"ide",
"python-3.x"
] |
Are there any IDE's that support Python 3 syntax? | 207,763 | <p>I recently saw an announcement and <a href="http://www.linux.com/feature/150399" rel="nofollow">article</a> outlining the release of the first <a href="http://www.python.org/download/releases/3.0/" rel="nofollow">Python 3.0</a> release candidate. I was wondering whether there were any commercial, free, open source etc. IDE's that support its syntax.</p>
| 6 | 2008-10-16T08:21:22Z | 209,844 | <p>Emacs + python.el continues to be better than anything else I've tried.</p>
| 1 | 2008-10-16T19:06:20Z | [
"python",
"syntax",
"ide",
"python-3.x"
] |
Are there any IDE's that support Python 3 syntax? | 207,763 | <p>I recently saw an announcement and <a href="http://www.linux.com/feature/150399" rel="nofollow">article</a> outlining the release of the first <a href="http://www.python.org/download/releases/3.0/" rel="nofollow">Python 3.0</a> release candidate. I was wondering whether there were any commercial, free, open source etc. IDE's that support its syntax.</p>
| 6 | 2008-10-16T08:21:22Z | 800,310 | <p>I can say that at the time of posting this (Apr. 28 2009, version 0.8.4h) that <a href="http://pythonide.blogspot.com/" rel="nofollow" title="SPE">SPE</a> does <em>not</em> correctly handle some python3 syntax - specifically exception handling. For example, the follow code is flagged as an error (and irritatingly, is jumped to whenever the file is saved):</p>
<pre><code>except urllib.error.URLError as e:
if hasattr(e, 'reason'):
#...
</code></pre>
| 0 | 2009-04-28T23:47:33Z | [
"python",
"syntax",
"ide",
"python-3.x"
] |
Are there any IDE's that support Python 3 syntax? | 207,763 | <p>I recently saw an announcement and <a href="http://www.linux.com/feature/150399" rel="nofollow">article</a> outlining the release of the first <a href="http://www.python.org/download/releases/3.0/" rel="nofollow">Python 3.0</a> release candidate. I was wondering whether there were any commercial, free, open source etc. IDE's that support its syntax.</p>
| 6 | 2008-10-16T08:21:22Z | 1,115,150 | <p><a href="http://code.google.com/p/pyscripter/" rel="nofollow">Pyscripter</a> is the PERFECT Python IDE on windows; it's compatible even with the newly released Python 3.1.</p>
| 1 | 2009-07-12T02:03:37Z | [
"python",
"syntax",
"ide",
"python-3.x"
] |
Are there any IDE's that support Python 3 syntax? | 207,763 | <p>I recently saw an announcement and <a href="http://www.linux.com/feature/150399" rel="nofollow">article</a> outlining the release of the first <a href="http://www.python.org/download/releases/3.0/" rel="nofollow">Python 3.0</a> release candidate. I was wondering whether there were any commercial, free, open source etc. IDE's that support its syntax.</p>
| 6 | 2008-10-16T08:21:22Z | 1,115,734 | <p><a href="http://pydev.org" rel="nofollow">PyDev</a> for Eclipse does support 3.0.
You can configure multiple interpreters in the plug-in settings.</p>
<p>In the project properties you can set:</p>
<ul>
<li>Project type (Python, Jython, IronPython)</li>
<li>Grammar version (2.1, 2.2, 2.3, 2.4, 2.5, 2.6, 3.0).</li>
</ul>
<p><em>(PyDev version at time of writing: 1.4.7.)</em></p>
| 3 | 2009-07-12T10:23:46Z | [
"python",
"syntax",
"ide",
"python-3.x"
] |
Are there any IDE's that support Python 3 syntax? | 207,763 | <p>I recently saw an announcement and <a href="http://www.linux.com/feature/150399" rel="nofollow">article</a> outlining the release of the first <a href="http://www.python.org/download/releases/3.0/" rel="nofollow">Python 3.0</a> release candidate. I was wondering whether there were any commercial, free, open source etc. IDE's that support its syntax.</p>
| 6 | 2008-10-16T08:21:22Z | 3,525,886 | <p>Geany works with python 3 if you install it and then:</p>
<blockquote>
<p>sudo gedit /usr/share/geany/filetypes.python</p>
</blockquote>
<p>change the last 2 lines with:</p>
<p>compiler=python3 -c "import py_compile; py_compile.compile('%f')"</p>
<p>run_cmd=python3 "%f"</p>
| 1 | 2010-08-19T20:21:26Z | [
"python",
"syntax",
"ide",
"python-3.x"
] |
Python module that implements ftps | 207,939 | <p>I was wondering if anybody could point me towards a free ftps module for python.</p>
<p>I am a complete newbie to python, but this is something I need for a work project. I need an ftps client to connect to a 3rd party ftps server.</p>
<p>thanks,</p>
<p>David.</p>
| 9 | 2008-10-16T09:33:39Z | 207,943 | <p>I haven't tried it myself (yes, I just used Google and followed some links), but <a href="http://www.lag.net/paramiko/" rel="nofollow">http://www.lag.net/paramiko/</a> seems to be the recommended solution. From a cursory glance, it's an SSH implementation in pure Python, which allows tunneling for things like FTP.</p>
<p>Update: a commenter pointed out that I mixed up sftp and ftps, sorry. I still suggest at least investigating Paramiko briefly to see if it matches the requirements.</p>
| 1 | 2008-10-16T09:36:43Z | [
"python",
"ftps"
] |
Python module that implements ftps | 207,939 | <p>I was wondering if anybody could point me towards a free ftps module for python.</p>
<p>I am a complete newbie to python, but this is something I need for a work project. I need an ftps client to connect to a 3rd party ftps server.</p>
<p>thanks,</p>
<p>David.</p>
| 9 | 2008-10-16T09:33:39Z | 208,030 | <p><a href="http://twistedmatrix.com/trac/wiki/TwistedProject" rel="nofollow">Twisted</a> seems to have some implementation of FTPS (FTP over SSL) under the <em>conch</em> sub-project. I am no twisted expert, but <a href="http://stackoverflow.com/users/13564/glyph">Glyph</a>, the <em>twisted</em> man himself, is listed in this site. Maybe by following his <a href="http://stackoverflow.com/questions/80617/asychronous-programming-in-python-twisted#81456">answer</a> to another question, you can find more details (good luck).</p>
| 3 | 2008-10-16T10:19:31Z | [
"python",
"ftps"
] |
Python module that implements ftps | 207,939 | <p>I was wondering if anybody could point me towards a free ftps module for python.</p>
<p>I am a complete newbie to python, but this is something I need for a work project. I need an ftps client to connect to a 3rd party ftps server.</p>
<p>thanks,</p>
<p>David.</p>
| 9 | 2008-10-16T09:33:39Z | 208,256 | <p>I believe you could use Twisted to implement FTPS by simply using its FTP implementation, but changing the <a href="http://twistedmatrix.com/trac/browser/trunk/twisted/protocols/ftp.py?rev=24609#L2186"><code>FTPClient.connectFactory</code></a> attribute to be a function that does something with <a href="http://twistedmatrix.com/documents/8.1.0/api/twisted.internet.interfaces.IReactorSSL.connectSSL.html"><code>connectSSL</code></a> rather than <code>connectTCP</code>.</p>
<p>Are you sure you want FTPS though? <a href="http://geekswithblogs.net/bvamsi/archive/2006/03/23/73147.aspx">SFTP is a different, better, and much more popular protocol</a> these days: Twisted contains <a href="http://twistedmatrix.com/trac/browser/trunk/twisted/conch/ssh/filetransfer.py?rev=24609">an SFTP implementation</a> as well.</p>
| 9 | 2008-10-16T12:00:12Z | [
"python",
"ftps"
] |
Python module that implements ftps | 207,939 | <p>I was wondering if anybody could point me towards a free ftps module for python.</p>
<p>I am a complete newbie to python, but this is something I need for a work project. I need an ftps client to connect to a 3rd party ftps server.</p>
<p>thanks,</p>
<p>David.</p>
| 9 | 2008-10-16T09:33:39Z | 210,942 | <p>I couldn't find a free sftp client for windows so I ended up wrapping Putty's PSFTP using python's subprocess module.
I probably would have used the twisted implementation mentioned by Glyph if i'd known about it.</p>
<p>Anyway if your interested it's available at:</p>
<p><a href="http://code.google.com/p/psftplib/" rel="nofollow">http://code.google.com/p/psftplib/</a></p>
| 1 | 2008-10-17T02:38:30Z | [
"python",
"ftps"
] |
Python module that implements ftps | 207,939 | <p>I was wondering if anybody could point me towards a free ftps module for python.</p>
<p>I am a complete newbie to python, but this is something I need for a work project. I need an ftps client to connect to a 3rd party ftps server.</p>
<p>thanks,</p>
<p>David.</p>
| 9 | 2008-10-16T09:33:39Z | 215,529 | <p><a href="http://chandlerproject.org/bin/view/Projects/MeTooCrypto" rel="nofollow">M2Cypto</a> has a FTPS module. From the <a href="http://eikkitoivonen.net/m2crypto/api/M2Crypto.ftpslib-module.html" rel="nofollow">documentation</a>:</p>
<pre><code>>>> from M2Crypto import ftpslib
>>> f = ftpslib.FTP_TLS()
>>> f.connect('', 9021)
'220 spinnaker.dyndns.org M2Crypto (Medusa) FTP/TLS server v0.07 ready.'
>>> f.auth_tls()
>>> f.set_pasv(0)
>>> f.login('ftp', 'ngps@')
'230 Ok.'
>>> f.retrlines('LIST')
-rw-rw-r-- 1 0 198 2326 Jul 3 1996 apache_pb.gif
drwxrwxr-x 7 0 198 1536 Oct 10 2000 manual
drwxrwxr-x 2 0 198 512 Oct 31 2000 modpy
drwxrwxr-x 2 0 198 512 Oct 31 2000 bobo
drwxr-xr-x 2 0 198 14336 May 28 15:54 postgresql
drwxr-xr-x 4 100 198 512 May 16 17:19 home
drwxr-xr-x 7 100 100 3584 Sep 23 2000 openacs
drwxr-xr-x 10 0 0 512 Aug 5 2000 python1.5
-rw-r--r-- 1 100 198 326 Jul 29 03:29 index.html
drwxr-xr-x 12 0 0 512 May 31 17:08 python2.1
'226 Transfer complete'
>>> f.quit()
'221 Goodbye.'
>>>
</code></pre>
<p>Alternatively, if you wanted to minimise use of third-party modules, you should be able to subclass the standard library's <a href="http://docs.python.org/library/ftplib.html#module-ftplib" rel="nofollow">ftplib</a>.FTP class with the built-in (to Python) SSL support. M2Crypto (or <a href="http://twistedmatrix.com/trac/" rel="nofollow">Twisted</a>, if you want to go that way) is the easier solution, though.</p>
| 4 | 2008-10-18T20:16:09Z | [
"python",
"ftps"
] |
Python module that implements ftps | 207,939 | <p>I was wondering if anybody could point me towards a free ftps module for python.</p>
<p>I am a complete newbie to python, but this is something I need for a work project. I need an ftps client to connect to a 3rd party ftps server.</p>
<p>thanks,</p>
<p>David.</p>
| 9 | 2008-10-16T09:33:39Z | 2,488,262 | <p>As for the server implementation you can take a look at pyftpdlib:
<a href="http://code.google.com/p/pyftpdlib/" rel="nofollow">http://code.google.com/p/pyftpdlib/</a>
It includes a demo script implementing a working FTPS server:
<a href="http://code.google.com/p/pyftpdlib/source/browse/trunk/demo/tls_ftpd.py" rel="nofollow">http://code.google.com/p/pyftpdlib/source/browse/trunk/demo/tls_ftpd.py</a></p>
<p>As for the client implementation I provided a patch which will be included in python 2.7 and 3.2.
<a href="http://bugs.python.org/issue2054" rel="nofollow">http://bugs.python.org/issue2054</a></p>
| 2 | 2010-03-21T18:47:59Z | [
"python",
"ftps"
] |
Python module that implements ftps | 207,939 | <p>I was wondering if anybody could point me towards a free ftps module for python.</p>
<p>I am a complete newbie to python, but this is something I need for a work project. I need an ftps client to connect to a 3rd party ftps server.</p>
<p>thanks,</p>
<p>David.</p>
| 9 | 2008-10-16T09:33:39Z | 4,534,996 | <p>The ftplib module in Python version 2.7.1 has all of the functionality you will need, including TLS support.</p>
<p><a href="http://docs.python.org/library/ftplib.html#module-ftplib">http://docs.python.org/library/ftplib.html#module-ftplib</a></p>
| 6 | 2010-12-26T18:54:21Z | [
"python",
"ftps"
] |
How to enable MySQL client auto re-connect with MySQLdb? | 207,981 | <p>I came across PHP way of doing the trick:</p>
<pre><code>my_bool reconnect = 1;
mysql_options(&mysql, MYSQL_OPT_RECONNECT, &reconnect);
</code></pre>
<p>but no luck with MySQLdb (python-mysql).</p>
<p>Can anybody please give a clue? Thanks.</p>
| 30 | 2008-10-16T09:56:05Z | 210,096 | <p>If you are using ubuntu Linux there was a patch added to the python-mysql package that added the ability to set that same MYSQL_OPT_RECONNECT option (see <a href="https://launchpad.net/ubuntu/hardy/+source/python-mysqldb/1.2.2-5">here</a>). I have not tried it though.</p>
<p>Unfortunately, the patch was later removed due to a conflict with autoconnect and transations (described <a href="https://launchpad.net/ubuntu/+source/python-mysqldb">here</a>).</p>
<p>The comments from that page say:
1.2.2-7 Published in intrepid-release on 2008-06-19 </p>
<p>python-mysqldb (1.2.2-7) unstable; urgency=low</p>
<p>[ Sandro Tosi ]
* debian/control
- list items lines in description starts with 2 space, to avoid reformat
on webpages (Closes: #480341)</p>
<p>[ Bernd Zeimetz ]
* debian/patches/02_reconnect.dpatch:
- Dropping patch:
Comment in Storm which explains the problem:</p>
<pre><code> # Here is another sad story about bad transactional behavior. MySQL
# offers a feature to automatically reconnect dropped connections.
# What sounds like a dream, is actually a nightmare for anyone who
# is dealing with transactions. When a reconnection happens, the
# currently running transaction is transparently rolled back, and
# everything that was being done is lost, without notice. Not only
# that, but the connection may be put back in AUTOCOMMIT mode, even
# when that's not the default MySQLdb behavior. The MySQL developers
# quickly understood that this is a terrible idea, and removed the
# behavior in MySQL 5.0.3. Unfortunately, Debian and Ubuntu still
# have a patch right now which *reenables* that behavior by default
# even past version 5.0.3.
</code></pre>
| 7 | 2008-10-16T20:11:18Z | [
"python",
"mysql"
] |
How to enable MySQL client auto re-connect with MySQLdb? | 207,981 | <p>I came across PHP way of doing the trick:</p>
<pre><code>my_bool reconnect = 1;
mysql_options(&mysql, MYSQL_OPT_RECONNECT, &reconnect);
</code></pre>
<p>but no luck with MySQLdb (python-mysql).</p>
<p>Can anybody please give a clue? Thanks.</p>
| 30 | 2008-10-16T09:56:05Z | 210,112 | <p>You other bet it to work around dropped connections yourself with code.</p>
<p>One way to do it would be the following:</p>
<pre><code>import MySQLdb
class DB:
conn = None
def connect(self):
self.conn = MySQLdb.connect()
def cursor(self):
try:
return self.conn.cursor()
except (AttributeError, MySQLdb.OperationalError):
self.connect()
return self.conn.cursor()
db = DB()
cur = db.cursor()
# wait a long time for the Mysql connection to timeout
cur = db.cursor()
# still works
</code></pre>
| -2 | 2008-10-16T20:15:17Z | [
"python",
"mysql"
] |
How to enable MySQL client auto re-connect with MySQLdb? | 207,981 | <p>I came across PHP way of doing the trick:</p>
<pre><code>my_bool reconnect = 1;
mysql_options(&mysql, MYSQL_OPT_RECONNECT, &reconnect);
</code></pre>
<p>but no luck with MySQLdb (python-mysql).</p>
<p>Can anybody please give a clue? Thanks.</p>
| 30 | 2008-10-16T09:56:05Z | 210,885 | <p>I had a similar problem with MySQL and Python, and the solution that worked for me was to upgrade MySQL to 5.0.27 (on Fedora Core 6; your system may work fine with a different version).</p>
<p>I tried a lot of other things, including patching the Python libraries, but upgrading the database was a lot easier and (I think) a better decision.</p>
| 1 | 2008-10-17T01:50:49Z | [
"python",
"mysql"
] |
How to enable MySQL client auto re-connect with MySQLdb? | 207,981 | <p>I came across PHP way of doing the trick:</p>
<pre><code>my_bool reconnect = 1;
mysql_options(&mysql, MYSQL_OPT_RECONNECT, &reconnect);
</code></pre>
<p>but no luck with MySQLdb (python-mysql).</p>
<p>Can anybody please give a clue? Thanks.</p>
| 30 | 2008-10-16T09:56:05Z | 982,873 | <p>I solved this problem by creating a function that wraps the <code>cursor.execute()</code> method since that's what was throwing the <code>MySQLdb.OperationalError</code> exception. The other example above implies that it is the <code>conn.cursor()</code> method that throws this exception.</p>
<pre><code>import MySQLdb
class DB:
conn = None
def connect(self):
self.conn = MySQLdb.connect()
def query(self, sql):
try:
cursor = self.conn.cursor()
cursor.execute(sql)
except (AttributeError, MySQLdb.OperationalError):
self.connect()
cursor = self.conn.cursor()
cursor.execute(sql)
return cursor
db = DB()
sql = "SELECT * FROM foo"
cur = db.query(sql)
# wait a long time for the Mysql connection to timeout
cur = db.query(sql)
# still works
</code></pre>
| 58 | 2009-06-11T18:38:11Z | [
"python",
"mysql"
] |
How to enable MySQL client auto re-connect with MySQLdb? | 207,981 | <p>I came across PHP way of doing the trick:</p>
<pre><code>my_bool reconnect = 1;
mysql_options(&mysql, MYSQL_OPT_RECONNECT, &reconnect);
</code></pre>
<p>but no luck with MySQLdb (python-mysql).</p>
<p>Can anybody please give a clue? Thanks.</p>
| 30 | 2008-10-16T09:56:05Z | 4,101,812 | <p>you can separate the commit and the close for the connection...that's not cute but it does it.</p>
<pre><code>class SqlManager(object):
"""
Class that handle the database operation
"""
def __init__(self,server, database, username, pswd):
self.server = server
self.dataBase = database
self.userID = username
self.password = pswd
def Close_Transation(self):
"""
Commit the SQL Query
"""
try:
self.conn.commit()
except Sql.Error, e:
print "-- reading SQL Error %d: %s" % (e.args[0], e.args[1])
def Close_db(self):
try:
self.conn.close()
except Sql.Error, e:
print "-- reading SQL Error %d: %s" % (e.args[0], e.args[1])
def __del__(self):
print "close connection with database.."
self.conn.close()
</code></pre>
| 3 | 2010-11-04T22:01:44Z | [
"python",
"mysql"
] |
How to enable MySQL client auto re-connect with MySQLdb? | 207,981 | <p>I came across PHP way of doing the trick:</p>
<pre><code>my_bool reconnect = 1;
mysql_options(&mysql, MYSQL_OPT_RECONNECT, &reconnect);
</code></pre>
<p>but no luck with MySQLdb (python-mysql).</p>
<p>Can anybody please give a clue? Thanks.</p>
| 30 | 2008-10-16T09:56:05Z | 29,331,237 | <p>I had problems with the proposed solution because it didn't catch the exception. I am not sure why.</p>
<p>I have solved the problem with the <code>ping(True)</code> statement which I think is neater:</p>
<pre><code>import MySQLdb
con=MySQLdb.Connect()
con.ping(True)
cur=con.cursor()
</code></pre>
<p>Got it from here: <a href="http://www.neotitans.com/resources/python/mysql-python-connection-error-2006.html">http://www.neotitans.com/resources/python/mysql-python-connection-error-2006.html</a></p>
| 9 | 2015-03-29T15:48:28Z | [
"python",
"mysql"
] |
How to make Apache/mod_python process collect its zombies? | 208,085 | <pre><code>Apache/2.2.6 (Unix) DAV/2 mod_python/3.2.8 Python/2.4.4 configured ...
</code></pre>
<p>One of apache processes spawns some long-running python script asynchronously, and apparently doesn't seem to collect its child process table entry. After that long-run-in-subprocess python script finishes - defunct python process has been left.</p>
<pre><code># ps -ef | grep httpd
root 23911 1 0 Oct15 ? 00:00:01 /usr/sbin/httpd
...
qa 23920 23911 0 Oct15 ? 00:00:00 /usr/sbin/httpd
# ps -ef | grep python
...
qa 28449 23920 0 12:38 ? 00:00:00 [python] <defunct>
</code></pre>
<p>What is the way to make the Apache process to collect its children? Is it possible to do the job via a mod_python request handler ( like PythonCleanupHandler for example)?</p>
<p>Thanks.</p>
| 2 | 2008-10-16T10:52:00Z | 209,051 | <p>File a bug report.</p>
<p>EDIT: I'm serious. Leaving zombies behind is a bug, and there is almost certainly nothing you can do from within Python.</p>
<p>Upgrade to the latest versions, look for bug reports, post on the mailing list, switch to another product.</p>
| 2 | 2008-10-16T15:31:54Z | [
"python",
"apache",
"apache2",
"mod-python"
] |
How to make Apache/mod_python process collect its zombies? | 208,085 | <pre><code>Apache/2.2.6 (Unix) DAV/2 mod_python/3.2.8 Python/2.4.4 configured ...
</code></pre>
<p>One of apache processes spawns some long-running python script asynchronously, and apparently doesn't seem to collect its child process table entry. After that long-run-in-subprocess python script finishes - defunct python process has been left.</p>
<pre><code># ps -ef | grep httpd
root 23911 1 0 Oct15 ? 00:00:01 /usr/sbin/httpd
...
qa 23920 23911 0 Oct15 ? 00:00:00 /usr/sbin/httpd
# ps -ef | grep python
...
qa 28449 23920 0 12:38 ? 00:00:00 [python] <defunct>
</code></pre>
<p>What is the way to make the Apache process to collect its children? Is it possible to do the job via a mod_python request handler ( like PythonCleanupHandler for example)?</p>
<p>Thanks.</p>
| 2 | 2008-10-16T10:52:00Z | 219,073 | <p>Drop mod_python in favor of <a href="http://code.google.com/p/modwsgi/" rel="nofollow">mod_wsgi</a> (is used for <a href="http://wsgi.org/wsgi/" rel="nofollow">wsgi</a>), which does not leave orphaned zombies around afaik.</p>
| 2 | 2008-10-20T16:31:46Z | [
"python",
"apache",
"apache2",
"mod-python"
] |
How to read and write multiple files? | 208,120 | <p>I want to write a program for this: In a folder I have <em>n</em> number of files; first read one file and perform some operation then store result in a separate file. Then read 2nd file, perform operation again and save result in new 2nd file. Do the same procedure for <em>n</em> number of files. The program reads all files one by one and stores results of each file separately. Please give examples how I can do it.</p>
| 4 | 2008-10-16T11:06:36Z | 208,156 | <pre><code>import sys
# argv is your commandline arguments, argv[0] is your program name, so skip it
for n in sys.argv[1:]:
print(n) #print out the filename we are currently processing
input = open(n, "r")
output = open(n + ".out", "w")
# do some processing
input.close()
output.close()
</code></pre>
<p>Then call it like:</p>
<pre>
./foo.py bar.txt baz.txt
</pre>
| 9 | 2008-10-16T11:23:29Z | [
"python"
] |
How to read and write multiple files? | 208,120 | <p>I want to write a program for this: In a folder I have <em>n</em> number of files; first read one file and perform some operation then store result in a separate file. Then read 2nd file, perform operation again and save result in new 2nd file. Do the same procedure for <em>n</em> number of files. The program reads all files one by one and stores results of each file separately. Please give examples how I can do it.</p>
| 4 | 2008-10-16T11:06:36Z | 208,227 | <p>You may find the <a href="https://docs.python.org/2/library/fileinput.html" rel="nofollow"><code>fileinput</code></a> module useful. It is designed for exactly this problem.</p>
| 5 | 2008-10-16T11:51:04Z | [
"python"
] |
How to read and write multiple files? | 208,120 | <p>I want to write a program for this: In a folder I have <em>n</em> number of files; first read one file and perform some operation then store result in a separate file. Then read 2nd file, perform operation again and save result in new 2nd file. Do the same procedure for <em>n</em> number of files. The program reads all files one by one and stores results of each file separately. Please give examples how I can do it.</p>
| 4 | 2008-10-16T11:06:36Z | 208,342 | <p>I think what you miss is how to retrieve all the files in that directory.
To do so, use the glob module.
Here is an example which will duplicate all the files with extension *.txt to files with extension *.out</p>
<pre><code>import glob
list_of_files = glob.glob('./*.txt') # create the list of file
for file_name in list_of_files:
FI = open(file_name, 'r')
FO = open(file_name.replace('txt', 'out'), 'w')
for line in FI:
FO.write(line)
FI.close()
FO.close()
</code></pre>
| 4 | 2008-10-16T12:28:48Z | [
"python"
] |
How to read and write multiple files? | 208,120 | <p>I want to write a program for this: In a folder I have <em>n</em> number of files; first read one file and perform some operation then store result in a separate file. Then read 2nd file, perform operation again and save result in new 2nd file. Do the same procedure for <em>n</em> number of files. The program reads all files one by one and stores results of each file separately. Please give examples how I can do it.</p>
| 4 | 2008-10-16T11:06:36Z | 208,731 | <p>Combined answer incorporating directory or specific list of filenames arguments:</p>
<pre><code>import sys
import os.path
import glob
def processFile(filename):
fileHandle = open(filename, "r")
for line in fileHandle:
# do some processing
pass
fileHandle.close()
def outputResults(filename):
output_filemask = "out"
fileHandle = open("%s.%s" % (filename, output_filemask), "w")
# do some processing
fileHandle.write('processed\n')
fileHandle.close()
def processFiles(args):
input_filemask = "log"
directory = args[1]
if os.path.isdir(directory):
print "processing a directory"
list_of_files = glob.glob('%s/*.%s' % (directory, input_filemask))
else:
print "processing a list of files"
list_of_files = sys.argv[1:]
for file_name in list_of_files:
print file_name
processFile(file_name)
outputResults(file_name)
if __name__ == '__main__':
if (len(sys.argv) > 1):
processFiles(sys.argv)
else:
print 'usage message'
</code></pre>
| 0 | 2008-10-16T14:12:40Z | [
"python"
] |
How to read and write multiple files? | 208,120 | <p>I want to write a program for this: In a folder I have <em>n</em> number of files; first read one file and perform some operation then store result in a separate file. Then read 2nd file, perform operation again and save result in new 2nd file. Do the same procedure for <em>n</em> number of files. The program reads all files one by one and stores results of each file separately. Please give examples how I can do it.</p>
| 4 | 2008-10-16T11:06:36Z | 211,188 | <p>I've just learned of the os.walk() command recently, and it may help you here.
It allows you to walk down a directory tree structure.</p>
<pre><code>import os
OUTPUT_DIR = 'C:\\RESULTS'
for path, dirs, files in os.walk('.'):
for file in files:
read_f = open(os.join(path,file),'r')
write_f = open(os.path.join(OUTPUT_DIR,file))
# Do stuff
</code></pre>
| 1 | 2008-10-17T05:53:51Z | [
"python"
] |
How to read and write multiple files? | 208,120 | <p>I want to write a program for this: In a folder I have <em>n</em> number of files; first read one file and perform some operation then store result in a separate file. Then read 2nd file, perform operation again and save result in new 2nd file. Do the same procedure for <em>n</em> number of files. The program reads all files one by one and stores results of each file separately. Please give examples how I can do it.</p>
| 4 | 2008-10-16T11:06:36Z | 11,945,810 | <pre><code>from pylab import *
import csv
import os
import glob
import re
x=[]
y=[]
f=open("one.txt",'w')
for infile in glob.glob(('*.csv')):
# print "" +infile
csv23=csv2rec(""+infile,'rb',delimiter=',')
for line in csv23:
x.append(line[1])
# print len(x)
for i in range(3000,8000):
y.append(x[i])
print ""+infile,"\t",mean(y)
print >>f,""+infile,"\t\t",mean(y)
del y[:len(y)]
del x[:len(x)]
</code></pre>
| 0 | 2012-08-14T04:30:15Z | [
"python"
] |
How to base64 encode a PDF file in Python | 208,894 | <p>How should I base64 encode a PDF file for transport over XML-RPC in Python?</p>
| 6 | 2008-10-16T14:54:49Z | 208,950 | <p>You can do it with the <a href="http://www.python.org/doc/2.5.2/lib/module-base64.html" rel="nofollow">base64 library</a>, legacy interface.</p>
| 1 | 2008-10-16T15:08:49Z | [
"python",
"encoding",
"base64",
"xml-rpc"
] |
How to base64 encode a PDF file in Python | 208,894 | <p>How should I base64 encode a PDF file for transport over XML-RPC in Python?</p>
| 6 | 2008-10-16T14:54:49Z | 208,960 | <p>Actually, after some more digging, it looks like the <code>xmlrpclib module may have the piece I need with it's <code>Binary</code> helper class:</p>
<pre>
binary_obj = xmlrpclib.Binary( open('foo.pdf').read() )
</code></pre>
<p>Here's an example from the <a href="http://trac-hacks.org/wiki/XmlRpcPlugin" rel="nofollow">Trac XML-RPC documentation</a></p>
<pre><code>
import xmlrpclib
server = xmlrpclib.ServerProxy("http://athomas:password@localhost:8080/trunk/login/xmlrpc")
server.wiki.putAttachment('WikiStart/t.py', xmlrpclib.Binary(open('t.py').read()))
</code></pre>
| 4 | 2008-10-16T15:09:33Z | [
"python",
"encoding",
"base64",
"xml-rpc"
] |
How to base64 encode a PDF file in Python | 208,894 | <p>How should I base64 encode a PDF file for transport over XML-RPC in Python?</p>
| 6 | 2008-10-16T14:54:49Z | 208,975 | <p>Looks like you might be able to use the <a href="http://docs.python.org/library/binascii.html" rel="nofollow">binascii</a> module</p>
<blockquote>
<p>binascii.b2a_base64(data)</p>
<p>Convert binary data to a line of ASCII characters in base64 coding. The return value is the converted line, including a newline char. The length of data should be at most 57 to adhere to the base64 standard.</p>
</blockquote>
| 0 | 2008-10-16T15:13:02Z | [
"python",
"encoding",
"base64",
"xml-rpc"
] |
How to base64 encode a PDF file in Python | 208,894 | <p>How should I base64 encode a PDF file for transport over XML-RPC in Python?</p>
| 6 | 2008-10-16T14:54:49Z | 209,363 | <p><i>NOTE: this is a community-wiki owned copy of Pat Notz's answer. This answer can be selected as the chosen answer. Edit freely to improve.</i></p>
<h3>Pat Notz says:</h3>
<p>Actually, after some more digging, it looks like the <code>xmlrpclib</code> module may have the piece I need with its <code>Binary</code> helper class:</p>
<pre><code>binary_obj = xmlrpclib.Binary( open('foo.pdf').read() )
</code></pre>
<p>Here's an example from the <a href="http://trac-hacks.org/wiki/XmlRpcPlugin" rel="nofollow">Trac XML-RPC documentation</a></p>
<pre><code>import xmlrpclib
server = xmlrpclib.ServerProxy("http://athomas:password@localhost:8080/trunk/login/xmlrpc")
server.wiki.putAttachment('WikiStart/t.py', xmlrpclib.Binary(open('t.py').read()))
</code></pre>
| 1 | 2008-10-16T16:38:08Z | [
"python",
"encoding",
"base64",
"xml-rpc"
] |
How to base64 encode a PDF file in Python | 208,894 | <p>How should I base64 encode a PDF file for transport over XML-RPC in Python?</p>
| 6 | 2008-10-16T14:54:49Z | 210,534 | <p>If you don't want to use the xmlrpclib's Binary class, you can just use the .encode() method of strings:</p>
<pre><code>a = open("pdf_reference.pdf", "rb").read().encode("base64")
</code></pre>
| 21 | 2008-10-16T22:33:24Z | [
"python",
"encoding",
"base64",
"xml-rpc"
] |
Django template with jquery: Ajax update on existing page | 209,023 | <p>I have a Google App Engine that has a form. When the user clicks on the submit button, AJAX operation will be called, and the server will output something to append to the end of the very page where it comes from. How, I have a Django template, and I intend to use jquery. I have the following view:</p>
<pre><code><html>
<head>
<title></title>
<script type="text/javascript" src="scripts/jquery.js"></script>
<script type="text/javascript" src="scripts/scripts.js"></script>
</head>
<body>
welcome
<form id="SubmitForm" action="/" method="POST">
<input type="file" name="vsprojFiles" />
<br/>
<input type="submit" id="SubmitButton"/>
</form>
<div id="Testing">
{{thebest}}
</div>
</body>
</html>
</code></pre>
<p>Here's the script in scripts.js:</p>
<pre><code>$(function() {
$("#SubmitForm").click(submitMe);
});
var submitMe = function(){
//alert('no way');
var f = $('#SubmitForm');
var action = f.attr("action");
var serializedForm = f.serialize();
$.ajax( {
type: 'post',
data: serializedForm,
url: form_action,
success: function( result ) {
$('#SubmitForm').after( "<div><tt>" +
result +
"</tt></div>" );
}
} );
};
</code></pre>
<p>And here's my controller code:</p>
<pre><code>from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext import db
from google.appengine.ext.webapp import template
from google.appengine.api.urlfetch_errors import *
import cgi
import wsgiref.handlers
import os
import sys
import re
import urllib
from django.utils import simplejson
class MainPage(webapp.RequestHandler):
def get(self):
path = os.path.join(os.path.dirname(__file__), 'Index.html')
template_values={'thebest': 'thebest'}
tmplRender =template.render(path, template_values)
self.response.out.write(tmplRender)
pass
def Post(self):
print >>sys.__stderr__,'me posting'
result = 'grsgres'
self.response.out.write(simplejson.dumps(result))
</code></pre>
<p>As you can see, when the user clicks on the submitbutton, the controller method Mainpage.post will be called.</p>
<p>Now I want to display the content of the 'result' variable right after the form, how can I do it?</p>
| 3 | 2008-10-16T15:27:38Z | 266,862 | <p>Without being able to test the code, what are your results? Have you checked the results returned by the AJAX call? I would suggest you run Firefox with Firebug and log the AJAX results to the Firebug console to see what you get:</p>
<pre><code>//...
success: function( result ) {
console.log( result );
$('#SubmitForm').after( "<div><tt>" +
// ...
</code></pre>
<p>You can also use the Net panel of Firebug to see what is being passed back and forth.</p>
<p>Also, what does "simplejson.dumps(result)" result in?</p>
| 2 | 2008-11-05T21:53:18Z | [
"jquery",
"python",
"django",
"google-app-engine",
"django-templates"
] |
Django template with jquery: Ajax update on existing page | 209,023 | <p>I have a Google App Engine that has a form. When the user clicks on the submit button, AJAX operation will be called, and the server will output something to append to the end of the very page where it comes from. How, I have a Django template, and I intend to use jquery. I have the following view:</p>
<pre><code><html>
<head>
<title></title>
<script type="text/javascript" src="scripts/jquery.js"></script>
<script type="text/javascript" src="scripts/scripts.js"></script>
</head>
<body>
welcome
<form id="SubmitForm" action="/" method="POST">
<input type="file" name="vsprojFiles" />
<br/>
<input type="submit" id="SubmitButton"/>
</form>
<div id="Testing">
{{thebest}}
</div>
</body>
</html>
</code></pre>
<p>Here's the script in scripts.js:</p>
<pre><code>$(function() {
$("#SubmitForm").click(submitMe);
});
var submitMe = function(){
//alert('no way');
var f = $('#SubmitForm');
var action = f.attr("action");
var serializedForm = f.serialize();
$.ajax( {
type: 'post',
data: serializedForm,
url: form_action,
success: function( result ) {
$('#SubmitForm').after( "<div><tt>" +
result +
"</tt></div>" );
}
} );
};
</code></pre>
<p>And here's my controller code:</p>
<pre><code>from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext import db
from google.appengine.ext.webapp import template
from google.appengine.api.urlfetch_errors import *
import cgi
import wsgiref.handlers
import os
import sys
import re
import urllib
from django.utils import simplejson
class MainPage(webapp.RequestHandler):
def get(self):
path = os.path.join(os.path.dirname(__file__), 'Index.html')
template_values={'thebest': 'thebest'}
tmplRender =template.render(path, template_values)
self.response.out.write(tmplRender)
pass
def Post(self):
print >>sys.__stderr__,'me posting'
result = 'grsgres'
self.response.out.write(simplejson.dumps(result))
</code></pre>
<p>As you can see, when the user clicks on the submitbutton, the controller method Mainpage.post will be called.</p>
<p>Now I want to display the content of the 'result' variable right after the form, how can I do it?</p>
| 3 | 2008-10-16T15:27:38Z | 832,625 | <p>here is an example of my success function </p>
<pre><code>success: function(json){
$('#gallons_cont').html(json['gallons']);
$('#area_cont').html(json['area']);
$('#usage_cont').html(json['usage'])
$('#results_json').show('slow');
},
</code></pre>
<p>please note that you do have to debug using firebug or something similar as there might be some issue serializing which will throw and error but will not be vieweable unless you use something like firebug or implement .ajax error</p>
| 1 | 2009-05-07T02:26:37Z | [
"jquery",
"python",
"django",
"google-app-engine",
"django-templates"
] |
Why do I receive an ImportError when running one of the CherryPy tutorials | 209,429 | <p>I have installed CherryPy 3.1.0,. Here is what happens when I try to run tutorial 9:</p>
<pre><code>$ cd /Library/Python/2.5/site-packages/cherrypy/tutorial/
$ python tut09_files.py
Traceback (most recent call last):
File "tut09_files.py", line 48, in <module>
from cherrypy.lib import static
ImportError: cannot import name static
</code></pre>
<p>The previous line in the file:</p>
<pre><code>import cherrypy
</code></pre>
<p>passes without error, so it appears that it can find cherrypy on the path. What am I missing?</p>
| 1 | 2008-10-16T16:58:43Z | 209,488 | <p>This works for me, and I'm also using CherryPy 3.1.0, so I'm not sure what to tell you.</p>
<p>Look in your /Library/Python/2.5/site-packages/cherrypy/lib directory for a file named static.py; if this file exists then I'm not sure what to tell you. If it doesn't then something has happened to your CherryPy and I'd advise you to reinstall. If it does then you should check the value of <code>sys.path</code> to make sure it's detecting the right version of CherryPy.</p>
<p>You can also try running the python interpreter on the command line and then doing a <code>from cherrypy.lib import static</code> to see if you get the same result.</p>
| 1 | 2008-10-16T17:16:56Z | [
"python",
"cherrypy"
] |
Why do I receive an ImportError when running one of the CherryPy tutorials | 209,429 | <p>I have installed CherryPy 3.1.0,. Here is what happens when I try to run tutorial 9:</p>
<pre><code>$ cd /Library/Python/2.5/site-packages/cherrypy/tutorial/
$ python tut09_files.py
Traceback (most recent call last):
File "tut09_files.py", line 48, in <module>
from cherrypy.lib import static
ImportError: cannot import name static
</code></pre>
<p>The previous line in the file:</p>
<pre><code>import cherrypy
</code></pre>
<p>passes without error, so it appears that it can find cherrypy on the path. What am I missing?</p>
| 1 | 2008-10-16T16:58:43Z | 216,440 | <p>I had an old CherryPy-2.3.0-py2.5.egg file in my site-packages. After removing the old .egg I could run the tutorial.</p>
| 1 | 2008-10-19T13:43:18Z | [
"python",
"cherrypy"
] |
Can I use Python as a Bash replacement? | 209,470 | <p>I currently do my textfile manipulation through a bunch of badly remembered AWK, sed, Bash and a tiny bit of Perl.</p>
<p>I've seen mentioned a few places that python is good for this kind of thing, I know a little and I would like to know more. Is Python a good choice for this, and is there a good book or guide to learning how to use Python to replace shell scripting, AWK, sed and friends?</p>
| 207 | 2008-10-16T17:11:37Z | 209,474 | <p>Python would be perfectly fine for text file manipulation. For learning, check <a href="http://stackoverflow.com/questions/918/how-to-learn-python-good-example-code#964">here</a>.</p>
| 0 | 2008-10-16T17:13:39Z | [
"python",
"bash",
"shell"
] |
Can I use Python as a Bash replacement? | 209,470 | <p>I currently do my textfile manipulation through a bunch of badly remembered AWK, sed, Bash and a tiny bit of Perl.</p>
<p>I've seen mentioned a few places that python is good for this kind of thing, I know a little and I would like to know more. Is Python a good choice for this, and is there a good book or guide to learning how to use Python to replace shell scripting, AWK, sed and friends?</p>
| 207 | 2008-10-16T17:11:37Z | 209,557 | <p>I suggest the awesome online book <em><a href="http://www.diveintopython.net">Dive Into Python</a></em>. It's how I learned the language originally.</p>
<p>Beyone teaching you the basic structure of the language, and a whole lot of useful data structures, it has a good chapter on <a href="http://www.diveintopython.net/file_handling/index.html">file handling</a> and subsequent chapters on <a href="http://www.diveintopython.net/regular_expressions/index.html">regular expressions</a> and more.</p>
| 8 | 2008-10-16T17:40:43Z | [
"python",
"bash",
"shell"
] |
Can I use Python as a Bash replacement? | 209,470 | <p>I currently do my textfile manipulation through a bunch of badly remembered AWK, sed, Bash and a tiny bit of Perl.</p>
<p>I've seen mentioned a few places that python is good for this kind of thing, I know a little and I would like to know more. Is Python a good choice for this, and is there a good book or guide to learning how to use Python to replace shell scripting, AWK, sed and friends?</p>
| 207 | 2008-10-16T17:11:37Z | 209,562 | <p>Any shell has several sets of features.</p>
<ul>
<li><p>The Essential Linux/Unix commands. All of these are available through the <a href="https://docs.python.org/3/library/subprocess.html">subprocess</a> library. This isn't always the best first choice for doing <em>all</em> external commands. Look also at <a href="https://docs.python.org/3/library/shutil.html">shutil</a> for some commands that are separate Linux commands, but you could probably implement directly in your Python scripts. Another huge batch of Linux commands are in the <a href="https://docs.python.org/3/library/os.html">os</a> library; you can do these more simply in Python.</p>
<p>And -- bonus! -- more quickly. Each separate Linux command in the shell (with a few exceptions) forks a subprocess. By using Python <code>shutil</code> and <code>os</code> modules, you don't fork a subprocess.</p></li>
<li><p>The shell environment features. This includes stuff that sets a command's environment (current directory and environment variables and what-not). You can easily manage this from Python directly.</p></li>
<li><p>The shell programming features. This is all the process status code checking, the various logic commands (if, while, for, etc.) the test command and all of it's relatives. The function definition stuff. This is all much, much easier in Python. This is one of the huge victories in getting rid of bash and doing it in Python.</p></li>
<li><p>Interaction features. This includes command history and what-not. You don't need this for writing shell scripts. This is only for human interaction, and not for script-writing.</p></li>
<li><p>The shell file management features. This includes redirection and pipelines. This is trickier. Much of this can be done with subprocess. But some things that are easy in the shell are unpleasant in Python. Specifically stuff like <code>(a | b; c ) | something >result</code>. This runs two processes in parallel (with output of <code>a</code> as input to <code>b</code>), followed by a third process. The output from that sequence is run in parallel with <code>something</code> and the output is collected into a file named <code>result</code>. That's just complex to express in any other language.</p></li>
</ul>
<p>Specific programs (awk, sed, grep, etc.) can often be rewritten as Python modules. Don't go overboard. Replace what you need and evolve your "grep" module. Don't start out writing a Python module that replaces "grep".</p>
<p>The best thing is that you can do this in steps.</p>
<ol>
<li>Replace AWK and PERL with Python. Leave everything else alone.</li>
<li>Look at replacing GREP with Python. This can be a bit more complex, but your version of GREP can be tailored to your processing needs.</li>
<li>Look at replacing FIND with Python loops that use <code>os.walk</code>. This is a big win because you don't spawn as many processes.</li>
<li>Look at replacing common shell logic (loops, decisions, etc.) with Python scripts.</li>
</ol>
| 127 | 2008-10-16T17:41:44Z | [
"python",
"bash",
"shell"
] |
Can I use Python as a Bash replacement? | 209,470 | <p>I currently do my textfile manipulation through a bunch of badly remembered AWK, sed, Bash and a tiny bit of Perl.</p>
<p>I've seen mentioned a few places that python is good for this kind of thing, I know a little and I would like to know more. Is Python a good choice for this, and is there a good book or guide to learning how to use Python to replace shell scripting, AWK, sed and friends?</p>
| 207 | 2008-10-16T17:11:37Z | 209,565 | <p>If your textfile manipulation usually is one-time, possibly done on the shell-prompt, you will not get anything better from python.</p>
<p>On the other hand, if you usually have to do the same (or similar) task over and over, and you have to write your scripts for doing that, then python is great - and you can easily create your own libraries (you can do that with shell scripts too, but it's more cumbersome).</p>
<p>A very simple example to get a feeling.</p>
<pre><code>import popen2
stdout_text, stdin_text=popen2.popen2("your-shell-command-here")
for line in stdout_text:
if line.startswith("#"):
pass
else
jobID=int(line.split(",")[0].split()[1].lstrip("<").rstrip(">"))
# do something with jobID
</code></pre>
<p>Check also sys and getopt module, they are the first you will need.</p>
| 1 | 2008-10-16T17:42:48Z | [
"python",
"bash",
"shell"
] |
Can I use Python as a Bash replacement? | 209,470 | <p>I currently do my textfile manipulation through a bunch of badly remembered AWK, sed, Bash and a tiny bit of Perl.</p>
<p>I've seen mentioned a few places that python is good for this kind of thing, I know a little and I would like to know more. Is Python a good choice for this, and is there a good book or guide to learning how to use Python to replace shell scripting, AWK, sed and friends?</p>
| 207 | 2008-10-16T17:11:37Z | 209,665 | <p>Your best bet is a tool that is specifically geared towards your problem. If it's processing text files, then Sed, Awk and Perl are the top contenders. Python is a general-purpose <em>dynamic</em> language. As with any general purpose language, there's support for file-manipulation, but that isn't what it's core purpose is. I would consider Python or Ruby if I had a requirement for a dynamic language in particular.</p>
<p>In short, learn Sed and Awk really well, plus all the other goodies that come with your flavour of *nix (All the Bash built-ins, grep, tr and so forth). If it's text file processing you're interested in, you're already using the right stuff. </p>
| 2 | 2008-10-16T18:14:48Z | [
"python",
"bash",
"shell"
] |
Can I use Python as a Bash replacement? | 209,470 | <p>I currently do my textfile manipulation through a bunch of badly remembered AWK, sed, Bash and a tiny bit of Perl.</p>
<p>I've seen mentioned a few places that python is good for this kind of thing, I know a little and I would like to know more. Is Python a good choice for this, and is there a good book or guide to learning how to use Python to replace shell scripting, AWK, sed and friends?</p>
| 207 | 2008-10-16T17:11:37Z | 209,670 | <ul>
<li>If you want to use Python as a shell, why not have a look at <a href="http://ipython.org/">IPython</a> ? It is also good to learn interactively the language.</li>
<li>If you do a lot of text manipulation, and if you use Vim as a text editor, you can also directly write plugins for Vim in python. just type ":help python" in Vim and follow the instructions or have a look at this <a href="http://www.tummy.com/Community/Presentations/vimpython-20070225/vim.html">presentation</a>. It is so easy and powerfull to write functions that you will use directly in your editor!</li>
</ul>
| 28 | 2008-10-16T18:16:52Z | [
"python",
"bash",
"shell"
] |
Can I use Python as a Bash replacement? | 209,470 | <p>I currently do my textfile manipulation through a bunch of badly remembered AWK, sed, Bash and a tiny bit of Perl.</p>
<p>I've seen mentioned a few places that python is good for this kind of thing, I know a little and I would like to know more. Is Python a good choice for this, and is there a good book or guide to learning how to use Python to replace shell scripting, AWK, sed and friends?</p>
| 207 | 2008-10-16T17:11:37Z | 210,290 | <p>In the beginning there was sh, sed, and awk (and find, and grep, and...). It was good. But awk can be an odd little beast and hard to remember if you don't use it often. Then the great camel created Perl. Perl was a system administrator's dream. It was like shell scripting on steroids. Text processing, including regular expressions were just part of the language. Then it got ugly... People tried to make big applications with Perl. Now, don't get me wrong, Perl can be an application, but it can (can!) look like a mess if you're not really careful. Then there is all this flat data business. It's enough to drive a programmer nuts.</p>
<p>Enter Python, Ruby, et al. These are really very good general purpose languages. They support text processing, and do it well (though perhaps not as tightly entwined in the basic core of the language). But they also scale up very well, and still have nice looking code at the end of the day. They also have developed pretty hefty communities with plenty of libraries for most anything.</p>
<p>Now, much of the negativeness towards Perl is a matter of opinion, and certainly some people can write very clean Perl, but with this many people complaining about it being too easy to create obfuscated code, you know some grain of truth is there. The question really becomes then, are you ever going to use this language for more than simple bash script replacements. If not, learn some more Perl.. it is absolutely fantastic for that. If, on the other hand, you want a language that will grow with you as you want to do more, may I suggest Python or Ruby.</p>
<p>Either way, good luck!</p>
| 16 | 2008-10-16T20:58:33Z | [
"python",
"bash",
"shell"
] |
Can I use Python as a Bash replacement? | 209,470 | <p>I currently do my textfile manipulation through a bunch of badly remembered AWK, sed, Bash and a tiny bit of Perl.</p>
<p>I've seen mentioned a few places that python is good for this kind of thing, I know a little and I would like to know more. Is Python a good choice for this, and is there a good book or guide to learning how to use Python to replace shell scripting, AWK, sed and friends?</p>
| 207 | 2008-10-16T17:11:37Z | 210,429 | <p>I have built semi-long shell scripts (300-500 lines) and Python code which does similar functionality. When many external commands are being executed, I find the shell is easier to use. Perl is also a good option when there is lots of text manipulation.</p>
| 4 | 2008-10-16T21:49:19Z | [
"python",
"bash",
"shell"
] |
Can I use Python as a Bash replacement? | 209,470 | <p>I currently do my textfile manipulation through a bunch of badly remembered AWK, sed, Bash and a tiny bit of Perl.</p>
<p>I've seen mentioned a few places that python is good for this kind of thing, I know a little and I would like to know more. Is Python a good choice for this, and is there a good book or guide to learning how to use Python to replace shell scripting, AWK, sed and friends?</p>
| 207 | 2008-10-16T17:11:37Z | 210,474 | <p>Adding to previous answers: check the <a href="http://www.noah.org/wiki/Pexpect">pexpect</a> module for dealing with interactive commands (adduser, passwd etc.)</p>
| 6 | 2008-10-16T22:05:19Z | [
"python",
"bash",
"shell"
] |
Can I use Python as a Bash replacement? | 209,470 | <p>I currently do my textfile manipulation through a bunch of badly remembered AWK, sed, Bash and a tiny bit of Perl.</p>
<p>I've seen mentioned a few places that python is good for this kind of thing, I know a little and I would like to know more. Is Python a good choice for this, and is there a good book or guide to learning how to use Python to replace shell scripting, AWK, sed and friends?</p>
| 207 | 2008-10-16T17:11:37Z | 3,851,454 | <p>While researching this topic, I found <a href="http://hg.mozilla.org/users/tmielczarek_mozilla.com/pyshell/file/tip/shell.py" rel="nofollow">this proof-of-concept code</a> (via a comment at <a href="http://jlebar.com/2010/2/1/Replacing_Bash.html" rel="nofollow">http://jlebar.com/2010/2/1/Replacing_Bash.html</a>) that lets you "write shell-like pipelines in Python using a terse syntax, and leveraging existing system tools where they make sense":</p>
<pre><code>for line in sh("cat /tmp/junk2") | cut(d=',',f=1) | 'sort' | uniq:
sys.stdout.write(line)
</code></pre>
| 2 | 2010-10-03T20:21:33Z | [
"python",
"bash",
"shell"
] |
Can I use Python as a Bash replacement? | 209,470 | <p>I currently do my textfile manipulation through a bunch of badly remembered AWK, sed, Bash and a tiny bit of Perl.</p>
<p>I've seen mentioned a few places that python is good for this kind of thing, I know a little and I would like to know more. Is Python a good choice for this, and is there a good book or guide to learning how to use Python to replace shell scripting, AWK, sed and friends?</p>
| 207 | 2008-10-16T17:11:37Z | 12,915,952 | <p>Yes, of course :)</p>
<p>Take a look at these libraries which help you <strong><em>Never write shell scripts again</em></strong> (Plumbum's motto).</p>
<ul>
<li><a href="http://plumbum.readthedocs.org/en/latest/">Plumbum</a> </li>
<li><a href="https://bitbucket.org/vinay.sajip/sarge/">Sarge</a></li>
<li><a href="http://amoffat.github.com/sh/">sh</a></li>
</ul>
<p>Also, if you want to replace awk, sed and grep with something Python based then I recommend <a href="http://pyvideo.org/video/686/the-pyed-piper-a-modern-python-alternative-to-aw">pyp</a> -</p>
<blockquote>
<p>"The Pyed Piper", or pyp, is a linux command line text manipulation
tool similar to awk or sed, but which uses standard python string and
list methods as well as custom functions evolved to generate fast
results in an intense production environment.</p>
</blockquote>
| 81 | 2012-10-16T13:37:46Z | [
"python",
"bash",
"shell"
] |
Can I use Python as a Bash replacement? | 209,470 | <p>I currently do my textfile manipulation through a bunch of badly remembered AWK, sed, Bash and a tiny bit of Perl.</p>
<p>I've seen mentioned a few places that python is good for this kind of thing, I know a little and I would like to know more. Is Python a good choice for this, and is there a good book or guide to learning how to use Python to replace shell scripting, AWK, sed and friends?</p>
| 207 | 2008-10-16T17:11:37Z | 15,712,610 | <p>I just discovered how to combine the best parts of bash and ipython. Up to now this seems more comfortable to me than using subprocess and so on. You can easily copy big parts of existing bash scripts and e.g. add error handling in the python way :)
And here is my result:</p>
<pre><code>#!/usr/bin/env ipython3
# *** How to have the most comfort scripting experience of your life ***
# ######################################################################
#
# ⦠by using ipython for scripting combined with subcommands from bash!
#
# 1. echo "#!/usr/bin/env ipython3" > scriptname.ipy # creates new ipy-file
#
# 2. chmod +x scriptname.ipy # make in executable
#
# 3. starting with line 2, write normal python or do some of
# the ! magic of ipython, so that you can use unix commands
# within python and even assign their output to a variable via
# var = !cmd1 | cmd2 | cmd3 # enjoy ;)
#
# 4. run via ./scriptname.ipy - if it fails with recognizing % and !
# but parses raw python fine, please check again for the .ipy suffix
# ugly example, please go and find more in the wild
files = !ls *.* | grep "y"
for file in files:
!echo $file | grep "p"
# sorry for this nonsense example ;)
</code></pre>
| 42 | 2013-03-29T22:49:18Z | [
"python",
"bash",
"shell"
] |
Can I use Python as a Bash replacement? | 209,470 | <p>I currently do my textfile manipulation through a bunch of badly remembered AWK, sed, Bash and a tiny bit of Perl.</p>
<p>I've seen mentioned a few places that python is good for this kind of thing, I know a little and I would like to know more. Is Python a good choice for this, and is there a good book or guide to learning how to use Python to replace shell scripting, AWK, sed and friends?</p>
| 207 | 2008-10-16T17:11:37Z | 16,726,383 | <p>One reason I love Python is that it is much better standardized than the POSIX tools. I have to double and triple check that each bit is compatible with other operating systems. A program written on a Linux system might not work the same on a BSD system of OSX. With Python, I just have to check that the target system has a sufficiently modern version of Python.</p>
<p>Even better, a program written in standard Python will even run on Windows!</p>
| 7 | 2013-05-24T01:23:24Z | [
"python",
"bash",
"shell"
] |
Can I use Python as a Bash replacement? | 209,470 | <p>I currently do my textfile manipulation through a bunch of badly remembered AWK, sed, Bash and a tiny bit of Perl.</p>
<p>I've seen mentioned a few places that python is good for this kind of thing, I know a little and I would like to know more. Is Python a good choice for this, and is there a good book or guide to learning how to use Python to replace shell scripting, AWK, sed and friends?</p>
| 207 | 2008-10-16T17:11:37Z | 20,313,297 | <p>I will give here my opinion based on experience:</p>
<p>For shell:</p>
<ul>
<li>shell can very easily spawn read-only code. Write it and when you come back to it, you will never figure out what you did again. It's very easy to accomplish this.</li>
<li>shell can do A LOT of text processing, splitting, etc in one line with pipes.</li>
<li>it is the best glue language when it comes to integrate the call of programs in different programming languages.</li>
</ul>
<p>For python:</p>
<ul>
<li>if you want portability to windows included, use python.</li>
<li>python can be better when you must manipulate just more than text, such as collections of numbers. For this, I recommend python.</li>
</ul>
<p>I usually choose bash for most of the things, but when I have something that must cross windows boundaries, I just use python.</p>
| 4 | 2013-12-01T14:40:14Z | [
"python",
"bash",
"shell"
] |
Can I use Python as a Bash replacement? | 209,470 | <p>I currently do my textfile manipulation through a bunch of badly remembered AWK, sed, Bash and a tiny bit of Perl.</p>
<p>I've seen mentioned a few places that python is good for this kind of thing, I know a little and I would like to know more. Is Python a good choice for this, and is there a good book or guide to learning how to use Python to replace shell scripting, AWK, sed and friends?</p>
| 207 | 2008-10-16T17:11:37Z | 25,820,270 | <p><a href="http://github.com/russell91/pythonpy" rel="nofollow">pythonpy</a> is a tool that provides easy access to many of the features from awk and sed, but using python syntax:</p>
<pre><code>$ echo me2 | py -x 're.sub("me", "you", x)'
you2
</code></pre>
| 2 | 2014-09-13T05:55:20Z | [
"python",
"bash",
"shell"
] |
Can I use Python as a Bash replacement? | 209,470 | <p>I currently do my textfile manipulation through a bunch of badly remembered AWK, sed, Bash and a tiny bit of Perl.</p>
<p>I've seen mentioned a few places that python is good for this kind of thing, I know a little and I would like to know more. Is Python a good choice for this, and is there a good book or guide to learning how to use Python to replace shell scripting, AWK, sed and friends?</p>
| 207 | 2008-10-16T17:11:37Z | 27,881,288 | <p>I have published a package on PyPI: <a href="https://pypi.python.org/pypi/ez" rel="nofollow">ez</a>.<br>
Use <code>pip install ez</code> to install it.</p>
<p>It has packed common commands in shell and nicely my lib uses basically the same syntax as shell. e.g., cp(source, destination) can handle both file and folder! (wrapper of shutil.copy shutil.copytree and it decides when to use which one). Even more nicely, it can support vectorization like R!</p>
<p>Another example: no os.walk, use fls(path, regex) to recursively find files and filter with regular expression and it returns a list of files with or without fullpath</p>
<p>Final example: you can combine them to write very simply scripts:<br>
<code>files = fls('.','py$'); cp(files, myDir)</code></p>
<p>Definitely check it out! It has cost me hundreds of hours to write/improve it!</p>
| 0 | 2015-01-10T21:14:27Z | [
"python",
"bash",
"shell"
] |
Can I use Python as a Bash replacement? | 209,470 | <p>I currently do my textfile manipulation through a bunch of badly remembered AWK, sed, Bash and a tiny bit of Perl.</p>
<p>I've seen mentioned a few places that python is good for this kind of thing, I know a little and I would like to know more. Is Python a good choice for this, and is there a good book or guide to learning how to use Python to replace shell scripting, AWK, sed and friends?</p>
| 207 | 2008-10-16T17:11:37Z | 30,617,053 | <p>As of 2015 and Python 3.4's release, there's now a reasonably complete user-interactive shell available at: <a href="http://xon.sh/">http://xon.sh/</a> or <a href="https://github.com/scopatz/xonsh/">https://github.com/scopatz/xonsh</a></p>
<p>The <a href="http://xon.sh/_static/xonsh-demo.webm">demonstration video</a> does not show pipes being used, but they ARE supported when in the default shell mode.</p>
<p>Xonsh ('conch') tries very hard to emulate bash, so things you've already gained muscle memory for, like </p>
<pre><code>env | uniq | sort -r | grep PATH
</code></pre>
<p>or </p>
<pre><code>my-web-server 2>&1 | my-log-sorter
</code></pre>
<p>will still work fine.</p>
<p>The tutorial is quite lengthy and seems to cover a significant amount of the functionality someone would generally expect at a ash or bash prompt:</p>
<ul>
<li>Compiles, Evaluates, & Executes!</li>
<li>Command History and Tab Completion</li>
<li>Help & Superhelp with ? & ??</li>
<li>Aliases & Customized Prompts</li>
<li>Executes Commands and/or *.xsh Scripts which can also be imported</li>
<li>Environment Variables including Lookup with ${}</li>
<li>Input/Output Redirection and Combining</li>
<li>Background Jobs & Job Control</li>
<li>Nesting Subprocesses, Pipes, and Coprocesses</li>
<li>Subprocess-mode when a command exists, Python-mode otherwise</li>
<li>Captured Subprocess with $(), Uncaptured Subprocess with $[], Python Evaluation with @()</li>
<li>Filename Globbing with * or Regular Expression Filename Globbing with Backticks</li>
</ul>
| 33 | 2015-06-03T10:08:43Z | [
"python",
"bash",
"shell"
] |
Can I use Python as a Bash replacement? | 209,470 | <p>I currently do my textfile manipulation through a bunch of badly remembered AWK, sed, Bash and a tiny bit of Perl.</p>
<p>I've seen mentioned a few places that python is good for this kind of thing, I know a little and I would like to know more. Is Python a good choice for this, and is there a good book or guide to learning how to use Python to replace shell scripting, AWK, sed and friends?</p>
| 207 | 2008-10-16T17:11:37Z | 35,443,255 | <p>You can use python instead of bash with the <a href="https://github.com/lamerman/shellpy" rel="nofollow">ShellPy</a> library. </p>
<p>Here is an example that downloads avatar of Python user from Github:</p>
<pre class="lang-python prettyprint-override"><code>import json
import os
import tempfile
# get the api answer with curl
answer = `curl https://api.github.com/users/python
# syntactic sugar for checking returncode of executed process for zero
if answer:
answer_json = json.loads(answer.stdout)
avatar_url = answer_json['avatar_url']
destination = os.path.join(tempfile.gettempdir(), 'python.png')
# execute curl once again, this time to get the image
result = `curl {avatar_url} > {destination}
if result:
# if there were no problems show the file
p`ls -l {destination}
else:
print('Failed to download avatar')
print('Avatar downloaded')
else:
print('Failed to access github api')
</code></pre>
<p>As you can see, all expressions inside of grave accent ( ` ) symbol are executed in shell. And in Python code, you can capture results of this execution and perform actions on it. For example:</p>
<pre class="lang-python prettyprint-override"><code>log = `git log --pretty=oneline --grep='Create'
</code></pre>
<p>This line will first execute <code>git log --pretty=oneline --grep='Create'</code> in shell and then assign the result to the log variable. The result has the following properties:</p>
<p><strong>stdout</strong> the whole text from stdout of the executed process</p>
<p><strong>stderr</strong> the whole text from stderr of the executed process</p>
<p><strong>returncode</strong> returncode of the execution</p>
<p>This is general overview of the library, more detailed description with examples can be found <a href="https://github.com/lamerman/shellpy" rel="nofollow">here</a>.</p>
| 1 | 2016-02-16T21:23:04Z | [
"python",
"bash",
"shell"
] |
Can I use Python as a Bash replacement? | 209,470 | <p>I currently do my textfile manipulation through a bunch of badly remembered AWK, sed, Bash and a tiny bit of Perl.</p>
<p>I've seen mentioned a few places that python is good for this kind of thing, I know a little and I would like to know more. Is Python a good choice for this, and is there a good book or guide to learning how to use Python to replace shell scripting, AWK, sed and friends?</p>
| 207 | 2008-10-16T17:11:37Z | 35,890,675 | <p>I wish there was something decent to replace bash scripting but really there isn't.</p>
<p>Python would seem like a great candidate until you're hit with the awkward standard library functions for file manipulation and spawning processes (os.popen3) and communicating with them.</p>
| 0 | 2016-03-09T11:43:18Z | [
"python",
"bash",
"shell"
] |
Howto do python command-line autocompletion but NOT only at the beginning of a string | 209,484 | <p>Python, through it's readline bindings allows for great command-line autocompletion (as described in <a href="http://stackoverflow.com/questions/187621/how-to-make-a-python-command-line-program-autocomplete-arbitrary-things-not-int">here</a>).</p>
<p>But, the completion only seems to work at the beginning of strings. If you want to match the middle or end of a string readline doesn't work.</p>
<p>I would like to autocomplete strings, in a command-line python program by matching what I type with any of the strings in a list of available strings. </p>
<ul>
<li>A good example of the type of autocompletion I would like to have is the type that happens in GMail when you type in the To field. If you type one of your contacts' last name, it will come up just as well as if you typed her first name. </li>
<li>Some use of the up and down arrows or some other method to select from the matched strings may be needed (and not needed in the case of readline) and that is fine in my case.</li>
<li>My particular use case is a command-line program that sends emails.</li>
<li>Specific code examples would be very helpful.</li>
</ul>
<p>Using terminal emulators like curses would be fine. It only has to run on linux, not Mac or Windows.</p>
<p>Here is an example:
Say I have the following three strings in a list </p>
<pre><code>['Paul Eden <[email protected]>',
'Eden Jones <[email protected]>',
'Somebody Else <[email protected]>']
</code></pre>
<p>I would like some code that will autocomplete the first two items in the list after I type 'Eden' and then allow me to pick one of them (all through the command-line using the keyboard).</p>
| 6 | 2008-10-16T17:16:34Z | 209,503 | <p>I'm not sure I understand the problem. You could use readline.clear_history and readline.add_history to set up the completable strings you want, then control-r to search backword in the history (just as if you were at a shell prompt). For example:</p>
<pre><code>#!/usr/bin/env python
import readline
readline.clear_history()
readline.add_history('foo')
readline.add_history('bar')
while 1:
print raw_input('> ')
</code></pre>
<p>Alternatively, you could write your own completer version and bind the appropriate key to it. This version uses caching in case your match list is huge:</p>
<pre><code>#!/usr/bin/env python
import readline
values = ['Paul Eden <[email protected]>',
'Eden Jones <[email protected]>',
'Somebody Else <[email protected]>']
completions = {}
def completer(text, state):
try:
matches = completions[text]
except KeyError:
matches = [value for value in values
if text.upper() in value.upper()]
completions[text] = matches
try:
return matches[state]
except IndexError:
return None
readline.set_completer(completer)
readline.parse_and_bind('tab: menu-complete')
while 1:
a = raw_input('> ')
print 'said:', a
</code></pre>
| 10 | 2008-10-16T17:23:34Z | [
"python",
"linux",
"unix",
"command-line",
"autocomplete"
] |
Convert hex string to int in Python | 209,513 | <p>How do I convert a hex string to an int in Python? </p>
<p>I may have it as "<code>0xffff</code>" or just "<code>ffff</code>".</p>
| 414 | 2008-10-16T17:28:03Z | 209,529 | <p><code>int(hexString, 16)</code> does the trick, and works with and without the 0x prefix:</p>
<pre><code>>>> int("a", 16)
10
>>> int("0xa",16)
10
</code></pre>
| 99 | 2008-10-16T17:32:10Z | [
"python",
"string",
"hex"
] |
Convert hex string to int in Python | 209,513 | <p>How do I convert a hex string to an int in Python? </p>
<p>I may have it as "<code>0xffff</code>" or just "<code>ffff</code>".</p>
| 414 | 2008-10-16T17:28:03Z | 209,530 | <p>For any given string s:</p>
<pre><code>int(s, 16)
</code></pre>
| 32 | 2008-10-16T17:32:32Z | [
"python",
"string",
"hex"
] |
Convert hex string to int in Python | 209,513 | <p>How do I convert a hex string to an int in Python? </p>
<p>I may have it as "<code>0xffff</code>" or just "<code>ffff</code>".</p>
| 414 | 2008-10-16T17:28:03Z | 209,550 | <p><strong>Without</strong> the 0x prefix, you need to specify the base explicitly, otherwise there's no way to tell:</p>
<pre><code>x = int("deadbeef", 16)
</code></pre>
<p><strong>With</strong> the 0x prefix, Python can distinguish hex and decimal automatically.</p>
<pre><code>>>> print int("0xdeadbeef", 0)
3735928559
>>> print int("10", 0)
10
</code></pre>
<p>(You <em>must</em> specify <code>0</code> as the base in order to invoke this prefix-guessing behavior; omitting the second parameter means to assume base-10. See the comments for more details.)</p>
| 594 | 2008-10-16T17:37:52Z | [
"python",
"string",
"hex"
] |
Convert hex string to int in Python | 209,513 | <p>How do I convert a hex string to an int in Python? </p>
<p>I may have it as "<code>0xffff</code>" or just "<code>ffff</code>".</p>
| 414 | 2008-10-16T17:28:03Z | 5,313,035 | <p>To convert a DWORD from hex to a signed integer , implement two's complement like this:</p>
<pre><code>~ (0xffffffff - int('0xdeadbeef', 16)) + 1
</code></pre>
| -3 | 2011-03-15T14:14:09Z | [
"python",
"string",
"hex"
] |
Convert hex string to int in Python | 209,513 | <p>How do I convert a hex string to an int in Python? </p>
<p>I may have it as "<code>0xffff</code>" or just "<code>ffff</code>".</p>
| 414 | 2008-10-16T17:28:03Z | 11,275,700 | <p>Adding to Dan's answer above: if you supply the int() function with a hex string, you will have to specify the base as 16 or it will not think you gave it a valid value. Specifying base 16 is unnecessary for hex numbers not contained in strings.</p>
<pre><code>print int(0xdeadbeef) # valid
myHex = "0xdeadbeef"
print int(myHex) # invalid, raises ValueError
print int(myHex , 16) # valid
</code></pre>
| 9 | 2012-06-30T16:25:01Z | [
"python",
"string",
"hex"
] |
Convert hex string to int in Python | 209,513 | <p>How do I convert a hex string to an int in Python? </p>
<p>I may have it as "<code>0xffff</code>" or just "<code>ffff</code>".</p>
| 414 | 2008-10-16T17:28:03Z | 12,049,551 | <p>with '0x' prefix, you might also use eval function</p>
<p>For example</p>
<pre><code>>>a='0xff'
>>eval(a)
255
</code></pre>
| -2 | 2012-08-21T06:39:36Z | [
"python",
"string",
"hex"
] |
Convert hex string to int in Python | 209,513 | <p>How do I convert a hex string to an int in Python? </p>
<p>I may have it as "<code>0xffff</code>" or just "<code>ffff</code>".</p>
| 414 | 2008-10-16T17:28:03Z | 17,250,080 | <p>The formatter option '%x' % seems to work in assignment statements as well for me. (Assuming Python 3.0 and later)</p>
<p><strong>Example</strong> </p>
<pre><code>a = int('0x100', 16)
print(a) #256
print('%x' % a) #100
b = a
print(b) #256
c = '%x' % a
print(c) #100
</code></pre>
| 1 | 2013-06-22T11:10:32Z | [
"python",
"string",
"hex"
] |
Convert hex string to int in Python | 209,513 | <p>How do I convert a hex string to an int in Python? </p>
<p>I may have it as "<code>0xffff</code>" or just "<code>ffff</code>".</p>
| 414 | 2008-10-16T17:28:03Z | 21,187,085 | <p>The worst way:</p>
<pre><code>>>> def hex_to_int(x):
return eval("0x" + x)
>>> hex_to_int("c0ffee")
12648430
</code></pre>
<h1><em>Please don't do this!</em></h1>
<p><a href="http://stackoverflow.com/questions/1832940/is-using-eval-in-python-a-bad-practice">Is Using eval In Python A Bad Practice?</a></p>
| 4 | 2014-01-17T13:20:15Z | [
"python",
"string",
"hex"
] |
Convert hex string to int in Python | 209,513 | <p>How do I convert a hex string to an int in Python? </p>
<p>I may have it as "<code>0xffff</code>" or just "<code>ffff</code>".</p>
| 414 | 2008-10-16T17:28:03Z | 30,270,489 | <p>In Python 2.7, <code>int('deadbeef',10)</code> doesn't seem to work. </p>
<p>The following works for me:</p>
<pre><code>>>a = int('deadbeef',16)
>>float(a)
3735928559.0
</code></pre>
| 2 | 2015-05-16T00:13:25Z | [
"python",
"string",
"hex"
] |
Convert hex string to int in Python | 209,513 | <p>How do I convert a hex string to an int in Python? </p>
<p>I may have it as "<code>0xffff</code>" or just "<code>ffff</code>".</p>
| 414 | 2008-10-16T17:28:03Z | 37,221,971 | <blockquote>
<h1>Convert hex string to int in Python</h1>
<p>I may have it as <code>"0xffff"</code> or just <code>"ffff"</code>.</p>
</blockquote>
<p>To convert a string to an int, pass the string to <code>int</code> along with the base you are converting from. </p>
<p>Both strings will suffice for conversion in this way:</p>
<pre><code>>>> string_1 = "0xffff"
>>> string_2 = "ffff"
>>> int(string_1, 16)
65535
>>> int(string_2, 16)
65535
</code></pre>
<h2>Letting <code>int</code> infer</h2>
<p>If you pass 0 as the base, <code>int</code> will infer the base from the prefix in the string. </p>
<pre><code>>>> int(string_1, 0)
65535
</code></pre>
<p>Without the hexadecimal prefix, <code>0x</code>, <code>int</code> does not have enough information with which to guess:</p>
<pre><code>>>> int(string_2, 0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 0: 'ffff'
</code></pre>
<h2>literals:</h2>
<p>If you're typing into source code or an interpreter, Python will make the conversion for you:</p>
<pre><code>>>> integer = 0xffff
>>> integer
65535
</code></pre>
<p>This won't work with <code>ffff</code> because Python will think you're trying to write a legitimate Python name instead:</p>
<pre><code>>>> integer = ffff
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'ffff' is not defined
</code></pre>
<p>Python numbers start with a numeric character, while Python names cannot start with a numeric character.</p>
| 2 | 2016-05-14T02:50:29Z | [
"python",
"string",
"hex"
] |
Map two lists into a dictionary in Python | 209,840 | <p>Imagine that you have:</p>
<pre><code>keys = ('name', 'age', 'food')
values = ('Monty', 42, 'spam')
</code></pre>
<p>What is the simplest way to produce the following dictionary ?</p>
<pre><code>dict = {'name' : 'Monty', 'age' : 42, 'food' : 'spam'}
</code></pre>
<p>This code works, but I'm not really proud of it :</p>
<pre><code>dict = {}
junk = map(lambda k, v: dict.update({k: v}), keys, values)
</code></pre>
| 435 | 2008-10-16T19:05:47Z | 209,854 | <p>Like this:</p>
<pre><code>>>> keys = ['a', 'b', 'c']
>>> values = [1, 2, 3]
>>> dictionary = dict(zip(keys, values))
>>> print dictionary
{'a': 1, 'b': 2, 'c': 3}
</code></pre>
<p>Voila :-) The pairwise dict constructor and zip function are awesomely useful: <a href="https://docs.python.org/2/library/functions.html#func-dict">https://docs.python.org/2/library/functions.html#func-dict</a></p>
| 770 | 2008-10-16T19:09:05Z | [
"python",
"dictionary"
] |
Map two lists into a dictionary in Python | 209,840 | <p>Imagine that you have:</p>
<pre><code>keys = ('name', 'age', 'food')
values = ('Monty', 42, 'spam')
</code></pre>
<p>What is the simplest way to produce the following dictionary ?</p>
<pre><code>dict = {'name' : 'Monty', 'age' : 42, 'food' : 'spam'}
</code></pre>
<p>This code works, but I'm not really proud of it :</p>
<pre><code>dict = {}
junk = map(lambda k, v: dict.update({k: v}), keys, values)
</code></pre>
| 435 | 2008-10-16T19:05:47Z | 209,855 | <pre><code>>>> keys = ('name', 'age', 'food')
>>> values = ('Monty', 42, 'spam')
>>> dict(zip(keys, values))
{'food': 'spam', 'age': 42, 'name': 'Monty'}
</code></pre>
| 25 | 2008-10-16T19:09:18Z | [
"python",
"dictionary"
] |
Map two lists into a dictionary in Python | 209,840 | <p>Imagine that you have:</p>
<pre><code>keys = ('name', 'age', 'food')
values = ('Monty', 42, 'spam')
</code></pre>
<p>What is the simplest way to produce the following dictionary ?</p>
<pre><code>dict = {'name' : 'Monty', 'age' : 42, 'food' : 'spam'}
</code></pre>
<p>This code works, but I'm not really proud of it :</p>
<pre><code>dict = {}
junk = map(lambda k, v: dict.update({k: v}), keys, values)
</code></pre>
| 435 | 2008-10-16T19:05:47Z | 209,880 | <p>Try this:</p>
<pre><code>>>> import itertools
>>> keys = ('name', 'age', 'food')
>>> values = ('Monty', 42, 'spam')
>>> adict = dict(itertools.izip(keys,values))
>>> adict
{'food': 'spam', 'age': 42, 'name': 'Monty'}
</code></pre>
<p>It was the simplest solution I could come up with.</p>
<p>PS It's also more economical in memory consumption compared to zip.</p>
| 92 | 2008-10-16T19:16:02Z | [
"python",
"dictionary"
] |
Map two lists into a dictionary in Python | 209,840 | <p>Imagine that you have:</p>
<pre><code>keys = ('name', 'age', 'food')
values = ('Monty', 42, 'spam')
</code></pre>
<p>What is the simplest way to produce the following dictionary ?</p>
<pre><code>dict = {'name' : 'Monty', 'age' : 42, 'food' : 'spam'}
</code></pre>
<p>This code works, but I'm not really proud of it :</p>
<pre><code>dict = {}
junk = map(lambda k, v: dict.update({k: v}), keys, values)
</code></pre>
| 435 | 2008-10-16T19:05:47Z | 210,234 | <p>If you need to transform keys or values before creating a dictionary then a <a href="http://docs.python.org/ref/genexpr.html">generator expression</a> could be used. Example:</p>
<pre><code>>>> adict = dict((str(k), v) for k, v in zip(['a', 1, 'b'], [2, 'c', 3]))
</code></pre>
<p>Take a look <a href="http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html">Code Like a Pythonista: Idiomatic Python</a>.</p>
| 11 | 2008-10-16T20:45:04Z | [
"python",
"dictionary"
] |
Map two lists into a dictionary in Python | 209,840 | <p>Imagine that you have:</p>
<pre><code>keys = ('name', 'age', 'food')
values = ('Monty', 42, 'spam')
</code></pre>
<p>What is the simplest way to produce the following dictionary ?</p>
<pre><code>dict = {'name' : 'Monty', 'age' : 42, 'food' : 'spam'}
</code></pre>
<p>This code works, but I'm not really proud of it :</p>
<pre><code>dict = {}
junk = map(lambda k, v: dict.update({k: v}), keys, values)
</code></pre>
| 435 | 2008-10-16T19:05:47Z | 10,971,932 | <p>You can also use dictionary comprehensions in Python ⥠2.7:</p>
<pre><code>>>> keys = ('name', 'age', 'food')
>>> values = ('Monty', 42, 'spam')
>>> {k: v for k, v in zip(keys, values)}
{'food': 'spam', 'age': 42, 'name': 'Monty'}
</code></pre>
| 23 | 2012-06-10T20:03:34Z | [
"python",
"dictionary"
] |
Map two lists into a dictionary in Python | 209,840 | <p>Imagine that you have:</p>
<pre><code>keys = ('name', 'age', 'food')
values = ('Monty', 42, 'spam')
</code></pre>
<p>What is the simplest way to produce the following dictionary ?</p>
<pre><code>dict = {'name' : 'Monty', 'age' : 42, 'food' : 'spam'}
</code></pre>
<p>This code works, but I'm not really proud of it :</p>
<pre><code>dict = {}
junk = map(lambda k, v: dict.update({k: v}), keys, values)
</code></pre>
| 435 | 2008-10-16T19:05:47Z | 15,709,950 | <p>For those who need simple code and arenât familiar with <code>zip</code>:</p>
<pre><code>List1 = ['This', 'is', 'a', 'list']
List2 = ['Put', 'this', 'into', 'dictionary']
</code></pre>
<p>This can be done by one line of code:</p>
<pre><code>d = {List1[n]: List2[n] for n in range(len(List1))}
</code></pre>
| 5 | 2013-03-29T19:13:45Z | [
"python",
"dictionary"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.