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 |
---|---|---|---|---|---|---|---|---|---|
How would I package and sell a Django app? | 164,901 | <p>Currently I am hosting a Django app I developed myself for my clients, but I am now starting to look at selling it to people for them to host themselves.</p>
<p>My question is this: How can I package up and sell a Django app, while protecting its code from pirating or theft? Distributing a bunch of .py files doesn't sound like a good idea as the people I sell it to too could just make copies of them and pass them on.</p>
<p>I think for the purpose of this problem it would be safe to assume that everyone who buys this would be running the same (LAMP) setup.</p>
| 30 | 2008-10-02T22:27:56Z | 164,959 | <p>You could package the whole thing up as an Amazon Machine Instance (AMI), and then have them run your app on <a href="http://aws.amazon.com/ec2/">Amazon EC2</a>. The nice thing about this solution is that Amazon will <a href="http://docs.amazonwebservices.com/AWSEC2/latest/DeveloperGuide/index.html?paidamis-intro.html">take care of billing for you</a>, and since you're distributing the entire machine image, you can be certain that all your clients are using the same LAMP stack. The AMI is an encrypted machine image that is configured however you want it.</p>
<p>You can have Amazon bill the client with a one-time fee, usage-based fee, or monthly fee.</p>
<p>Of course, this solution requires that your clients host their app at Amazon, and pay the appropriate fees.</p>
| 9 | 2008-10-02T22:54:43Z | [
"python",
"django",
"distribution",
"piracy-prevention"
] |
How would I package and sell a Django app? | 164,901 | <p>Currently I am hosting a Django app I developed myself for my clients, but I am now starting to look at selling it to people for them to host themselves.</p>
<p>My question is this: How can I package up and sell a Django app, while protecting its code from pirating or theft? Distributing a bunch of .py files doesn't sound like a good idea as the people I sell it to too could just make copies of them and pass them on.</p>
<p>I think for the purpose of this problem it would be safe to assume that everyone who buys this would be running the same (LAMP) setup.</p>
| 30 | 2008-10-02T22:27:56Z | 164,987 | <p>Don't try and obfuscate or encrypt the code - it will never work.</p>
<p>I would suggest selling the Django application "as a service" - either host it for them, or sell them the code <em>and support</em>. Write up a contract that forbids them from redistributing it.</p>
<p>That said, if you were determined to obfuscate the code in some way - you can distribute python applications entirely as .pyc (Python compiled byte-code).. It's how Py2App works.</p>
<p>It will still be re-distributable, <em>but</em> it will be very difficult to edit the files - so you could add some basic licensing stuff, and not have it foiled by a few <code>#</code>s..</p>
<p>As I said, I don't think you'll succeed in anti-piracy via encryption or obfuscation etc.. Depending on your clients, a simple contract, and maybe some really basic checks will go a long much further than some complicated decryption system (And make the experience of using your application <em>better</em>, instead of <em>hopefully not any worse</em>)</p>
| 48 | 2008-10-02T23:10:21Z | [
"python",
"django",
"distribution",
"piracy-prevention"
] |
How would I package and sell a Django app? | 164,901 | <p>Currently I am hosting a Django app I developed myself for my clients, but I am now starting to look at selling it to people for them to host themselves.</p>
<p>My question is this: How can I package up and sell a Django app, while protecting its code from pirating or theft? Distributing a bunch of .py files doesn't sound like a good idea as the people I sell it to too could just make copies of them and pass them on.</p>
<p>I think for the purpose of this problem it would be safe to assume that everyone who buys this would be running the same (LAMP) setup.</p>
| 30 | 2008-10-02T22:27:56Z | 167,240 | <p>You'll never be able to keep the source code from people who really want it. It's best to come to grips with this fact now, and save yourself the headache later.</p>
| 7 | 2008-10-03T14:48:12Z | [
"python",
"django",
"distribution",
"piracy-prevention"
] |
How would I package and sell a Django app? | 164,901 | <p>Currently I am hosting a Django app I developed myself for my clients, but I am now starting to look at selling it to people for them to host themselves.</p>
<p>My question is this: How can I package up and sell a Django app, while protecting its code from pirating or theft? Distributing a bunch of .py files doesn't sound like a good idea as the people I sell it to too could just make copies of them and pass them on.</p>
<p>I think for the purpose of this problem it would be safe to assume that everyone who buys this would be running the same (LAMP) setup.</p>
| 30 | 2008-10-02T22:27:56Z | 395,813 | <p>One thing you might want to consider is what FogBugz does. Simply include a small binary (perhaps a C program) that is compiled for the target platforms and contains the code to validate the license. </p>
<p>This way you can keep the honest people honest with minimal headache on your part.</p>
| 3 | 2008-12-28T04:19:39Z | [
"python",
"django",
"distribution",
"piracy-prevention"
] |
How would I package and sell a Django app? | 164,901 | <p>Currently I am hosting a Django app I developed myself for my clients, but I am now starting to look at selling it to people for them to host themselves.</p>
<p>My question is this: How can I package up and sell a Django app, while protecting its code from pirating or theft? Distributing a bunch of .py files doesn't sound like a good idea as the people I sell it to too could just make copies of them and pass them on.</p>
<p>I think for the purpose of this problem it would be safe to assume that everyone who buys this would be running the same (LAMP) setup.</p>
| 30 | 2008-10-02T22:27:56Z | 445,887 | <p>"Encrypting" Python source code (or bytecode, or really bytecode for any language that uses it -- not just Python) is like those little JavaScript things some people put on web pages to try to disable the right-hand mouse button, declaring "now you can't steal my images!"</p>
<p>The workarounds are trivial, and will not stop a determined person.</p>
<p>If you're really serious about selling a piece of Python software, you need to act serious. Pay an attorney to draw up license/contract terms, have people agree to them at the time of purchase, and then just let them have the actual software. This means you'll have to haul people into court if they violate the license/contract terms, but you'd have to do that no matter what (e.g., if somebody breaks your "encryption" and starts distributing your software), and having the actual proper form of legal words already set down on paper, with their signature, will be far better for your business in the long term.</p>
<p>If you're really <em>that</em> paranoid about people "stealing" your software, though, just stick with a hosted model and don't give them access to the server. Plenty of successful businesses are based around that model.</p>
| 10 | 2009-01-15T07:01:38Z | [
"python",
"django",
"distribution",
"piracy-prevention"
] |
How would I package and sell a Django app? | 164,901 | <p>Currently I am hosting a Django app I developed myself for my clients, but I am now starting to look at selling it to people for them to host themselves.</p>
<p>My question is this: How can I package up and sell a Django app, while protecting its code from pirating or theft? Distributing a bunch of .py files doesn't sound like a good idea as the people I sell it to too could just make copies of them and pass them on.</p>
<p>I think for the purpose of this problem it would be safe to assume that everyone who buys this would be running the same (LAMP) setup.</p>
| 30 | 2008-10-02T22:27:56Z | 5,915,669 | <p>May I speak frankly, as a friend? Unless your app is Really Amazing, you may not get many buyers. Why waste the time on lawyers, obfuscation, licensing and whatnot? You stand to gain a better reputation by open-sourcing your code...and maintaining it.</p>
<p>Django comes from the open-source end of the spectrum from licensing (and obfuscating). Granted, the MIT license is more common than the GPL; still they are both very far removed from anything like Microsoft's EULA. A lot of Djangophiles will balk at closed source code, simply because that's what Microsoft does.</p>
<p>Also, people will trust your code more, since they will be able to read it and verify that it contains no malicious code. Remember, "obfuscating" means "hiding;" and who will really know exactly what you've hidden?</p>
<p>Granted, there's no easy way to monetize open-sourced code. But you could offer your services or even post a campaign on Pledgie.com, for those who are thankful for all your great work.</p>
| 2 | 2011-05-06T18:40:40Z | [
"python",
"django",
"distribution",
"piracy-prevention"
] |
Detecting Mouse clicks in windows using python | 165,495 | <p>How can I detect mouse clicks regardless of the window the mouse is in?</p>
<p>Perferabliy in python, but if someone can explain it in any langauge I might be able to figure it out.</p>
<p>I found this on microsoft's site:
<a href="http://msdn.microsoft.com/en-us/library/ms645533(VS.85).aspx">http://msdn.microsoft.com/en-us/library/ms645533(VS.85).aspx</a></p>
<p>But I don't see how I can detect or pick up the notifications listed.</p>
<p>Tried using pygame's pygame.mouse.get_pos() function as follows:</p>
<pre><code>import pygame
pygame.init()
while True:
print pygame.mouse.get_pos()
</code></pre>
<p>This just returns 0,0.
I'm not familiar with pygame, is something missing?</p>
<p>In anycase I'd prefer a method without the need to install a 3rd party module.
(other than pywin32 <a href="http://sourceforge.net/projects/pywin32/">http://sourceforge.net/projects/pywin32/</a> )</p>
| 13 | 2008-10-03T02:51:44Z | 166,054 | <p>The windows way of doing it is to handle the <code>WM_LBUTTONDBLCLK</code> message. </p>
<p>For this to be sent, your window class needs to be created with the <code>CS_DBLCLKS</code> class style.</p>
<p>I'm afraid I don't know how to apply this in Python, but hopefully it might give you some hints.</p>
| 2 | 2008-10-03T09:13:27Z | [
"python",
"windows",
"mouse"
] |
Detecting Mouse clicks in windows using python | 165,495 | <p>How can I detect mouse clicks regardless of the window the mouse is in?</p>
<p>Perferabliy in python, but if someone can explain it in any langauge I might be able to figure it out.</p>
<p>I found this on microsoft's site:
<a href="http://msdn.microsoft.com/en-us/library/ms645533(VS.85).aspx">http://msdn.microsoft.com/en-us/library/ms645533(VS.85).aspx</a></p>
<p>But I don't see how I can detect or pick up the notifications listed.</p>
<p>Tried using pygame's pygame.mouse.get_pos() function as follows:</p>
<pre><code>import pygame
pygame.init()
while True:
print pygame.mouse.get_pos()
</code></pre>
<p>This just returns 0,0.
I'm not familiar with pygame, is something missing?</p>
<p>In anycase I'd prefer a method without the need to install a 3rd party module.
(other than pywin32 <a href="http://sourceforge.net/projects/pywin32/">http://sourceforge.net/projects/pywin32/</a> )</p>
| 13 | 2008-10-03T02:51:44Z | 166,144 | <p>Windows MFC, including GUI programming, is accessible with python using the <a href="http://sourceforge.net/projects/pywin32/" rel="nofollow">Python for Windows extensions</a> by Mark Hammond. <a href="http://www.onlamp.com/lpt/a/217" rel="nofollow">An O'Reilly Book Excerpt</a> from Hammond's and Robinson's <a href="http://oreilly.com/catalog/9781565926219/" rel="nofollow">book</a> shows how to hook mouse messages, .e.g:</p>
<pre><code>self.HookMessage(self.OnMouseMove,win32con.WM_MOUSEMOVE)
</code></pre>
<p>Raw MFC is not easy or obvious, but searching the web for python examples may yield some usable examples.</p>
| 3 | 2008-10-03T09:56:35Z | [
"python",
"windows",
"mouse"
] |
Detecting Mouse clicks in windows using python | 165,495 | <p>How can I detect mouse clicks regardless of the window the mouse is in?</p>
<p>Perferabliy in python, but if someone can explain it in any langauge I might be able to figure it out.</p>
<p>I found this on microsoft's site:
<a href="http://msdn.microsoft.com/en-us/library/ms645533(VS.85).aspx">http://msdn.microsoft.com/en-us/library/ms645533(VS.85).aspx</a></p>
<p>But I don't see how I can detect or pick up the notifications listed.</p>
<p>Tried using pygame's pygame.mouse.get_pos() function as follows:</p>
<pre><code>import pygame
pygame.init()
while True:
print pygame.mouse.get_pos()
</code></pre>
<p>This just returns 0,0.
I'm not familiar with pygame, is something missing?</p>
<p>In anycase I'd prefer a method without the need to install a 3rd party module.
(other than pywin32 <a href="http://sourceforge.net/projects/pywin32/">http://sourceforge.net/projects/pywin32/</a> )</p>
| 13 | 2008-10-03T02:51:44Z | 168,996 | <p>The only way to detect mouse events outside your program is to install a Windows hook using <a href="http://msdn.microsoft.com/en-us/library/ms644990(VS.85).aspx">SetWindowsHookEx</a>. The <a href="http://www.cs.unc.edu/Research/assist/developer.shtml">pyHook</a> module encapsulates the nitty-gritty details. Here's a sample that will print the location of every mouse click:</p>
<pre><code>import pyHook
import pythoncom
def onclick(event):
print event.Position
return True
hm = pyHook.HookManager()
hm.SubscribeMouseAllButtonsDown(onclick)
hm.HookMouse()
pythoncom.PumpMessages()
hm.UnhookMouse()
</code></pre>
<p>You can check the <strong>example.py</strong> script that is installed with the module for more info about the <strong>event</strong> parameter.</p>
<p>pyHook might be tricky to use in a pure Python script, because it requires an active message pump. From the <a href="http://mindtrove.info/articles/monitoring-global-input-with-pyhook/">tutorial</a>:</p>
<blockquote>
<p>Any application that wishes to receive
notifications of global input events
must have a Windows message pump. The
easiest way to get one of these is to
use the PumpMessages method in the
Win32 Extensions package for Python.
[...] When run, this program just sits
idle and waits for Windows events. If
you are using a GUI toolkit (e.g.
wxPython), this loop is unnecessary
since the toolkit provides its own.</p>
</blockquote>
| 23 | 2008-10-03T21:38:15Z | [
"python",
"windows",
"mouse"
] |
Python object attributes - methodology for access | 165,883 | <p>Suppose I have a class with some attributes. How is it best (in the Pythonic-OOP) sense to access these attributes ? Just like <code>obj.attr</code> ? Or perhaps write get accessors ?
What are the accepted naming styles for such things ?</p>
<p><strong>Edit:</strong>
Can you elaborate on the best-practices of naming attributes with a single or double leading underscore ? I see in most modules that a single underscore is used.</p>
<p><hr /></p>
<p>If this question has already been asked (and I have a hunch it has, though searching didn't bring results), please point to it - and I will close this one.</p>
| 22 | 2008-10-03T06:18:37Z | 165,892 | <p>I think most just access them directly, no need for get/set methods.</p>
<pre><code>>>> class myclass:
... x = 'hello'
...
>>>
>>> class_inst = myclass()
>>> class_inst.x
'hello'
>>> class_inst.x = 'world'
>>> class_inst.x
'world'
</code></pre>
<p>BTW, you can use the dir() function to see what attributes/methods are attached to your instance:</p>
<pre><code>>>> dir(class_inst)
['__doc__', '__module__', 'x']
</code></pre>
<p>Two leading underbars, "__" are used to make a attribute or function private.
For other conventions refer to PEP 08:
<a href="http://www.python.org/dev/peps/pep-0008/" rel="nofollow">http://www.python.org/dev/peps/pep-0008/</a></p>
| 3 | 2008-10-03T06:24:01Z | [
"python",
"oop",
"object",
"attributes"
] |
Python object attributes - methodology for access | 165,883 | <p>Suppose I have a class with some attributes. How is it best (in the Pythonic-OOP) sense to access these attributes ? Just like <code>obj.attr</code> ? Or perhaps write get accessors ?
What are the accepted naming styles for such things ?</p>
<p><strong>Edit:</strong>
Can you elaborate on the best-practices of naming attributes with a single or double leading underscore ? I see in most modules that a single underscore is used.</p>
<p><hr /></p>
<p>If this question has already been asked (and I have a hunch it has, though searching didn't bring results), please point to it - and I will close this one.</p>
| 22 | 2008-10-03T06:18:37Z | 165,896 | <p>Python does not need to define accessors right from the beginning, since converting attributes into properties is quick and painless. See the following for a vivid demonstration:</p>
<p><a href="http://www.archive.org/details/SeanKellyRecoveryfromAddiction" rel="nofollow">Recovery from Addiction</a></p>
| 0 | 2008-10-03T06:26:39Z | [
"python",
"oop",
"object",
"attributes"
] |
Python object attributes - methodology for access | 165,883 | <p>Suppose I have a class with some attributes. How is it best (in the Pythonic-OOP) sense to access these attributes ? Just like <code>obj.attr</code> ? Or perhaps write get accessors ?
What are the accepted naming styles for such things ?</p>
<p><strong>Edit:</strong>
Can you elaborate on the best-practices of naming attributes with a single or double leading underscore ? I see in most modules that a single underscore is used.</p>
<p><hr /></p>
<p>If this question has already been asked (and I have a hunch it has, though searching didn't bring results), please point to it - and I will close this one.</p>
| 22 | 2008-10-03T06:18:37Z | 165,901 | <p>Some people use getters and setters. Depending on which coding style you use you can name them getSpam and seteggs. But you can also make you attributes readonly or assign only. That's a bit awkward to do. One way is overriding the </p>
<pre><code>> __getattr__
</code></pre>
<p>and </p>
<pre><code>> __setattr__
</code></pre>
<p>methods.</p>
<h2>Edit:</h2>
<p>While my answer is still true, it's not right, as I came to realize. There are better ways to make accessors in python and are not very awkward.</p>
| -2 | 2008-10-03T06:29:22Z | [
"python",
"oop",
"object",
"attributes"
] |
Python object attributes - methodology for access | 165,883 | <p>Suppose I have a class with some attributes. How is it best (in the Pythonic-OOP) sense to access these attributes ? Just like <code>obj.attr</code> ? Or perhaps write get accessors ?
What are the accepted naming styles for such things ?</p>
<p><strong>Edit:</strong>
Can you elaborate on the best-practices of naming attributes with a single or double leading underscore ? I see in most modules that a single underscore is used.</p>
<p><hr /></p>
<p>If this question has already been asked (and I have a hunch it has, though searching didn't bring results), please point to it - and I will close this one.</p>
| 22 | 2008-10-03T06:18:37Z | 165,911 | <p>The generally accepted way of doing things is just using simple attributes, like so</p>
<pre><code>>>> class MyClass:
... myAttribute = 0
...
>>> c = MyClass()
>>> c.myAttribute
0
>>> c.myAttribute = 1
>>> c.myAttribute
1
</code></pre>
<p>If you do find yourself needing to be able to write getters and setters, then what you want to look for is "python class properties" and <a href="http://tomayko.com/writings/getters-setters-fuxors">Ryan Tomayko's article on
Getters/Setters/Fuxors</a> is a great place to start (albeit a little long)</p>
| 20 | 2008-10-03T06:35:37Z | [
"python",
"oop",
"object",
"attributes"
] |
Python object attributes - methodology for access | 165,883 | <p>Suppose I have a class with some attributes. How is it best (in the Pythonic-OOP) sense to access these attributes ? Just like <code>obj.attr</code> ? Or perhaps write get accessors ?
What are the accepted naming styles for such things ?</p>
<p><strong>Edit:</strong>
Can you elaborate on the best-practices of naming attributes with a single or double leading underscore ? I see in most modules that a single underscore is used.</p>
<p><hr /></p>
<p>If this question has already been asked (and I have a hunch it has, though searching didn't bring results), please point to it - and I will close this one.</p>
| 22 | 2008-10-03T06:18:37Z | 165,925 | <p>There is no real point of doing getter/setters in python, you can't protect stuff anyway and if you need to execute some extra code when getting/setting the property look at the property() builtin (python -c 'help(property)')</p>
| 0 | 2008-10-03T06:43:09Z | [
"python",
"oop",
"object",
"attributes"
] |
Python object attributes - methodology for access | 165,883 | <p>Suppose I have a class with some attributes. How is it best (in the Pythonic-OOP) sense to access these attributes ? Just like <code>obj.attr</code> ? Or perhaps write get accessors ?
What are the accepted naming styles for such things ?</p>
<p><strong>Edit:</strong>
Can you elaborate on the best-practices of naming attributes with a single or double leading underscore ? I see in most modules that a single underscore is used.</p>
<p><hr /></p>
<p>If this question has already been asked (and I have a hunch it has, though searching didn't bring results), please point to it - and I will close this one.</p>
| 22 | 2008-10-03T06:18:37Z | 166,073 | <blockquote>
<p>Edit: Can you elaborate on the best-practices of naming attributes with a single or double leading underscore ? I see in most modules that a single underscore is used.</p>
</blockquote>
<p>Single underscore doesn't mean anything special to python, it is just best practice, to tell "hey you probably don't want to access this unless you know what you are doing". Double underscore however makes python mangle the name internally making it accessible only from the class where it is defined.</p>
<p>Double leading AND trailing underscore denotes a special function, such as <code>__add__</code> which is called when using the + operator.</p>
<p>Read more in <a href="http://www.python.org/dev/peps/pep-0008/" rel="nofollow">PEP 8</a>, especially the "Naming Conventions" section.</p>
| 7 | 2008-10-03T09:23:40Z | [
"python",
"oop",
"object",
"attributes"
] |
Python object attributes - methodology for access | 165,883 | <p>Suppose I have a class with some attributes. How is it best (in the Pythonic-OOP) sense to access these attributes ? Just like <code>obj.attr</code> ? Or perhaps write get accessors ?
What are the accepted naming styles for such things ?</p>
<p><strong>Edit:</strong>
Can you elaborate on the best-practices of naming attributes with a single or double leading underscore ? I see in most modules that a single underscore is used.</p>
<p><hr /></p>
<p>If this question has already been asked (and I have a hunch it has, though searching didn't bring results), please point to it - and I will close this one.</p>
| 22 | 2008-10-03T06:18:37Z | 166,098 | <p>With regards to the single and double-leading underscores: both indicate the same concept of 'privateness'. That is to say, people will know the attribute (be it a method or a 'normal' data attribute or anything else) is not part of the public API of the object. People will know that to touch it directly is to invite disaster.</p>
<p>On top of that, the double-leading underscore attributes (but not the single-leading underscore attributes) are <em>name-mangled</em> to make accessing them <em>by accident</em> from subclasses or anywhere else outside the current class less likely. You can still access them, but not as trivially. For example:</p>
<pre><code>>>> class ClassA:
... def __init__(self):
... self._single = "Single"
... self.__double = "Double"
... def getSingle(self):
... return self._single
... def getDouble(self):
... return self.__double
...
>>> class ClassB(ClassA):
... def getSingle_B(self):
... return self._single
... def getDouble_B(self):
... return self.__double
...
>>> a = ClassA()
>>> b = ClassB()
</code></pre>
<p>You can now trivially access <code>a._single</code> and <code>b._single</code> and get the <code>_single</code> attribute created by <code>ClassA</code>:</p>
<pre><code>>>> a._single, b._single
('Single', 'Single')
>>> a.getSingle(), b.getSingle(), b.getSingle_B()
('Single', 'Single', 'Single')
</code></pre>
<p>But trying to access the <code>__double</code> attribute on the <code>a</code> or <code>b</code> instance directly won't work:</p>
<pre><code>>>> a.__double
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: ClassA instance has no attribute '__double'
>>> b.__double
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: ClassB instance has no attribute '__double'
</code></pre>
<p>And though methods defined in <code>ClassA</code> can get at it directly (when called on either instance):</p>
<pre><code>>>> a.getDouble(), b.getDouble()
('Double', 'Double')
</code></pre>
<p>Methods defined on <code>ClassB</code> can not:</p>
<pre><code>>>> b.getDouble_B()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 5, in getDouble_B
AttributeError: ClassB instance has no attribute '_ClassB__double'
</code></pre>
<p>And right in that error you get a hint about what's happening. The <code>__double</code> attribute name, when accessed inside a class, is being name-mangled to include the name of the class that it is being accessed <em>in</em>. When <code>ClassA</code> tries to access <code>self.__double</code>, it actually turns -- at compiletime -- into an access of <code>self._ClassA__double</code>, and likewise for <code>ClassB</code>. (If a method in <code>ClassB</code> were to assign to <code>__double</code>, not included in the code for brevity, it would therefor not touch <code>ClassA</code>'s <code>__double</code> but create a new attribute.) There is no other protection of this attribute, so you can still access it directly if you know the right name:</p>
<pre><code>>>> a._ClassA__double, b._ClassA__double
('Double', 'Double')
</code></pre>
<p><strong>So why is this a problem?</strong></p>
<p>Well, it's a problem any time you want to inherit and change the behaviour of any code dealing with this attribute. You either have to reimplement everything that touches this double-underscore attribute directly, or you have to guess at the class name and mangle the name manually. The problem gets worse when this double-underscore attribute is actually a method: overriding the method <em>or calling the method in a subclass</em> means doing the name-mangling manually, or reimplementing all the code that calls the method to not use the double-underscore name. Not to mention accessing the attribute dynamically, with <code>getattr()</code>: you will have to manually mangle there, too.</p>
<p>On the other hand, because the attribute is only trivially rewritten, it offers only superficial 'protection'. Any piece of code can still get at the attribute by manually mangling, although that will make <em>their</em> code dependant on the name of <em>your</em> class, and efforts on your side to refactor your code or rename your class (while still keeping the same user-visible name, a common practice in Python) would needlessly break their code. They can also 'trick' Python into doing the name-mangling for them by naming their class the same as yours: notice how there is no module name included in the mangled attribute name. And lastly, the double-underscore attribute is still visible in all attribute lists and all forms of introspection that don't take care to skip attributes starting with a (<em>single</em>) underscore.</p>
<p>So, <em>if</em> you use double-underscore names, use them exceedingly sparingly, as they can turn out quite inconvenient, and never use them for methods <strong>or anything else a subclass may ever want to reimplement, override or access directly</strong>. And realize that double-leading underscore name-mangling offers <em>no real protection</em>. In the end, using a single leading underscore wins you just as much and gives you less (potential, future) pain. Use a single leading underscore.</p>
| 51 | 2008-10-03T09:37:51Z | [
"python",
"oop",
"object",
"attributes"
] |
Sleeping in a batch file | 166,044 | <p>When writing a batch file to automate something on a Windows box, I've needed to pause its execution for several seconds (usually in a test/wait loop, waiting for a process to start). At the time, the best solution I could find uses ping (I kid you not) to achieve the desired effect. I've found a better write-up of it <a href="http://malektips.com/dos0017.html">here</a>, which describes a callable "wait.bat", implemented as follows:</p>
<pre><code>@ping 127.0.0.1 -n 2 -w 1000 > nul
@ping 127.0.0.1 -n %1% -w 1000> nul
</code></pre>
<p>You can then include calls to wait.bat in your own batch file, passing in the number of seconds to sleep.</p>
<p><a href="http://malektips.com/xp_dos_0002.html">Apparently the Windows 2003 Resource Kit provides a Unix-like sleep command</a> (at last!). In the meantime, for those of us still using Windows XP, Windows 2000 or (sadly) <a href="http://en.wikipedia.org/wiki/Windows_NT">Windows NT</a>, is there a better way?</p>
<p>I modified the <code>sleep.py</code> script in the <a href="http://stackoverflow.com/questions/166044/sleeping-in-a-dos-batch-file#166290">accepted answer</a>, so that it defaults to one second if no arguments are passed on the command line:</p>
<pre class="lang-py prettyprint-override"><code>import time, sys
time.sleep(float(sys.argv[1]) if len(sys.argv) > 1 else 1)
</code></pre>
| 129 | 2008-10-03T09:10:29Z | 166,053 | <p>The Resource Kit has always included this. At least since Windows 2000.</p>
<p>Also, the cygwin package has a <code>sleep</code> - plop that into your PATH and include the <code>cygwin.dll</code> (or whatever it's called) and way to go!</p>
| 4 | 2008-10-03T09:13:05Z | [
"python",
"batch-file"
] |
Sleeping in a batch file | 166,044 | <p>When writing a batch file to automate something on a Windows box, I've needed to pause its execution for several seconds (usually in a test/wait loop, waiting for a process to start). At the time, the best solution I could find uses ping (I kid you not) to achieve the desired effect. I've found a better write-up of it <a href="http://malektips.com/dos0017.html">here</a>, which describes a callable "wait.bat", implemented as follows:</p>
<pre><code>@ping 127.0.0.1 -n 2 -w 1000 > nul
@ping 127.0.0.1 -n %1% -w 1000> nul
</code></pre>
<p>You can then include calls to wait.bat in your own batch file, passing in the number of seconds to sleep.</p>
<p><a href="http://malektips.com/xp_dos_0002.html">Apparently the Windows 2003 Resource Kit provides a Unix-like sleep command</a> (at last!). In the meantime, for those of us still using Windows XP, Windows 2000 or (sadly) <a href="http://en.wikipedia.org/wiki/Windows_NT">Windows NT</a>, is there a better way?</p>
<p>I modified the <code>sleep.py</code> script in the <a href="http://stackoverflow.com/questions/166044/sleeping-in-a-dos-batch-file#166290">accepted answer</a>, so that it defaults to one second if no arguments are passed on the command line:</p>
<pre class="lang-py prettyprint-override"><code>import time, sys
time.sleep(float(sys.argv[1]) if len(sys.argv) > 1 else 1)
</code></pre>
| 129 | 2008-10-03T09:10:29Z | 166,058 | <p><code>SLEEP.exe</code> is included in most Resource Kits e.g. <a href="http://www.microsoft.com/downloads/details.aspx?familyid=9d467a69-57ff-4ae7-96ee-b18c4790cffd&displaylang=en" rel="nofollow">The Windows Server 2003 Resource Kit</a> which can be installed on Windows XP too.</p>
<pre><code>Usage: sleep time-to-sleep-in-seconds
sleep [-m] time-to-sleep-in-milliseconds
sleep [-c] commited-memory ratio (1%-100%)
</code></pre>
| 14 | 2008-10-03T09:15:39Z | [
"python",
"batch-file"
] |
Sleeping in a batch file | 166,044 | <p>When writing a batch file to automate something on a Windows box, I've needed to pause its execution for several seconds (usually in a test/wait loop, waiting for a process to start). At the time, the best solution I could find uses ping (I kid you not) to achieve the desired effect. I've found a better write-up of it <a href="http://malektips.com/dos0017.html">here</a>, which describes a callable "wait.bat", implemented as follows:</p>
<pre><code>@ping 127.0.0.1 -n 2 -w 1000 > nul
@ping 127.0.0.1 -n %1% -w 1000> nul
</code></pre>
<p>You can then include calls to wait.bat in your own batch file, passing in the number of seconds to sleep.</p>
<p><a href="http://malektips.com/xp_dos_0002.html">Apparently the Windows 2003 Resource Kit provides a Unix-like sleep command</a> (at last!). In the meantime, for those of us still using Windows XP, Windows 2000 or (sadly) <a href="http://en.wikipedia.org/wiki/Windows_NT">Windows NT</a>, is there a better way?</p>
<p>I modified the <code>sleep.py</code> script in the <a href="http://stackoverflow.com/questions/166044/sleeping-in-a-dos-batch-file#166290">accepted answer</a>, so that it defaults to one second if no arguments are passed on the command line:</p>
<pre class="lang-py prettyprint-override"><code>import time, sys
time.sleep(float(sys.argv[1]) if len(sys.argv) > 1 else 1)
</code></pre>
| 129 | 2008-10-03T09:10:29Z | 166,093 | <p>I faced a similar problem, but I just knocked up a very short C++ console application to do the same thing. Just run <em>MySleep.exe 1000</em> - perhaps easier than downloading/installing the whole resource kit.</p>
<pre class="lang-c prettyprint-override"><code>#include <tchar.h>
#include <stdio.h>
#include "Windows.h"
int _tmain(int argc, _TCHAR* argv[])
{
if (argc == 2)
{
_tprintf(_T("Sleeping for %s ms\n"), argv[1]);
Sleep(_tstoi(argv[1]));
}
else
{
_tprintf(_T("Wrong number of arguments.\n"));
}
return 0;
}
</code></pre>
| 14 | 2008-10-03T09:35:43Z | [
"python",
"batch-file"
] |
Sleeping in a batch file | 166,044 | <p>When writing a batch file to automate something on a Windows box, I've needed to pause its execution for several seconds (usually in a test/wait loop, waiting for a process to start). At the time, the best solution I could find uses ping (I kid you not) to achieve the desired effect. I've found a better write-up of it <a href="http://malektips.com/dos0017.html">here</a>, which describes a callable "wait.bat", implemented as follows:</p>
<pre><code>@ping 127.0.0.1 -n 2 -w 1000 > nul
@ping 127.0.0.1 -n %1% -w 1000> nul
</code></pre>
<p>You can then include calls to wait.bat in your own batch file, passing in the number of seconds to sleep.</p>
<p><a href="http://malektips.com/xp_dos_0002.html">Apparently the Windows 2003 Resource Kit provides a Unix-like sleep command</a> (at last!). In the meantime, for those of us still using Windows XP, Windows 2000 or (sadly) <a href="http://en.wikipedia.org/wiki/Windows_NT">Windows NT</a>, is there a better way?</p>
<p>I modified the <code>sleep.py</code> script in the <a href="http://stackoverflow.com/questions/166044/sleeping-in-a-dos-batch-file#166290">accepted answer</a>, so that it defaults to one second if no arguments are passed on the command line:</p>
<pre class="lang-py prettyprint-override"><code>import time, sys
time.sleep(float(sys.argv[1]) if len(sys.argv) > 1 else 1)
</code></pre>
| 129 | 2008-10-03T09:10:29Z | 166,187 | <p>The usage of <a href="http://en.wikipedia.org/wiki/Ping_%28networking_utility%29" rel="nofollow">ping</a> is good, as long as you just want to "wait for a bit". This since you are dependent on other functions underneath, like your network working and the fact that there is nothing answering on 127.0.0.1. ;-) Maybe it is not very likely it fails, but it is not impossible... </p>
<p>If you want to be sure that you are waiting exactly the specified time, you should use the <code>sleep</code> functionality (which also have the advantage that it doesn't use CPU power or wait for a network to become ready).</p>
<p>To find an already made executable for sleep is the most convenient way. Just drop it into your Windows folder or any other part of your standard path and it is always available.</p>
<p>Otherwise, if you have a compiling environment you can easily make one yourself.
The <code>Sleep</code> function is available in <code>kernel32.dll</code>, so you just need to use that one. :-)
For VB / VBA declare the following in the beginning of your source to declare a sleep function:</p>
<pre><code>private Declare Sub Sleep Lib "kernel32" Alias "Sleep" (byval dwMilliseconds as Long)
</code></pre>
<p>For C#:</p>
<pre><code>[DllImport("kernel32.dll")]
static extern void Sleep(uint dwMilliseconds);
</code></pre>
<p>You'll find here more about this functionality (available since Windows 2000) in <em><a href="http://msdn.microsoft.com/en-us/library/ms686298%28VS.85%29.aspx" rel="nofollow">Sleep function</a></em> (MSDN).</p>
<p>In standard C, <code>sleep()</code> is included in the standard library and in Microsoft's Visual Studio C the function is named <code>Sleep()</code>, if memory serves me. ;-) Those two takes the argument in seconds, not in milliseconds as the two previous declarations.</p>
| 3 | 2008-10-03T10:08:15Z | [
"python",
"batch-file"
] |
Sleeping in a batch file | 166,044 | <p>When writing a batch file to automate something on a Windows box, I've needed to pause its execution for several seconds (usually in a test/wait loop, waiting for a process to start). At the time, the best solution I could find uses ping (I kid you not) to achieve the desired effect. I've found a better write-up of it <a href="http://malektips.com/dos0017.html">here</a>, which describes a callable "wait.bat", implemented as follows:</p>
<pre><code>@ping 127.0.0.1 -n 2 -w 1000 > nul
@ping 127.0.0.1 -n %1% -w 1000> nul
</code></pre>
<p>You can then include calls to wait.bat in your own batch file, passing in the number of seconds to sleep.</p>
<p><a href="http://malektips.com/xp_dos_0002.html">Apparently the Windows 2003 Resource Kit provides a Unix-like sleep command</a> (at last!). In the meantime, for those of us still using Windows XP, Windows 2000 or (sadly) <a href="http://en.wikipedia.org/wiki/Windows_NT">Windows NT</a>, is there a better way?</p>
<p>I modified the <code>sleep.py</code> script in the <a href="http://stackoverflow.com/questions/166044/sleeping-in-a-dos-batch-file#166290">accepted answer</a>, so that it defaults to one second if no arguments are passed on the command line:</p>
<pre class="lang-py prettyprint-override"><code>import time, sys
time.sleep(float(sys.argv[1]) if len(sys.argv) > 1 else 1)
</code></pre>
| 129 | 2008-10-03T09:10:29Z | 166,290 | <p>If you have Python installed, or don't mind installing it (it has other uses too :), just create the following <strong>sleep.py</strong> script and add it somewhere in your PATH:</p>
<pre class="lang-py prettyprint-override"><code>import time, sys
time.sleep(float(sys.argv[1]))
</code></pre>
<p>It will allow sub-second pauses (e.g. 1.5 sec, 0.1 etc), should you have such a need. If you want to call it as <code>sleep</code> rather than <code>sleep.py</code>, then you can add the <code>.PY</code> extension to your PATHEXT environment variable. In XP, you can edit it in:</p>
<p>My Computer â Properties (menu) â Advanced (tab) â Environment Variables (button) â System variables (frame)</p>
| 16 | 2008-10-03T10:42:19Z | [
"python",
"batch-file"
] |
Sleeping in a batch file | 166,044 | <p>When writing a batch file to automate something on a Windows box, I've needed to pause its execution for several seconds (usually in a test/wait loop, waiting for a process to start). At the time, the best solution I could find uses ping (I kid you not) to achieve the desired effect. I've found a better write-up of it <a href="http://malektips.com/dos0017.html">here</a>, which describes a callable "wait.bat", implemented as follows:</p>
<pre><code>@ping 127.0.0.1 -n 2 -w 1000 > nul
@ping 127.0.0.1 -n %1% -w 1000> nul
</code></pre>
<p>You can then include calls to wait.bat in your own batch file, passing in the number of seconds to sleep.</p>
<p><a href="http://malektips.com/xp_dos_0002.html">Apparently the Windows 2003 Resource Kit provides a Unix-like sleep command</a> (at last!). In the meantime, for those of us still using Windows XP, Windows 2000 or (sadly) <a href="http://en.wikipedia.org/wiki/Windows_NT">Windows NT</a>, is there a better way?</p>
<p>I modified the <code>sleep.py</code> script in the <a href="http://stackoverflow.com/questions/166044/sleeping-in-a-dos-batch-file#166290">accepted answer</a>, so that it defaults to one second if no arguments are passed on the command line:</p>
<pre class="lang-py prettyprint-override"><code>import time, sys
time.sleep(float(sys.argv[1]) if len(sys.argv) > 1 else 1)
</code></pre>
| 129 | 2008-10-03T09:10:29Z | 1,092,731 | <p>I have been using this C# sleep program. It might be more convenient for you if C# is your preferred language:</p>
<pre class="lang-cs prettyprint-override"><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace sleep
{
class Program
{
static void Main(string[] args)
{
if (args.Length == 1)
{
double time = Double.Parse(args[0]);
Thread.Sleep((int)(time*1000));
}
else
{
Console.WriteLine("Usage: sleep <seconds>\nExample: sleep 10");
}
}
}
}
</code></pre>
| 3 | 2009-07-07T14:39:09Z | [
"python",
"batch-file"
] |
Sleeping in a batch file | 166,044 | <p>When writing a batch file to automate something on a Windows box, I've needed to pause its execution for several seconds (usually in a test/wait loop, waiting for a process to start). At the time, the best solution I could find uses ping (I kid you not) to achieve the desired effect. I've found a better write-up of it <a href="http://malektips.com/dos0017.html">here</a>, which describes a callable "wait.bat", implemented as follows:</p>
<pre><code>@ping 127.0.0.1 -n 2 -w 1000 > nul
@ping 127.0.0.1 -n %1% -w 1000> nul
</code></pre>
<p>You can then include calls to wait.bat in your own batch file, passing in the number of seconds to sleep.</p>
<p><a href="http://malektips.com/xp_dos_0002.html">Apparently the Windows 2003 Resource Kit provides a Unix-like sleep command</a> (at last!). In the meantime, for those of us still using Windows XP, Windows 2000 or (sadly) <a href="http://en.wikipedia.org/wiki/Windows_NT">Windows NT</a>, is there a better way?</p>
<p>I modified the <code>sleep.py</code> script in the <a href="http://stackoverflow.com/questions/166044/sleeping-in-a-dos-batch-file#166290">accepted answer</a>, so that it defaults to one second if no arguments are passed on the command line:</p>
<pre class="lang-py prettyprint-override"><code>import time, sys
time.sleep(float(sys.argv[1]) if len(sys.argv) > 1 else 1)
</code></pre>
| 129 | 2008-10-03T09:10:29Z | 1,202,058 | <p>Even more lightweight than the Python solution is a Perl
one-liner. </p>
<p>To sleep for 7 seconds put this in the BAT script:</p>
<pre><code>perl -e "sleep 7"
</code></pre>
<p>This solution only provides a resolution of 1 second. </p>
<p>If you need higher resolution then use the Time::HiRes
module from CPAN. It provides usleep() which sleeps in
microseconds and nanosleep() which sleeps in nanoseconds
(both functions takes only integer arguments). See the
StackOverflow question
<a href="http://stackoverflow.com/questions/896904">http://stackoverflow.com/questions/896904</a>, "millisecond
sleep in Perl" for further details.</p>
<p>I have used ActivePerl for many years. It is very easy to
install and can be downloaded from
<a href="http://downloads.activestate.com/ActivePerl/Windows/5.10/" rel="nofollow">http://downloads.activestate.com/ActivePerl/Windows/5.10/</a> (use the latest, build number 1005).</p>
| 2 | 2009-07-29T18:12:24Z | [
"python",
"batch-file"
] |
Sleeping in a batch file | 166,044 | <p>When writing a batch file to automate something on a Windows box, I've needed to pause its execution for several seconds (usually in a test/wait loop, waiting for a process to start). At the time, the best solution I could find uses ping (I kid you not) to achieve the desired effect. I've found a better write-up of it <a href="http://malektips.com/dos0017.html">here</a>, which describes a callable "wait.bat", implemented as follows:</p>
<pre><code>@ping 127.0.0.1 -n 2 -w 1000 > nul
@ping 127.0.0.1 -n %1% -w 1000> nul
</code></pre>
<p>You can then include calls to wait.bat in your own batch file, passing in the number of seconds to sleep.</p>
<p><a href="http://malektips.com/xp_dos_0002.html">Apparently the Windows 2003 Resource Kit provides a Unix-like sleep command</a> (at last!). In the meantime, for those of us still using Windows XP, Windows 2000 or (sadly) <a href="http://en.wikipedia.org/wiki/Windows_NT">Windows NT</a>, is there a better way?</p>
<p>I modified the <code>sleep.py</code> script in the <a href="http://stackoverflow.com/questions/166044/sleeping-in-a-dos-batch-file#166290">accepted answer</a>, so that it defaults to one second if no arguments are passed on the command line:</p>
<pre class="lang-py prettyprint-override"><code>import time, sys
time.sleep(float(sys.argv[1]) if len(sys.argv) > 1 else 1)
</code></pre>
| 129 | 2008-10-03T09:10:29Z | 1,304,768 | <p>You can use ping:</p>
<pre><code>ping 127.0.0.1 -n 11 -w 1000 >nul: 2>nul:
</code></pre>
<p>will wait 10 seconds.</p>
<p>The reason you have to use 11 is because the first ping goes out immediately, not after one second. The number should always be one more than the number of seconds you want to wait.</p>
<p>Keep in mind that the purpose of the <code>-w</code> is not to wait one second, it's to ensure that you wait no <em>more</em> than one second in the event that there are network problems. <code>ping</code> on it's own will send one ICMP packet per second. It's probably not required for localhost but old habits die hard.</p>
| 7 | 2009-08-20T08:28:55Z | [
"python",
"batch-file"
] |
Sleeping in a batch file | 166,044 | <p>When writing a batch file to automate something on a Windows box, I've needed to pause its execution for several seconds (usually in a test/wait loop, waiting for a process to start). At the time, the best solution I could find uses ping (I kid you not) to achieve the desired effect. I've found a better write-up of it <a href="http://malektips.com/dos0017.html">here</a>, which describes a callable "wait.bat", implemented as follows:</p>
<pre><code>@ping 127.0.0.1 -n 2 -w 1000 > nul
@ping 127.0.0.1 -n %1% -w 1000> nul
</code></pre>
<p>You can then include calls to wait.bat in your own batch file, passing in the number of seconds to sleep.</p>
<p><a href="http://malektips.com/xp_dos_0002.html">Apparently the Windows 2003 Resource Kit provides a Unix-like sleep command</a> (at last!). In the meantime, for those of us still using Windows XP, Windows 2000 or (sadly) <a href="http://en.wikipedia.org/wiki/Windows_NT">Windows NT</a>, is there a better way?</p>
<p>I modified the <code>sleep.py</code> script in the <a href="http://stackoverflow.com/questions/166044/sleeping-in-a-dos-batch-file#166290">accepted answer</a>, so that it defaults to one second if no arguments are passed on the command line:</p>
<pre class="lang-py prettyprint-override"><code>import time, sys
time.sleep(float(sys.argv[1]) if len(sys.argv) > 1 else 1)
</code></pre>
| 129 | 2008-10-03T09:10:29Z | 1,811,248 | <p>Over at Server Fault, <a href="http://serverfault.com/questions/38318/better-way-to-wait-a-few-seconds-in-a-bat-file">a similar question was asked</a>, the solution there was:</p>
<pre><code>choice /d y /t 5 > nul
</code></pre>
| 10 | 2009-11-28T01:29:47Z | [
"python",
"batch-file"
] |
Sleeping in a batch file | 166,044 | <p>When writing a batch file to automate something on a Windows box, I've needed to pause its execution for several seconds (usually in a test/wait loop, waiting for a process to start). At the time, the best solution I could find uses ping (I kid you not) to achieve the desired effect. I've found a better write-up of it <a href="http://malektips.com/dos0017.html">here</a>, which describes a callable "wait.bat", implemented as follows:</p>
<pre><code>@ping 127.0.0.1 -n 2 -w 1000 > nul
@ping 127.0.0.1 -n %1% -w 1000> nul
</code></pre>
<p>You can then include calls to wait.bat in your own batch file, passing in the number of seconds to sleep.</p>
<p><a href="http://malektips.com/xp_dos_0002.html">Apparently the Windows 2003 Resource Kit provides a Unix-like sleep command</a> (at last!). In the meantime, for those of us still using Windows XP, Windows 2000 or (sadly) <a href="http://en.wikipedia.org/wiki/Windows_NT">Windows NT</a>, is there a better way?</p>
<p>I modified the <code>sleep.py</code> script in the <a href="http://stackoverflow.com/questions/166044/sleeping-in-a-dos-batch-file#166290">accepted answer</a>, so that it defaults to one second if no arguments are passed on the command line:</p>
<pre class="lang-py prettyprint-override"><code>import time, sys
time.sleep(float(sys.argv[1]) if len(sys.argv) > 1 else 1)
</code></pre>
| 129 | 2008-10-03T09:10:29Z | 1,811,314 | <p>You could use the Windows <em>cscript WSH</em> layer and this <em>wait.js</em> JavaScript file:</p>
<pre><code>if (WScript.Arguments.Count() == 1)
WScript.Sleep(WScript.Arguments(0)*1000);
else
WScript.Echo("Usage: cscript wait.js seconds");
</code></pre>
| 9 | 2009-11-28T02:00:40Z | [
"python",
"batch-file"
] |
Sleeping in a batch file | 166,044 | <p>When writing a batch file to automate something on a Windows box, I've needed to pause its execution for several seconds (usually in a test/wait loop, waiting for a process to start). At the time, the best solution I could find uses ping (I kid you not) to achieve the desired effect. I've found a better write-up of it <a href="http://malektips.com/dos0017.html">here</a>, which describes a callable "wait.bat", implemented as follows:</p>
<pre><code>@ping 127.0.0.1 -n 2 -w 1000 > nul
@ping 127.0.0.1 -n %1% -w 1000> nul
</code></pre>
<p>You can then include calls to wait.bat in your own batch file, passing in the number of seconds to sleep.</p>
<p><a href="http://malektips.com/xp_dos_0002.html">Apparently the Windows 2003 Resource Kit provides a Unix-like sleep command</a> (at last!). In the meantime, for those of us still using Windows XP, Windows 2000 or (sadly) <a href="http://en.wikipedia.org/wiki/Windows_NT">Windows NT</a>, is there a better way?</p>
<p>I modified the <code>sleep.py</code> script in the <a href="http://stackoverflow.com/questions/166044/sleeping-in-a-dos-batch-file#166290">accepted answer</a>, so that it defaults to one second if no arguments are passed on the command line:</p>
<pre class="lang-py prettyprint-override"><code>import time, sys
time.sleep(float(sys.argv[1]) if len(sys.argv) > 1 else 1)
</code></pre>
| 129 | 2008-10-03T09:10:29Z | 5,437,271 | <p>Just put this in your batch file where you want the wait.</p>
<pre><code>@ping 127.0.0.1 -n 11 -w 1000 > null
</code></pre>
| 5 | 2011-03-25T19:35:09Z | [
"python",
"batch-file"
] |
Sleeping in a batch file | 166,044 | <p>When writing a batch file to automate something on a Windows box, I've needed to pause its execution for several seconds (usually in a test/wait loop, waiting for a process to start). At the time, the best solution I could find uses ping (I kid you not) to achieve the desired effect. I've found a better write-up of it <a href="http://malektips.com/dos0017.html">here</a>, which describes a callable "wait.bat", implemented as follows:</p>
<pre><code>@ping 127.0.0.1 -n 2 -w 1000 > nul
@ping 127.0.0.1 -n %1% -w 1000> nul
</code></pre>
<p>You can then include calls to wait.bat in your own batch file, passing in the number of seconds to sleep.</p>
<p><a href="http://malektips.com/xp_dos_0002.html">Apparently the Windows 2003 Resource Kit provides a Unix-like sleep command</a> (at last!). In the meantime, for those of us still using Windows XP, Windows 2000 or (sadly) <a href="http://en.wikipedia.org/wiki/Windows_NT">Windows NT</a>, is there a better way?</p>
<p>I modified the <code>sleep.py</code> script in the <a href="http://stackoverflow.com/questions/166044/sleeping-in-a-dos-batch-file#166290">accepted answer</a>, so that it defaults to one second if no arguments are passed on the command line:</p>
<pre class="lang-py prettyprint-override"><code>import time, sys
time.sleep(float(sys.argv[1]) if len(sys.argv) > 1 else 1)
</code></pre>
| 129 | 2008-10-03T09:10:29Z | 5,438,142 | <p>Depending on your compatibility needs, either use <code>ping</code>:</p>
<pre><code>ping -n <numberofseconds+1> localhost >nul 2>&1
</code></pre>
<p>e.g. to wait 5 seconds, use </p>
<pre><code>ping -n 6 localhost >nul 2>&1
</code></pre>
<p>or on Windows 7 or later use <code>timeout</code>:</p>
<pre><code>timeout 6 >nul
</code></pre>
| 8 | 2011-03-25T21:04:54Z | [
"python",
"batch-file"
] |
Sleeping in a batch file | 166,044 | <p>When writing a batch file to automate something on a Windows box, I've needed to pause its execution for several seconds (usually in a test/wait loop, waiting for a process to start). At the time, the best solution I could find uses ping (I kid you not) to achieve the desired effect. I've found a better write-up of it <a href="http://malektips.com/dos0017.html">here</a>, which describes a callable "wait.bat", implemented as follows:</p>
<pre><code>@ping 127.0.0.1 -n 2 -w 1000 > nul
@ping 127.0.0.1 -n %1% -w 1000> nul
</code></pre>
<p>You can then include calls to wait.bat in your own batch file, passing in the number of seconds to sleep.</p>
<p><a href="http://malektips.com/xp_dos_0002.html">Apparently the Windows 2003 Resource Kit provides a Unix-like sleep command</a> (at last!). In the meantime, for those of us still using Windows XP, Windows 2000 or (sadly) <a href="http://en.wikipedia.org/wiki/Windows_NT">Windows NT</a>, is there a better way?</p>
<p>I modified the <code>sleep.py</code> script in the <a href="http://stackoverflow.com/questions/166044/sleeping-in-a-dos-batch-file#166290">accepted answer</a>, so that it defaults to one second if no arguments are passed on the command line:</p>
<pre class="lang-py prettyprint-override"><code>import time, sys
time.sleep(float(sys.argv[1]) if len(sys.argv) > 1 else 1)
</code></pre>
| 129 | 2008-10-03T09:10:29Z | 5,483,958 | <p>The <a href="http://technet.microsoft.com/en-us/library/cc754891.aspx"><code>timeout</code></a> command is available from Vista onwards.</p>
<pre><code>c:\> timeout /?
TIMEOUT [/T] timeout [/NOBREAK]
Description:
This utility accepts a timeout parameter to wait for the specified
time period (in seconds) or until any key is pressed. It also
accepts a parameter to ignore the key press.
Parameter List:
/T timeout Specifies the number of seconds to wait.
Valid range is -1 to 99999 seconds.
/NOBREAK Ignore key presses and wait specified time.
/? Displays this help message.
NOTE: A timeout value of -1 means to wait indefinitely for a key press.
Examples:
TIMEOUT /?
TIMEOUT /T 10
TIMEOUT /T 300 /NOBREAK
TIMEOUT /T -1
</code></pre>
<p>Note: Does not work with input redirection - trivial example:</p>
<pre><code>C:\>echo 1 | timeout /t 1 /nobreak
ERROR: Input redirection is not supported, exiting the process immediately.
</code></pre>
| 189 | 2011-03-30T08:38:43Z | [
"python",
"batch-file"
] |
Sleeping in a batch file | 166,044 | <p>When writing a batch file to automate something on a Windows box, I've needed to pause its execution for several seconds (usually in a test/wait loop, waiting for a process to start). At the time, the best solution I could find uses ping (I kid you not) to achieve the desired effect. I've found a better write-up of it <a href="http://malektips.com/dos0017.html">here</a>, which describes a callable "wait.bat", implemented as follows:</p>
<pre><code>@ping 127.0.0.1 -n 2 -w 1000 > nul
@ping 127.0.0.1 -n %1% -w 1000> nul
</code></pre>
<p>You can then include calls to wait.bat in your own batch file, passing in the number of seconds to sleep.</p>
<p><a href="http://malektips.com/xp_dos_0002.html">Apparently the Windows 2003 Resource Kit provides a Unix-like sleep command</a> (at last!). In the meantime, for those of us still using Windows XP, Windows 2000 or (sadly) <a href="http://en.wikipedia.org/wiki/Windows_NT">Windows NT</a>, is there a better way?</p>
<p>I modified the <code>sleep.py</code> script in the <a href="http://stackoverflow.com/questions/166044/sleeping-in-a-dos-batch-file#166290">accepted answer</a>, so that it defaults to one second if no arguments are passed on the command line:</p>
<pre class="lang-py prettyprint-override"><code>import time, sys
time.sleep(float(sys.argv[1]) if len(sys.argv) > 1 else 1)
</code></pre>
| 129 | 2008-10-03T09:10:29Z | 5,822,491 | <p>Impressed with this one:</p>
<p><a href="http://www.computerhope.com/batch.htm#02" rel="nofollow">http://www.computerhope.com/batch.htm#02</a></p>
<pre><code>choice /n /c y /d y /t 5 >NUL
</code></pre>
<p>Technically you're telling the choice command to accept only y, default to y, to do so in 5 seconds, to draw no prompt, and to dump anything it does say to NUL (like null terminal in Linux).</p>
| 1 | 2011-04-28T17:15:08Z | [
"python",
"batch-file"
] |
Sleeping in a batch file | 166,044 | <p>When writing a batch file to automate something on a Windows box, I've needed to pause its execution for several seconds (usually in a test/wait loop, waiting for a process to start). At the time, the best solution I could find uses ping (I kid you not) to achieve the desired effect. I've found a better write-up of it <a href="http://malektips.com/dos0017.html">here</a>, which describes a callable "wait.bat", implemented as follows:</p>
<pre><code>@ping 127.0.0.1 -n 2 -w 1000 > nul
@ping 127.0.0.1 -n %1% -w 1000> nul
</code></pre>
<p>You can then include calls to wait.bat in your own batch file, passing in the number of seconds to sleep.</p>
<p><a href="http://malektips.com/xp_dos_0002.html">Apparently the Windows 2003 Resource Kit provides a Unix-like sleep command</a> (at last!). In the meantime, for those of us still using Windows XP, Windows 2000 or (sadly) <a href="http://en.wikipedia.org/wiki/Windows_NT">Windows NT</a>, is there a better way?</p>
<p>I modified the <code>sleep.py</code> script in the <a href="http://stackoverflow.com/questions/166044/sleeping-in-a-dos-batch-file#166290">accepted answer</a>, so that it defaults to one second if no arguments are passed on the command line:</p>
<pre class="lang-py prettyprint-override"><code>import time, sys
time.sleep(float(sys.argv[1]) if len(sys.argv) > 1 else 1)
</code></pre>
| 129 | 2008-10-03T09:10:29Z | 6,806,192 | <p>I disagree with the answers I found here.</p>
<p>I use the following method entirely based on Windows XP capabilities to do a delay in a batch file:</p>
<p>DELAY.BAT:</p>
<pre><code>@ECHO OFF
REM DELAY seconds
REM GET ENDING SECOND
FOR /F "TOKENS=1-3 DELIMS=:." %%A IN ("%TIME%") DO SET /A H=%%A, M=1%%B%%100, S=1%%C%%100, ENDING=(H*60+M)*60+S+%1
REM WAIT FOR SUCH A SECOND
:WAIT
FOR /F "TOKENS=1-3 DELIMS=:." %%A IN ("%TIME%") DO SET /A H=%%A, M=1%%B%%100, S=1%%C%%100, CURRENT=(H*60+M)*60+S
IF %CURRENT% LSS %ENDING% GOTO WAIT
</code></pre>
<p>You may also insert the day in the calculation so the method also works when the delay interval pass over midnight.</p>
| 15 | 2011-07-24T10:10:43Z | [
"python",
"batch-file"
] |
Sleeping in a batch file | 166,044 | <p>When writing a batch file to automate something on a Windows box, I've needed to pause its execution for several seconds (usually in a test/wait loop, waiting for a process to start). At the time, the best solution I could find uses ping (I kid you not) to achieve the desired effect. I've found a better write-up of it <a href="http://malektips.com/dos0017.html">here</a>, which describes a callable "wait.bat", implemented as follows:</p>
<pre><code>@ping 127.0.0.1 -n 2 -w 1000 > nul
@ping 127.0.0.1 -n %1% -w 1000> nul
</code></pre>
<p>You can then include calls to wait.bat in your own batch file, passing in the number of seconds to sleep.</p>
<p><a href="http://malektips.com/xp_dos_0002.html">Apparently the Windows 2003 Resource Kit provides a Unix-like sleep command</a> (at last!). In the meantime, for those of us still using Windows XP, Windows 2000 or (sadly) <a href="http://en.wikipedia.org/wiki/Windows_NT">Windows NT</a>, is there a better way?</p>
<p>I modified the <code>sleep.py</code> script in the <a href="http://stackoverflow.com/questions/166044/sleeping-in-a-dos-batch-file#166290">accepted answer</a>, so that it defaults to one second if no arguments are passed on the command line:</p>
<pre class="lang-py prettyprint-override"><code>import time, sys
time.sleep(float(sys.argv[1]) if len(sys.argv) > 1 else 1)
</code></pre>
| 129 | 2008-10-03T09:10:29Z | 6,852,798 | <p>Using the <code>ping</code> method as outlined is how I do it when I can't (or don't want to) add more executables or install any other software.</p>
<p>You should be pinging something that isn't there, and using the <code>-w</code> flag so that it fails after that amount of time, not pinging something that <em>is</em> there (like localhost) <code>-n</code> times. This allows you to handle time less than a second, and I think it's slightly more accurate.</p>
<p>e.g.</p>
<p>(test that 1.1.1.1 isn't taken)</p>
<pre><code>ECHO Waiting 15 seconds
PING 1.1.1.1 -n 1 -w 15000 > NUL
or
PING -n 15 -w 1000 127.1 >NUL
</code></pre>
| 21 | 2011-07-28T00:20:12Z | [
"python",
"batch-file"
] |
Sleeping in a batch file | 166,044 | <p>When writing a batch file to automate something on a Windows box, I've needed to pause its execution for several seconds (usually in a test/wait loop, waiting for a process to start). At the time, the best solution I could find uses ping (I kid you not) to achieve the desired effect. I've found a better write-up of it <a href="http://malektips.com/dos0017.html">here</a>, which describes a callable "wait.bat", implemented as follows:</p>
<pre><code>@ping 127.0.0.1 -n 2 -w 1000 > nul
@ping 127.0.0.1 -n %1% -w 1000> nul
</code></pre>
<p>You can then include calls to wait.bat in your own batch file, passing in the number of seconds to sleep.</p>
<p><a href="http://malektips.com/xp_dos_0002.html">Apparently the Windows 2003 Resource Kit provides a Unix-like sleep command</a> (at last!). In the meantime, for those of us still using Windows XP, Windows 2000 or (sadly) <a href="http://en.wikipedia.org/wiki/Windows_NT">Windows NT</a>, is there a better way?</p>
<p>I modified the <code>sleep.py</code> script in the <a href="http://stackoverflow.com/questions/166044/sleeping-in-a-dos-batch-file#166290">accepted answer</a>, so that it defaults to one second if no arguments are passed on the command line:</p>
<pre class="lang-py prettyprint-override"><code>import time, sys
time.sleep(float(sys.argv[1]) if len(sys.argv) > 1 else 1)
</code></pre>
| 129 | 2008-10-03T09:10:29Z | 8,775,655 | <p>Or command line Python, for example, for 6 and a half seconds:</p>
<pre><code>python -c "import time;time.sleep(6.5)"
</code></pre>
| 1 | 2012-01-08T05:39:12Z | [
"python",
"batch-file"
] |
Sleeping in a batch file | 166,044 | <p>When writing a batch file to automate something on a Windows box, I've needed to pause its execution for several seconds (usually in a test/wait loop, waiting for a process to start). At the time, the best solution I could find uses ping (I kid you not) to achieve the desired effect. I've found a better write-up of it <a href="http://malektips.com/dos0017.html">here</a>, which describes a callable "wait.bat", implemented as follows:</p>
<pre><code>@ping 127.0.0.1 -n 2 -w 1000 > nul
@ping 127.0.0.1 -n %1% -w 1000> nul
</code></pre>
<p>You can then include calls to wait.bat in your own batch file, passing in the number of seconds to sleep.</p>
<p><a href="http://malektips.com/xp_dos_0002.html">Apparently the Windows 2003 Resource Kit provides a Unix-like sleep command</a> (at last!). In the meantime, for those of us still using Windows XP, Windows 2000 or (sadly) <a href="http://en.wikipedia.org/wiki/Windows_NT">Windows NT</a>, is there a better way?</p>
<p>I modified the <code>sleep.py</code> script in the <a href="http://stackoverflow.com/questions/166044/sleeping-in-a-dos-batch-file#166290">accepted answer</a>, so that it defaults to one second if no arguments are passed on the command line:</p>
<pre class="lang-py prettyprint-override"><code>import time, sys
time.sleep(float(sys.argv[1]) if len(sys.argv) > 1 else 1)
</code></pre>
| 129 | 2008-10-03T09:10:29Z | 14,404,448 | <p>In Notepad, write:</p>
<pre><code>@echo off
set /a WAITTIME=%1+1
PING 127.0.0.1 -n %WAITTIME% > nul
goto:eof
</code></pre>
<p>Now save as wait.bat in the folder C:\WINDOWS\System32,
then whenever you want to wait, use:</p>
<pre><code>CALL WAIT.bat <whole number of seconds without quotes>
</code></pre>
| 4 | 2013-01-18T17:35:21Z | [
"python",
"batch-file"
] |
Sleeping in a batch file | 166,044 | <p>When writing a batch file to automate something on a Windows box, I've needed to pause its execution for several seconds (usually in a test/wait loop, waiting for a process to start). At the time, the best solution I could find uses ping (I kid you not) to achieve the desired effect. I've found a better write-up of it <a href="http://malektips.com/dos0017.html">here</a>, which describes a callable "wait.bat", implemented as follows:</p>
<pre><code>@ping 127.0.0.1 -n 2 -w 1000 > nul
@ping 127.0.0.1 -n %1% -w 1000> nul
</code></pre>
<p>You can then include calls to wait.bat in your own batch file, passing in the number of seconds to sleep.</p>
<p><a href="http://malektips.com/xp_dos_0002.html">Apparently the Windows 2003 Resource Kit provides a Unix-like sleep command</a> (at last!). In the meantime, for those of us still using Windows XP, Windows 2000 or (sadly) <a href="http://en.wikipedia.org/wiki/Windows_NT">Windows NT</a>, is there a better way?</p>
<p>I modified the <code>sleep.py</code> script in the <a href="http://stackoverflow.com/questions/166044/sleeping-in-a-dos-batch-file#166290">accepted answer</a>, so that it defaults to one second if no arguments are passed on the command line:</p>
<pre class="lang-py prettyprint-override"><code>import time, sys
time.sleep(float(sys.argv[1]) if len(sys.argv) > 1 else 1)
</code></pre>
| 129 | 2008-10-03T09:10:29Z | 14,574,706 | <p>I like <a href="http://stackoverflow.com/a/6806192/2020158">Aacini's response</a>. I added to it to handle the day and also enable it to handle <a href="http://en.wikipedia.org/wiki/Centisecond" rel="nofollow" title="Centisecond">centiseconds</a> (<code>%TIME%</code> outputs <code>H:MM:SS.CC</code>):</p>
<pre><code>:delay
SET DELAYINPUT=%1
SET /A DAYS=DELAYINPUT/8640000
SET /A DELAYINPUT=DELAYINPUT-(DAYS*864000)
::Get ending centisecond (10 milliseconds)
FOR /F "tokens=1-4 delims=:." %%A IN ("%TIME%") DO SET /A H=%%A, M=1%%B%%100, S=1%%C%%100, X=1%%D%%100, ENDING=((H*60+M)*60+S)*100+X+DELAYINPUT
SET /A DAYS=DAYS+ENDING/8640000
SET /A ENDING=ENDING-(DAYS*864000)
::Wait for such a centisecond
:delay_wait
FOR /F "tokens=1-4 delims=:." %%A IN ("%TIME%") DO SET /A H=%%A, M=1%%B%%100, S=1%%C%%100, X=1%%D%%100, CURRENT=((H*60+M)*60+S)*100+X
IF DEFINED LASTCURRENT IF %CURRENT% LSS %LASTCURRENT% SET /A DAYS=DAYS-1
SET LASTCURRENT=%CURRENT%
IF %CURRENT% LSS %ENDING% GOTO delay_wait
IF %DAYS% GTR 0 GOTO delay_wait
GOTO :EOF
</code></pre>
| 3 | 2013-01-29T02:30:37Z | [
"python",
"batch-file"
] |
Sleeping in a batch file | 166,044 | <p>When writing a batch file to automate something on a Windows box, I've needed to pause its execution for several seconds (usually in a test/wait loop, waiting for a process to start). At the time, the best solution I could find uses ping (I kid you not) to achieve the desired effect. I've found a better write-up of it <a href="http://malektips.com/dos0017.html">here</a>, which describes a callable "wait.bat", implemented as follows:</p>
<pre><code>@ping 127.0.0.1 -n 2 -w 1000 > nul
@ping 127.0.0.1 -n %1% -w 1000> nul
</code></pre>
<p>You can then include calls to wait.bat in your own batch file, passing in the number of seconds to sleep.</p>
<p><a href="http://malektips.com/xp_dos_0002.html">Apparently the Windows 2003 Resource Kit provides a Unix-like sleep command</a> (at last!). In the meantime, for those of us still using Windows XP, Windows 2000 or (sadly) <a href="http://en.wikipedia.org/wiki/Windows_NT">Windows NT</a>, is there a better way?</p>
<p>I modified the <code>sleep.py</code> script in the <a href="http://stackoverflow.com/questions/166044/sleeping-in-a-dos-batch-file#166290">accepted answer</a>, so that it defaults to one second if no arguments are passed on the command line:</p>
<pre class="lang-py prettyprint-override"><code>import time, sys
time.sleep(float(sys.argv[1]) if len(sys.argv) > 1 else 1)
</code></pre>
| 129 | 2008-10-03T09:10:29Z | 16,803,440 | <p>If you've got <a href="http://en.wikipedia.org/wiki/Windows_PowerShell" rel="nofollow">PowerShell</a> on your system, you can just execute this command:</p>
<pre><code>powershell -command "Start-Sleep -s 1"
</code></pre>
<hr>
<p>Edit: from <a href="http://stackoverflow.com/a/16803409/114200">my answer on a similar thread</a>, people raised an issue where the amount of time powershell takes to start is significant compared to how long you're trying to wait for. If the accuracy of the wait time is important (ie a second or two extra delay is not acceptable), you can use this approach:</p>
<pre><code>powershell -command "$sleepUntil = [DateTime]::Parse('%date% %time%').AddSeconds(5); $sleepDuration = $sleepUntil.Subtract((get-date)).TotalMilliseconds; start-sleep -m $sleepDuration"
</code></pre>
<p>This takes the time when the windows command was issued, and the powershell script sleeps until 5 seconds after that time. So as long as powershell takes less time to start than your sleep duration, this approach will work (it's around 600ms on my machine).</p>
| 4 | 2013-05-29T00:03:40Z | [
"python",
"batch-file"
] |
Sleeping in a batch file | 166,044 | <p>When writing a batch file to automate something on a Windows box, I've needed to pause its execution for several seconds (usually in a test/wait loop, waiting for a process to start). At the time, the best solution I could find uses ping (I kid you not) to achieve the desired effect. I've found a better write-up of it <a href="http://malektips.com/dos0017.html">here</a>, which describes a callable "wait.bat", implemented as follows:</p>
<pre><code>@ping 127.0.0.1 -n 2 -w 1000 > nul
@ping 127.0.0.1 -n %1% -w 1000> nul
</code></pre>
<p>You can then include calls to wait.bat in your own batch file, passing in the number of seconds to sleep.</p>
<p><a href="http://malektips.com/xp_dos_0002.html">Apparently the Windows 2003 Resource Kit provides a Unix-like sleep command</a> (at last!). In the meantime, for those of us still using Windows XP, Windows 2000 or (sadly) <a href="http://en.wikipedia.org/wiki/Windows_NT">Windows NT</a>, is there a better way?</p>
<p>I modified the <code>sleep.py</code> script in the <a href="http://stackoverflow.com/questions/166044/sleeping-in-a-dos-batch-file#166290">accepted answer</a>, so that it defaults to one second if no arguments are passed on the command line:</p>
<pre class="lang-py prettyprint-override"><code>import time, sys
time.sleep(float(sys.argv[1]) if len(sys.argv) > 1 else 1)
</code></pre>
| 129 | 2008-10-03T09:10:29Z | 18,644,875 | <p>You can get fancy by putting the PAUSE message in the title bar:</p>
<pre><code>@ECHO off
SET TITLETEXT=Sleep
TITLE %TITLETEXT%
CALL :sleep 5
GOTO :END
:: Function Section
:sleep ARG
ECHO Pausing...
FOR /l %%a in (%~1,-1,1) DO (TITLE Script %TITLETEXT% -- time left^
%%as&PING.exe -n 2 -w 1000 127.1>NUL)
EXIT /B 0
:: End of script
:END
pause
::this is EOF
</code></pre>
| 0 | 2013-09-05T19:58:32Z | [
"python",
"batch-file"
] |
Sleeping in a batch file | 166,044 | <p>When writing a batch file to automate something on a Windows box, I've needed to pause its execution for several seconds (usually in a test/wait loop, waiting for a process to start). At the time, the best solution I could find uses ping (I kid you not) to achieve the desired effect. I've found a better write-up of it <a href="http://malektips.com/dos0017.html">here</a>, which describes a callable "wait.bat", implemented as follows:</p>
<pre><code>@ping 127.0.0.1 -n 2 -w 1000 > nul
@ping 127.0.0.1 -n %1% -w 1000> nul
</code></pre>
<p>You can then include calls to wait.bat in your own batch file, passing in the number of seconds to sleep.</p>
<p><a href="http://malektips.com/xp_dos_0002.html">Apparently the Windows 2003 Resource Kit provides a Unix-like sleep command</a> (at last!). In the meantime, for those of us still using Windows XP, Windows 2000 or (sadly) <a href="http://en.wikipedia.org/wiki/Windows_NT">Windows NT</a>, is there a better way?</p>
<p>I modified the <code>sleep.py</code> script in the <a href="http://stackoverflow.com/questions/166044/sleeping-in-a-dos-batch-file#166290">accepted answer</a>, so that it defaults to one second if no arguments are passed on the command line:</p>
<pre class="lang-py prettyprint-override"><code>import time, sys
time.sleep(float(sys.argv[1]) if len(sys.argv) > 1 else 1)
</code></pre>
| 129 | 2008-10-03T09:10:29Z | 20,994,851 | <p>From Vista on you have <a href="http://ss64.com/nt/timeout.html" rel="nofollow">TIMEOUT</a> and <a href="http://ss64.com/nt/sleep.html" rel="nofollow">SLEEP</a> commands , but to use them in XP or Win2003 you'll need <a href="http://www.microsoft.com/en-us/download/details.aspx?id=17657" rel="nofollow">Win2003 resource tool kit</a> . <a href="http://www.robvanderwoude.com/wait.php" rel="nofollow">Here</a> you have a good overview of sleep alternatives (the ping approach is the most popular as it will work on every windows machine) , but there's (at least) one not mentioned which (ab)uses W32TM command:</p>
<pre><code>w32tm /stripchart /computer:localhost /period:1 /dataonly /samples:N >nul 2>&1
</code></pre>
<p>where you should replace the N with the seconds you want to pause.Also will work on every Windows system without prerequisites.</p>
| 1 | 2014-01-08T11:50:43Z | [
"python",
"batch-file"
] |
Sleeping in a batch file | 166,044 | <p>When writing a batch file to automate something on a Windows box, I've needed to pause its execution for several seconds (usually in a test/wait loop, waiting for a process to start). At the time, the best solution I could find uses ping (I kid you not) to achieve the desired effect. I've found a better write-up of it <a href="http://malektips.com/dos0017.html">here</a>, which describes a callable "wait.bat", implemented as follows:</p>
<pre><code>@ping 127.0.0.1 -n 2 -w 1000 > nul
@ping 127.0.0.1 -n %1% -w 1000> nul
</code></pre>
<p>You can then include calls to wait.bat in your own batch file, passing in the number of seconds to sleep.</p>
<p><a href="http://malektips.com/xp_dos_0002.html">Apparently the Windows 2003 Resource Kit provides a Unix-like sleep command</a> (at last!). In the meantime, for those of us still using Windows XP, Windows 2000 or (sadly) <a href="http://en.wikipedia.org/wiki/Windows_NT">Windows NT</a>, is there a better way?</p>
<p>I modified the <code>sleep.py</code> script in the <a href="http://stackoverflow.com/questions/166044/sleeping-in-a-dos-batch-file#166290">accepted answer</a>, so that it defaults to one second if no arguments are passed on the command line:</p>
<pre class="lang-py prettyprint-override"><code>import time, sys
time.sleep(float(sys.argv[1]) if len(sys.argv) > 1 else 1)
</code></pre>
| 129 | 2008-10-03T09:10:29Z | 21,252,806 | <p>You can also use a .vbs file to do specific timeouts:</p>
<p>The code below creates the .vbs file, put this near the top of you rbatch code:</p>
<pre><code>echo WScript.sleep WScript.Arguments(0) >"%cd%\sleeper.vbs"
</code></pre>
<p><br />
The Code Below Then opens the .vbs and specifies how long to wait for:</p>
<pre><code>start /WAIT "" "%cd%\sleeper.vbs" "1000"
</code></pre>
<p>In the above code, the "1000" is the value of time delay to be sent to the .vbs file in miliseconds e.g. 1000ms = 1s. You can alter this part to be however long you want.</p>
<p><br />
The Code Below Deletes the .vbs after you are done with it, put this at the end of your batch file:</p>
<pre><code>del /f /q "%cd%\sleeper.vbs"
</code></pre>
<p><br />
And here is the code all together so it's easy to copy:</p>
<pre><code>echo WScript.sleep WScript.Arguments(0) >"%cd%\sleeper.vbs"
start /WAIT "" "%cd%\sleeper.vbs" "1000"
del /f /q "%cd%\sleeper.vbs"
</code></pre>
| 1 | 2014-01-21T08:28:47Z | [
"python",
"batch-file"
] |
Sleeping in a batch file | 166,044 | <p>When writing a batch file to automate something on a Windows box, I've needed to pause its execution for several seconds (usually in a test/wait loop, waiting for a process to start). At the time, the best solution I could find uses ping (I kid you not) to achieve the desired effect. I've found a better write-up of it <a href="http://malektips.com/dos0017.html">here</a>, which describes a callable "wait.bat", implemented as follows:</p>
<pre><code>@ping 127.0.0.1 -n 2 -w 1000 > nul
@ping 127.0.0.1 -n %1% -w 1000> nul
</code></pre>
<p>You can then include calls to wait.bat in your own batch file, passing in the number of seconds to sleep.</p>
<p><a href="http://malektips.com/xp_dos_0002.html">Apparently the Windows 2003 Resource Kit provides a Unix-like sleep command</a> (at last!). In the meantime, for those of us still using Windows XP, Windows 2000 or (sadly) <a href="http://en.wikipedia.org/wiki/Windows_NT">Windows NT</a>, is there a better way?</p>
<p>I modified the <code>sleep.py</code> script in the <a href="http://stackoverflow.com/questions/166044/sleeping-in-a-dos-batch-file#166290">accepted answer</a>, so that it defaults to one second if no arguments are passed on the command line:</p>
<pre class="lang-py prettyprint-override"><code>import time, sys
time.sleep(float(sys.argv[1]) if len(sys.argv) > 1 else 1)
</code></pre>
| 129 | 2008-10-03T09:10:29Z | 21,433,296 | <p>Tested on XP SP3 and Win7, uses cscript. I put some safe guards to avoid del "" prompting. (/q would be dangerous)</p>
<p>wait 1 s: </p>
<blockquote>
<p>sleepOrDelayExecution 1000 </p>
</blockquote>
<p>wait 500 ms and then run stuff after:</p>
<blockquote>
<p>sleepOrDelayExecution 500 dir \ /s</p>
</blockquote>
<p>sleepOrDelayExecution.bat:</p>
<pre><code>@echo off
if "%1" == "" goto end
if NOT %1 GTR 0 goto end
setlocal
set sleepfn="%temp%\sleep%random%.vbs"
echo WScript.Sleep(%1) >%sleepfn%
if NOT %sleepfn% == "" if NOT EXIST %sleepfn% goto end
cscript %sleepfn% >nul
if NOT %sleepfn% == "" if EXIST %sleepfn% del %sleepfn%
for /f "usebackq tokens=1*" %%i in (`echo %*`) DO @ set params=%%j
%params%
:end
</code></pre>
| 0 | 2014-01-29T14:01:10Z | [
"python",
"batch-file"
] |
Sleeping in a batch file | 166,044 | <p>When writing a batch file to automate something on a Windows box, I've needed to pause its execution for several seconds (usually in a test/wait loop, waiting for a process to start). At the time, the best solution I could find uses ping (I kid you not) to achieve the desired effect. I've found a better write-up of it <a href="http://malektips.com/dos0017.html">here</a>, which describes a callable "wait.bat", implemented as follows:</p>
<pre><code>@ping 127.0.0.1 -n 2 -w 1000 > nul
@ping 127.0.0.1 -n %1% -w 1000> nul
</code></pre>
<p>You can then include calls to wait.bat in your own batch file, passing in the number of seconds to sleep.</p>
<p><a href="http://malektips.com/xp_dos_0002.html">Apparently the Windows 2003 Resource Kit provides a Unix-like sleep command</a> (at last!). In the meantime, for those of us still using Windows XP, Windows 2000 or (sadly) <a href="http://en.wikipedia.org/wiki/Windows_NT">Windows NT</a>, is there a better way?</p>
<p>I modified the <code>sleep.py</code> script in the <a href="http://stackoverflow.com/questions/166044/sleeping-in-a-dos-batch-file#166290">accepted answer</a>, so that it defaults to one second if no arguments are passed on the command line:</p>
<pre class="lang-py prettyprint-override"><code>import time, sys
time.sleep(float(sys.argv[1]) if len(sys.argv) > 1 else 1)
</code></pre>
| 129 | 2008-10-03T09:10:29Z | 21,586,700 | <p>Guys from my point of view this discussion is going a bit out of topic...
the best solution that should work on all windows versions after 2000 would be:</p>
<pre><code>timeout numbersofseconds /nobreak > nul
</code></pre>
| 2 | 2014-02-05T19:30:27Z | [
"python",
"batch-file"
] |
Sleeping in a batch file | 166,044 | <p>When writing a batch file to automate something on a Windows box, I've needed to pause its execution for several seconds (usually in a test/wait loop, waiting for a process to start). At the time, the best solution I could find uses ping (I kid you not) to achieve the desired effect. I've found a better write-up of it <a href="http://malektips.com/dos0017.html">here</a>, which describes a callable "wait.bat", implemented as follows:</p>
<pre><code>@ping 127.0.0.1 -n 2 -w 1000 > nul
@ping 127.0.0.1 -n %1% -w 1000> nul
</code></pre>
<p>You can then include calls to wait.bat in your own batch file, passing in the number of seconds to sleep.</p>
<p><a href="http://malektips.com/xp_dos_0002.html">Apparently the Windows 2003 Resource Kit provides a Unix-like sleep command</a> (at last!). In the meantime, for those of us still using Windows XP, Windows 2000 or (sadly) <a href="http://en.wikipedia.org/wiki/Windows_NT">Windows NT</a>, is there a better way?</p>
<p>I modified the <code>sleep.py</code> script in the <a href="http://stackoverflow.com/questions/166044/sleeping-in-a-dos-batch-file#166290">accepted answer</a>, so that it defaults to one second if no arguments are passed on the command line:</p>
<pre class="lang-py prettyprint-override"><code>import time, sys
time.sleep(float(sys.argv[1]) if len(sys.argv) > 1 else 1)
</code></pre>
| 129 | 2008-10-03T09:10:29Z | 21,941,058 | <p>There is a better way to sleep using ping. You'll want to ping an address that does not exist, so you can specify a timeout with millisecond precision. Luckily, such an address is defined in a standard (RFC 3330), and it is <code>192.0.2.x</code>. This is not made-up, it really is an address with the sole purpose of not-existing (it may not be clear, but it applies even in local networks):</p>
<blockquote>
<p>192.0.2.0/24 - This block is assigned as "TEST-NET" for use in
documentation and example code. It is often used in conjunction with
domain names example.com or example.net in vendor and protocol
documentation. Addresses within this block should not appear on the
public Internet.</p>
</blockquote>
<p>To sleep for 123 milliseconds, use <strong><code>ping 192.0.2.1 -n 1 -w 123 >nul</code></strong></p>
| 2 | 2014-02-21T17:24:23Z | [
"python",
"batch-file"
] |
Sleeping in a batch file | 166,044 | <p>When writing a batch file to automate something on a Windows box, I've needed to pause its execution for several seconds (usually in a test/wait loop, waiting for a process to start). At the time, the best solution I could find uses ping (I kid you not) to achieve the desired effect. I've found a better write-up of it <a href="http://malektips.com/dos0017.html">here</a>, which describes a callable "wait.bat", implemented as follows:</p>
<pre><code>@ping 127.0.0.1 -n 2 -w 1000 > nul
@ping 127.0.0.1 -n %1% -w 1000> nul
</code></pre>
<p>You can then include calls to wait.bat in your own batch file, passing in the number of seconds to sleep.</p>
<p><a href="http://malektips.com/xp_dos_0002.html">Apparently the Windows 2003 Resource Kit provides a Unix-like sleep command</a> (at last!). In the meantime, for those of us still using Windows XP, Windows 2000 or (sadly) <a href="http://en.wikipedia.org/wiki/Windows_NT">Windows NT</a>, is there a better way?</p>
<p>I modified the <code>sleep.py</code> script in the <a href="http://stackoverflow.com/questions/166044/sleeping-in-a-dos-batch-file#166290">accepted answer</a>, so that it defaults to one second if no arguments are passed on the command line:</p>
<pre class="lang-py prettyprint-override"><code>import time, sys
time.sleep(float(sys.argv[1]) if len(sys.argv) > 1 else 1)
</code></pre>
| 129 | 2008-10-03T09:10:29Z | 24,022,832 | <p>Just use</p>
<blockquote>
<p>timeout /t </p>
</blockquote>
<p>For example, I mostly use it as</p>
<blockquote>
<p>timeout /t 2 /nobreak >NUL</p>
</blockquote>
<p>Which means the script will wait 2 seconds before continuing.
By default, a keystroke will put the timeout to 0 instantly, so put '/nobreak' after it so they can't stop the timeout. Also, >NUL makes the timeout invisible as it typically says how many seconds to go.</p>
| 4 | 2014-06-03T18:55:46Z | [
"python",
"batch-file"
] |
Sleeping in a batch file | 166,044 | <p>When writing a batch file to automate something on a Windows box, I've needed to pause its execution for several seconds (usually in a test/wait loop, waiting for a process to start). At the time, the best solution I could find uses ping (I kid you not) to achieve the desired effect. I've found a better write-up of it <a href="http://malektips.com/dos0017.html">here</a>, which describes a callable "wait.bat", implemented as follows:</p>
<pre><code>@ping 127.0.0.1 -n 2 -w 1000 > nul
@ping 127.0.0.1 -n %1% -w 1000> nul
</code></pre>
<p>You can then include calls to wait.bat in your own batch file, passing in the number of seconds to sleep.</p>
<p><a href="http://malektips.com/xp_dos_0002.html">Apparently the Windows 2003 Resource Kit provides a Unix-like sleep command</a> (at last!). In the meantime, for those of us still using Windows XP, Windows 2000 or (sadly) <a href="http://en.wikipedia.org/wiki/Windows_NT">Windows NT</a>, is there a better way?</p>
<p>I modified the <code>sleep.py</code> script in the <a href="http://stackoverflow.com/questions/166044/sleeping-in-a-dos-batch-file#166290">accepted answer</a>, so that it defaults to one second if no arguments are passed on the command line:</p>
<pre class="lang-py prettyprint-override"><code>import time, sys
time.sleep(float(sys.argv[1]) if len(sys.argv) > 1 else 1)
</code></pre>
| 129 | 2008-10-03T09:10:29Z | 24,990,713 | <pre><code>ping -n X 127.0.0.1>nul
</code></pre>
<p>replace X with the number of seconds +1</p>
<p>example, if u were to wait 10 seconds, replace X with 11
wait 5 seconds, use 6</p>
<p>read earlier answers for miliseconds</p>
| -2 | 2014-07-28T07:51:43Z | [
"python",
"batch-file"
] |
Sleeping in a batch file | 166,044 | <p>When writing a batch file to automate something on a Windows box, I've needed to pause its execution for several seconds (usually in a test/wait loop, waiting for a process to start). At the time, the best solution I could find uses ping (I kid you not) to achieve the desired effect. I've found a better write-up of it <a href="http://malektips.com/dos0017.html">here</a>, which describes a callable "wait.bat", implemented as follows:</p>
<pre><code>@ping 127.0.0.1 -n 2 -w 1000 > nul
@ping 127.0.0.1 -n %1% -w 1000> nul
</code></pre>
<p>You can then include calls to wait.bat in your own batch file, passing in the number of seconds to sleep.</p>
<p><a href="http://malektips.com/xp_dos_0002.html">Apparently the Windows 2003 Resource Kit provides a Unix-like sleep command</a> (at last!). In the meantime, for those of us still using Windows XP, Windows 2000 or (sadly) <a href="http://en.wikipedia.org/wiki/Windows_NT">Windows NT</a>, is there a better way?</p>
<p>I modified the <code>sleep.py</code> script in the <a href="http://stackoverflow.com/questions/166044/sleeping-in-a-dos-batch-file#166290">accepted answer</a>, so that it defaults to one second if no arguments are passed on the command line:</p>
<pre class="lang-py prettyprint-override"><code>import time, sys
time.sleep(float(sys.argv[1]) if len(sys.argv) > 1 else 1)
</code></pre>
| 129 | 2008-10-03T09:10:29Z | 28,957,671 | <p>If you are on guest account, ping will not work from what I experienced. Use the following instead:</p>
<pre><code>timeout /t 5 /nobreak>nul
</code></pre>
<p>This will wait 5 seconds. To allow it to skip from pressing any key, remove /nobreak.</p>
| -3 | 2015-03-10T06:48:22Z | [
"python",
"batch-file"
] |
How can I capture all exceptions from a wxPython application? | 166,198 | <p>I'm writing a little debug app for a bit of kit we're developing and I'd like to roll it out to a few users to see if they can provoke any crashes. Does anyone know a way of effectively wrapping a wxPython app to catch any and all unhandled exceptions that would cause the app to crash?</p>
<p>Ideally I'd want to capture all output (not just errors) and log it to a file. Any unhandled exceptions ought to log to the current file and then allow the exception to pass on as per usual (i.e. the logging process ought to be transparent).</p>
<p>I'm sure someone must have done something along these lines before, but I've not managed to turn up anything that looks useful via google.</p>
| 6 | 2008-10-03T10:11:16Z | 166,213 | <p>There are various ways. You can put a try..catch block in the wxApplication::OnInit, however, that would not always work with Gtk. </p>
<p>A nice alternative would be to override the Application::HandleEvent in your wxApplication derived class, and write a code like this:</p>
<pre><code>void Application::HandleEvent(wxEvtHandler* handler, wxEventFunction func, wxEvent& event) const
{
try
{
wxAppConsole::HandleEvent(handler, func, event);
}
catch (const std::exception& e)
{
wxMessageBox(std2wx(e.what()), _("Unhandled Error"),
wxOK | wxICON_ERROR, wxGetTopLevelParent(wxGetActiveWindow()));
}
}
</code></pre>
<p>It's a C++ example, but you can surely translate to Python easily.</p>
| 1 | 2008-10-03T10:17:48Z | [
"python",
"exception",
"error-handling",
"wxwidgets",
"error-reporting"
] |
How can I capture all exceptions from a wxPython application? | 166,198 | <p>I'm writing a little debug app for a bit of kit we're developing and I'd like to roll it out to a few users to see if they can provoke any crashes. Does anyone know a way of effectively wrapping a wxPython app to catch any and all unhandled exceptions that would cause the app to crash?</p>
<p>Ideally I'd want to capture all output (not just errors) and log it to a file. Any unhandled exceptions ought to log to the current file and then allow the exception to pass on as per usual (i.e. the logging process ought to be transparent).</p>
<p>I'm sure someone must have done something along these lines before, but I've not managed to turn up anything that looks useful via google.</p>
| 6 | 2008-10-03T10:11:16Z | 166,246 | <p>For logging standard output, you can use a stdout wrapper, such as this one:</p>
<pre><code>from __future__ import with_statement
class OutWrapper(object):
def __init__(self, realOutput, logFileName):
self._realOutput = realOutput
self._logFileName = logFileName
def _log(self, text):
with open(self._logFileName, 'a') as logFile:
logFile.write(text)
def write(self, text):
self._log(text)
self._realOutput.write(text)
</code></pre>
<p>You then have to initialize it in your main Python file (the one that runs everything):</p>
<pre><code>import sys
sys.stdout = OutWrapper(sys.stdout, r'c:\temp\log.txt')
</code></pre>
<p>As to logging exceptions, the easiest thing to do is to wrap <code>MainLoop</code> method of wx.App in a try..except, then extract the exception information, save it in some way, and then re-raise the exception through <code>raise</code>, e.g.:</p>
<pre><code>try:
app.MainLoop()
except:
exc_info = sys.exc_info()
saveExcInfo(exc_info) # this method you have to write yourself
raise
</code></pre>
| 6 | 2008-10-03T10:30:07Z | [
"python",
"exception",
"error-handling",
"wxwidgets",
"error-reporting"
] |
How can I capture all exceptions from a wxPython application? | 166,198 | <p>I'm writing a little debug app for a bit of kit we're developing and I'd like to roll it out to a few users to see if they can provoke any crashes. Does anyone know a way of effectively wrapping a wxPython app to catch any and all unhandled exceptions that would cause the app to crash?</p>
<p>Ideally I'd want to capture all output (not just errors) and log it to a file. Any unhandled exceptions ought to log to the current file and then allow the exception to pass on as per usual (i.e. the logging process ought to be transparent).</p>
<p>I'm sure someone must have done something along these lines before, but I've not managed to turn up anything that looks useful via google.</p>
| 6 | 2008-10-03T10:11:16Z | 190,233 | <p>For the exception handling, assuming your log file is opened as log:</p>
<pre><code>import sys
import traceback
def excepthook(type, value, tb):
message = 'Uncaught exception:\n'
message += ''.join(traceback.format_exception(type, value, tb))
log.write(message)
sys.excepthook = excepthook
</code></pre>
| 9 | 2008-10-10T05:30:47Z | [
"python",
"exception",
"error-handling",
"wxwidgets",
"error-reporting"
] |
How can I capture all exceptions from a wxPython application? | 166,198 | <p>I'm writing a little debug app for a bit of kit we're developing and I'd like to roll it out to a few users to see if they can provoke any crashes. Does anyone know a way of effectively wrapping a wxPython app to catch any and all unhandled exceptions that would cause the app to crash?</p>
<p>Ideally I'd want to capture all output (not just errors) and log it to a file. Any unhandled exceptions ought to log to the current file and then allow the exception to pass on as per usual (i.e. the logging process ought to be transparent).</p>
<p>I'm sure someone must have done something along these lines before, but I've not managed to turn up anything that looks useful via google.</p>
| 6 | 2008-10-03T10:11:16Z | 372,826 | <p>You can use</p>
<blockquote>
<p>sys.excepthook</p>
</blockquote>
<p>(see <a href="http://docs.python.org/library/sys.html#sys.excepthook" rel="nofollow">Python docs</a>)</p>
<p>and assign some custom object to it, that would catch all exceptions not caught earlier in your code. You can then log any message to any file you wish, together with traceback and do whatever you like with the exception (reraise it, display error message and allow user to continue using your app etc).</p>
<p>As for logging stdout - the best way for me was to write something similar to DzinX's OutWrapper.</p>
<p>If you're at debugging stage, consider flushing your log files after each entry. This harms performance a lot, but if you manage to cause segfault in some underlying C code, your logs won't mislead you.</p>
| 3 | 2008-12-16T21:33:00Z | [
"python",
"exception",
"error-handling",
"wxwidgets",
"error-reporting"
] |
How to build and deploy Python web applications | 166,334 | <p>I have a Python web application consisting of several Python packages. What is the best way of building and deploying this to the servers?</p>
<p>Currently I'm deploying the packages with Capistrano, installing the packages into a virtualenv with bash, and configuring the servers with puppet, but I would like to go for a more Python based solution.</p>
<p>I've been looking a bit into zc.buildout, but it's not clear for me what I can/should use it for.</p>
| 17 | 2008-10-03T10:57:44Z | 166,788 | <p>Would SCons do what you want?</p>
<p><a href="http://www.scons.org/" rel="nofollow">http://www.scons.org/</a></p>
| 0 | 2008-10-03T13:17:07Z | [
"python",
"deployment"
] |
How to build and deploy Python web applications | 166,334 | <p>I have a Python web application consisting of several Python packages. What is the best way of building and deploying this to the servers?</p>
<p>Currently I'm deploying the packages with Capistrano, installing the packages into a virtualenv with bash, and configuring the servers with puppet, but I would like to go for a more Python based solution.</p>
<p>I've been looking a bit into zc.buildout, but it's not clear for me what I can/should use it for.</p>
| 17 | 2008-10-03T10:57:44Z | 171,395 | <p><a href="http://pypi.python.org/pypi/pyinstall" rel="nofollow">pyinstall</a> looks like it should be a simpler solution for you. At least as far as packaging the python stuff and installing in virtualenv goes. I don't know of a pythonic way to do server configuration...</p>
| 0 | 2008-10-05T02:51:42Z | [
"python",
"deployment"
] |
How to build and deploy Python web applications | 166,334 | <p>I have a Python web application consisting of several Python packages. What is the best way of building and deploying this to the servers?</p>
<p>Currently I'm deploying the packages with Capistrano, installing the packages into a virtualenv with bash, and configuring the servers with puppet, but I would like to go for a more Python based solution.</p>
<p>I've been looking a bit into zc.buildout, but it's not clear for me what I can/should use it for.</p>
| 17 | 2008-10-03T10:57:44Z | 171,396 | <p><a href="http://www.blueskyonmars.com/projects/paver/" rel="nofollow">Paver</a> is a rake/make work alike for python. I don't know if this is what your looking for, still haven't found anything equivalent to puppet for python...</p>
| 1 | 2008-10-05T02:52:37Z | [
"python",
"deployment"
] |
How to build and deploy Python web applications | 166,334 | <p>I have a Python web application consisting of several Python packages. What is the best way of building and deploying this to the servers?</p>
<p>Currently I'm deploying the packages with Capistrano, installing the packages into a virtualenv with bash, and configuring the servers with puppet, but I would like to go for a more Python based solution.</p>
<p>I've been looking a bit into zc.buildout, but it's not clear for me what I can/should use it for.</p>
| 17 | 2008-10-03T10:57:44Z | 171,470 | <p>I use Mercurial as my SCM system, and also for deployment too. It's just a matter of cloning the repository from another one, and then a pull/update or a fetch will get it up to date.</p>
<p>I use several instances of the repository - one on the development server, one (or more, depending upon circumstance) on my local machine, one on the production server, and one 'Master' repository that is available to the greater internet (although only by SSH).</p>
<p>The only thing it doesn't do is automatically update the database if it is changed, but with incoming hooks I could probably do this too.</p>
| 0 | 2008-10-05T04:08:58Z | [
"python",
"deployment"
] |
How to build and deploy Python web applications | 166,334 | <p>I have a Python web application consisting of several Python packages. What is the best way of building and deploying this to the servers?</p>
<p>Currently I'm deploying the packages with Capistrano, installing the packages into a virtualenv with bash, and configuring the servers with puppet, but I would like to go for a more Python based solution.</p>
<p>I've been looking a bit into zc.buildout, but it's not clear for me what I can/should use it for.</p>
| 17 | 2008-10-03T10:57:44Z | 2,779,942 | <p>Depends on what Your infrastructure is. We're just using debian packages and buildbot to make them.</p>
<p>On other setups, I use <a href="http://docs.fabfile.org/" rel="nofollow">Fabric</a> scripts. As for format, I'm just using tbz2 files, but I've heard about people just depoloying eggs.</p>
<p>I'd strongly recommend having proper build and having BuildBot/Hudson to build packages, as using SCM beats the purpose and encourage bad practices. </p>
| 2 | 2010-05-06T09:25:44Z | [
"python",
"deployment"
] |
Django, mod_python, apache and wacky sessions | 166,364 | <p>I am running a Django through mod_python on Apache on a linux box. I have a custom authentication backend, and middleware that requires authentication for all pages, except static content.</p>
<p>My problem is that after I log in, I will still randomly get the log in screen now and again. It seems to me that each apache process has it's own python process, which in turn has it's own internals. So as long as I get served by the same process I logged in to, everything is fine and dandy. But if my request gets served by a different apache process, I am no longer authenticated.</p>
<p>I have checked the HTTP headers I send with FireBug, and they are the same each time, ie. same cookie.</p>
<p>Is this a known issue and are there workarounds/fixes?</p>
<p>Edit: I have a page that displays a lot of generated images. Some off these will not display. This is because they are too behind the authenticating middleware, so they will randomly put up a login image. However, refreshing this page enough times, and it will eventually work, meaning all processes recognize my session.</p>
| 1 | 2008-10-03T11:10:04Z | 166,509 | <p>Do you have standard database-driven sessions? Is caching enabled in settings?</p>
| 0 | 2008-10-03T12:04:32Z | [
"python",
"django",
"apache",
"session",
"mod-python"
] |
Django, mod_python, apache and wacky sessions | 166,364 | <p>I am running a Django through mod_python on Apache on a linux box. I have a custom authentication backend, and middleware that requires authentication for all pages, except static content.</p>
<p>My problem is that after I log in, I will still randomly get the log in screen now and again. It seems to me that each apache process has it's own python process, which in turn has it's own internals. So as long as I get served by the same process I logged in to, everything is fine and dandy. But if my request gets served by a different apache process, I am no longer authenticated.</p>
<p>I have checked the HTTP headers I send with FireBug, and they are the same each time, ie. same cookie.</p>
<p>Is this a known issue and are there workarounds/fixes?</p>
<p>Edit: I have a page that displays a lot of generated images. Some off these will not display. This is because they are too behind the authenticating middleware, so they will randomly put up a login image. However, refreshing this page enough times, and it will eventually work, meaning all processes recognize my session.</p>
| 1 | 2008-10-03T11:10:04Z | 166,539 | <p>You are correct about how Apache handles the processes, and sometimes you'll get served by a different process. You can see this when you make a change to your site; new processes will pick up the change, but old processes will give you the old site. To get consistency, you have to restart Apache.</p>
<p>Assuming a restart doesn't fix the problem, I would guess it's something in the "custom authentication backend" storing part of the authentication in memory (which won't work very well for a web server). I would try setting <code>MaxRequestsPerChild</code> to 1 in your Apache config and seeing if you still get the login screen. If you do, something is being stored in memory, maybe a model not being saved?</p>
<p>Hope that helps!</p>
<p>P.S. Just out of curiosity, why are you using a custom authentication backend and a middleware to ensure the user is logged in? It seems Django's contrib.auth and @login_required would be easier...</p>
| 2 | 2008-10-03T12:15:14Z | [
"python",
"django",
"apache",
"session",
"mod-python"
] |
Django, mod_python, apache and wacky sessions | 166,364 | <p>I am running a Django through mod_python on Apache on a linux box. I have a custom authentication backend, and middleware that requires authentication for all pages, except static content.</p>
<p>My problem is that after I log in, I will still randomly get the log in screen now and again. It seems to me that each apache process has it's own python process, which in turn has it's own internals. So as long as I get served by the same process I logged in to, everything is fine and dandy. But if my request gets served by a different apache process, I am no longer authenticated.</p>
<p>I have checked the HTTP headers I send with FireBug, and they are the same each time, ie. same cookie.</p>
<p>Is this a known issue and are there workarounds/fixes?</p>
<p>Edit: I have a page that displays a lot of generated images. Some off these will not display. This is because they are too behind the authenticating middleware, so they will randomly put up a login image. However, refreshing this page enough times, and it will eventually work, meaning all processes recognize my session.</p>
| 1 | 2008-10-03T11:10:04Z | 171,460 | <p>I highly recommend you don't set MaxRequestsPerChild to 1, as that would cause so much overhead as each process gets killed off and respawns with every request.</p>
<p>Are you using apaches preform MPM or worker MPM? </p>
<p>Take a look at <a href="http://docs.djangoproject.com/en/dev/howto/deployment/modpython/?from=olddocs" rel="nofollow">http://docs.djangoproject.com/en/dev/howto/deployment/modpython/?from=olddocs</a> that may give you some help</p>
| 0 | 2008-10-05T04:00:50Z | [
"python",
"django",
"apache",
"session",
"mod-python"
] |
Django, mod_python, apache and wacky sessions | 166,364 | <p>I am running a Django through mod_python on Apache on a linux box. I have a custom authentication backend, and middleware that requires authentication for all pages, except static content.</p>
<p>My problem is that after I log in, I will still randomly get the log in screen now and again. It seems to me that each apache process has it's own python process, which in turn has it's own internals. So as long as I get served by the same process I logged in to, everything is fine and dandy. But if my request gets served by a different apache process, I am no longer authenticated.</p>
<p>I have checked the HTTP headers I send with FireBug, and they are the same each time, ie. same cookie.</p>
<p>Is this a known issue and are there workarounds/fixes?</p>
<p>Edit: I have a page that displays a lot of generated images. Some off these will not display. This is because they are too behind the authenticating middleware, so they will randomly put up a login image. However, refreshing this page enough times, and it will eventually work, meaning all processes recognize my session.</p>
| 1 | 2008-10-03T11:10:04Z | 699,045 | <p>If you are using some global variables to hold data of your custom authentication session, you need to change this to use either file, database or memcached. As stated above mod_python launches few processes and there's no shared memory between them.</p>
<p>I recommend using memcached for this, also use cookies to store session ID or pass it with as GET parameter so that later you can easily extract session data from the cache. </p>
| 0 | 2009-03-30T21:12:26Z | [
"python",
"django",
"apache",
"session",
"mod-python"
] |
Django, mod_python, apache and wacky sessions | 166,364 | <p>I am running a Django through mod_python on Apache on a linux box. I have a custom authentication backend, and middleware that requires authentication for all pages, except static content.</p>
<p>My problem is that after I log in, I will still randomly get the log in screen now and again. It seems to me that each apache process has it's own python process, which in turn has it's own internals. So as long as I get served by the same process I logged in to, everything is fine and dandy. But if my request gets served by a different apache process, I am no longer authenticated.</p>
<p>I have checked the HTTP headers I send with FireBug, and they are the same each time, ie. same cookie.</p>
<p>Is this a known issue and are there workarounds/fixes?</p>
<p>Edit: I have a page that displays a lot of generated images. Some off these will not display. This is because they are too behind the authenticating middleware, so they will randomly put up a login image. However, refreshing this page enough times, and it will eventually work, meaning all processes recognize my session.</p>
| 1 | 2008-10-03T11:10:04Z | 14,830,843 | <p>How to ensure that session is not cleared after Apache restart( or stop and start) ?</p>
<p>Because when I upgrade my source code and restart Apache, I refresh the web page and there I have to login again. Session is lost. </p>
<p>Session is stored in Memcache. No idea how and why its cleared. How to preserve the session so that the user need not login after the apache restart?</p>
| 0 | 2013-02-12T10:53:25Z | [
"python",
"django",
"apache",
"session",
"mod-python"
] |
Clearing a list | 166,431 | <p>I find it annoying that I can't clear a list. In this example:</p>
<pre><code>a = []
a.append(1)
a.append(2)
a = []
</code></pre>
<p>The second time I initialize a to a blank list, it creates a new instance of a list, which is in a different place in memory, so I can't use it to reference the first, not to mention it's inefficient.</p>
<p>The only way I can see of retaining the same pointer is doing something like the following:</p>
<pre><code>for i in range(len(a)):
a.pop()
</code></pre>
<p>This seems pretty long-winded though, is there a better way of solving this?</p>
| 7 | 2008-10-03T11:37:23Z | 166,441 | <p>You are looking for:</p>
<pre><code>del L[:]
</code></pre>
| 26 | 2008-10-03T11:40:52Z | [
"python",
"memory-management",
"refactoring",
"list"
] |
Clearing a list | 166,431 | <p>I find it annoying that I can't clear a list. In this example:</p>
<pre><code>a = []
a.append(1)
a.append(2)
a = []
</code></pre>
<p>The second time I initialize a to a blank list, it creates a new instance of a list, which is in a different place in memory, so I can't use it to reference the first, not to mention it's inefficient.</p>
<p>The only way I can see of retaining the same pointer is doing something like the following:</p>
<pre><code>for i in range(len(a)):
a.pop()
</code></pre>
<p>This seems pretty long-winded though, is there a better way of solving this?</p>
| 7 | 2008-10-03T11:37:23Z | 166,462 | <p>I'm not sure why you're worried about the fact that you're referencing a new, empty list in memory instead of the same "pointer".</p>
<p>Your other list is going to be collected sooner or later and one of the big perks about working in a high level, garbage-collected language is that you don't normally need to worry about stuff like this.</p>
| 3 | 2008-10-03T11:45:20Z | [
"python",
"memory-management",
"refactoring",
"list"
] |
Finding local IP addresses using Python's stdlib | 166,506 | <p>How can I find local IP addresses (i.e. 192.168.x.x or 10.0.x.x) in Python platform independently and using only the standard library?</p>
| 290 | 2008-10-03T12:03:36Z | 166,520 | <pre><code>import socket
socket.gethostbyname(socket.gethostname())
</code></pre>
<p>This won't work always (returns <code>127.0.0.1</code> on machines having the hostname in <code>/etc/hosts</code> as <code>127.0.0.1</code>), a paliative would be what gimel shows, use <code>socket.getfqdn()</code> instead. Of course your machine needs a resolvable hostname.</p>
| 222 | 2008-10-03T12:06:50Z | [
"python",
"networking",
"ip-address"
] |
Finding local IP addresses using Python's stdlib | 166,506 | <p>How can I find local IP addresses (i.e. 192.168.x.x or 10.0.x.x) in Python platform independently and using only the standard library?</p>
| 290 | 2008-10-03T12:03:36Z | 166,521 | <p>I'm afraid there aren't any good platform independent ways to do this other than connecting to another computer and having it send you your IP address. For example: <a href="http://www.findmyipaddress.info/locateipaddresses.html">findmyipaddress</a>. Note that this won't work if you need an IP address that's behind NAT unless the computer you're connecting to is behind NAT as well.</p>
<p>Here's one solution that works in Linux: <a href="http://code.activestate.com/recipes/439094/">get the IP address associated with a network interface</a>.</p>
| 5 | 2008-10-03T12:07:00Z | [
"python",
"networking",
"ip-address"
] |
Finding local IP addresses using Python's stdlib | 166,506 | <p>How can I find local IP addresses (i.e. 192.168.x.x or 10.0.x.x) in Python platform independently and using only the standard library?</p>
| 290 | 2008-10-03T12:03:36Z | 166,589 | <p>I just found this but it seems a bit hackish, however they say tried it on *nix and I did on windows and it worked.</p>
<pre><code>import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("gmail.com",80))
print(s.getsockname()[0])
s.close()
</code></pre>
<p>This assumes you have an internet access, and that there is no local proxy.</p>
| 226 | 2008-10-03T12:35:13Z | [
"python",
"networking",
"ip-address"
] |
Finding local IP addresses using Python's stdlib | 166,506 | <p>How can I find local IP addresses (i.e. 192.168.x.x or 10.0.x.x) in Python platform independently and using only the standard library?</p>
| 290 | 2008-10-03T12:03:36Z | 166,591 | <p>You can use the <a href="http://pypi.python.org/pypi/netifaces">netifaces</a> module. Just type:</p>
<pre><code>easy_install netifaces
</code></pre>
<p>in your command shell and it will install itself on default Python installation.</p>
<p>Then you can use it like this:</p>
<pre><code>from netifaces import interfaces, ifaddresses, AF_INET
for ifaceName in interfaces():
addresses = [i['addr'] for i in ifaddresses(ifaceName).setdefault(AF_INET, [{'addr':'No IP addr'}] )]
print '%s: %s' % (ifaceName, ', '.join(addresses))
</code></pre>
<p>On my computer it printed:</p>
<pre>{45639BDC-1050-46E0-9BE9-075C30DE1FBC}: 192.168.0.100
{D43A468B-F3AE-4BF9-9391-4863A4500583}: 10.5.9.207</pre>
<p>Author of this module claims it should work on Windows, UNIX and Mac OS X.</p>
| 62 | 2008-10-03T12:35:42Z | [
"python",
"networking",
"ip-address"
] |
Finding local IP addresses using Python's stdlib | 166,506 | <p>How can I find local IP addresses (i.e. 192.168.x.x or 10.0.x.x) in Python platform independently and using only the standard library?</p>
| 290 | 2008-10-03T12:03:36Z | 166,992 | <p>If you don't want to use external packages and don't want to rely on outside Internet servers, this might help. It's a code sample that I found on <a href="http://www.google.com/codesearch?hl=en&lr=&q=getMACAddrWin&sbtn=Search">Google Code Search</a> and modified to return required information:</p>
<pre><code>def getIPAddresses():
from ctypes import Structure, windll, sizeof
from ctypes import POINTER, byref
from ctypes import c_ulong, c_uint, c_ubyte, c_char
MAX_ADAPTER_DESCRIPTION_LENGTH = 128
MAX_ADAPTER_NAME_LENGTH = 256
MAX_ADAPTER_ADDRESS_LENGTH = 8
class IP_ADDR_STRING(Structure):
pass
LP_IP_ADDR_STRING = POINTER(IP_ADDR_STRING)
IP_ADDR_STRING._fields_ = [
("next", LP_IP_ADDR_STRING),
("ipAddress", c_char * 16),
("ipMask", c_char * 16),
("context", c_ulong)]
class IP_ADAPTER_INFO (Structure):
pass
LP_IP_ADAPTER_INFO = POINTER(IP_ADAPTER_INFO)
IP_ADAPTER_INFO._fields_ = [
("next", LP_IP_ADAPTER_INFO),
("comboIndex", c_ulong),
("adapterName", c_char * (MAX_ADAPTER_NAME_LENGTH + 4)),
("description", c_char * (MAX_ADAPTER_DESCRIPTION_LENGTH + 4)),
("addressLength", c_uint),
("address", c_ubyte * MAX_ADAPTER_ADDRESS_LENGTH),
("index", c_ulong),
("type", c_uint),
("dhcpEnabled", c_uint),
("currentIpAddress", LP_IP_ADDR_STRING),
("ipAddressList", IP_ADDR_STRING),
("gatewayList", IP_ADDR_STRING),
("dhcpServer", IP_ADDR_STRING),
("haveWins", c_uint),
("primaryWinsServer", IP_ADDR_STRING),
("secondaryWinsServer", IP_ADDR_STRING),
("leaseObtained", c_ulong),
("leaseExpires", c_ulong)]
GetAdaptersInfo = windll.iphlpapi.GetAdaptersInfo
GetAdaptersInfo.restype = c_ulong
GetAdaptersInfo.argtypes = [LP_IP_ADAPTER_INFO, POINTER(c_ulong)]
adapterList = (IP_ADAPTER_INFO * 10)()
buflen = c_ulong(sizeof(adapterList))
rc = GetAdaptersInfo(byref(adapterList[0]), byref(buflen))
if rc == 0:
for a in adapterList:
adNode = a.ipAddressList
while True:
ipAddr = adNode.ipAddress
if ipAddr:
yield ipAddr
adNode = adNode.next
if not adNode:
break
</code></pre>
<p>Usage:</p>
<pre><code>>>> for addr in getIPAddresses():
>>> print addr
192.168.0.100
10.5.9.207
</code></pre>
<p>As it relies on <code>windll</code>, this will work only on Windows.</p>
| 17 | 2008-10-03T13:54:11Z | [
"python",
"networking",
"ip-address"
] |
Finding local IP addresses using Python's stdlib | 166,506 | <p>How can I find local IP addresses (i.e. 192.168.x.x or 10.0.x.x) in Python platform independently and using only the standard library?</p>
| 290 | 2008-10-03T12:03:36Z | 1,267,524 | <pre class="lang-py prettyprint-override"><code>import socket
print([ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith("127.")][:1])
</code></pre>
<p>I'm using this, because one of the computers I was on had an /etc/hosts with duplicate entries and references to itself. socket.gethostbyname() only returns the last entry in /etc/hosts. This solution weeds out the ones starting with "127.".
Works with Python 3 and 2.5, possibly other versions too. Does not deal with several network devices or IPv6. Works on Linux and Windows.</p>
<p><strong>Update:</strong> The above technique stopped working on recent Linux distros. This can be used instead:</p>
<pre class="lang-py prettyprint-override"><code>import socket
print([(s.connect(('8.8.8.8', 53)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1])
</code></pre>
<p><strong>Update:</strong> Created a long one-liner that combines the two one-liners above. Should work everywhere (Linux, Windows, OS X, Python 2.x and Python 3):</p>
<pre><code>import socket
print([l for l in ([ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith("127.")][:1], [[(s.connect(('8.8.8.8', 53)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1]]) if l][0][0])
</code></pre>
<p>Note that this may throw an exception if no IP is configured.</p>
<p>As an alias:</p>
<p><code>alias myip="python -c 'import socket; print([l for l in ([ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith(\"127.\")][:1], [[(s.connect((\"8.8.8.8\", 53)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1]]) if l][0][0])'"</code></p>
| 100 | 2009-08-12T17:20:38Z | [
"python",
"networking",
"ip-address"
] |
Finding local IP addresses using Python's stdlib | 166,506 | <p>How can I find local IP addresses (i.e. 192.168.x.x or 10.0.x.x) in Python platform independently and using only the standard library?</p>
| 290 | 2008-10-03T12:03:36Z | 1,947,766 | <p>im using following module:</p>
<pre><code>#!/usr/bin/python
# module for getting the lan ip address of the computer
import os
import socket
if os.name != "nt":
import fcntl
import struct
def get_interface_ip(ifname):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
return socket.inet_ntoa(fcntl.ioctl(
s.fileno(),
0x8915, # SIOCGIFADDR
struct.pack('256s', bytes(ifname[:15], 'utf-8'))
# Python 2.7: remove the second argument for the bytes call
)[20:24])
def get_lan_ip():
ip = socket.gethostbyname(socket.gethostname())
if ip.startswith("127.") and os.name != "nt":
interfaces = ["eth0","eth1","eth2","wlan0","wlan1","wifi0","ath0","ath1","ppp0"]
for ifname in interfaces:
try:
ip = get_interface_ip(ifname)
break;
except IOError:
pass
return ip
</code></pre>
<p>Tested with windows and linux (and doesnt require additional modules for those)
intended for use on systems which are in a single IPv4 based LAN.</p>
<p>The fixed list of interface names does not work for recent linux versions, which have adopted the systemd v197 change regarding predictable interface names as pointed out by <a href="https://stackoverflow.com/questions/166506/finding-local-ip-addresses-using-pythons-stdlib/1947766?noredirect=1#comment35654143_1947766">Alexander</a>.
In such cases, you need to manually replace the list with the interface names on your system, or use another solution like <a href="http://alastairs-place.net/projects/netifaces/" rel="nofollow">netifaces</a>.</p>
| 21 | 2009-12-22T17:07:58Z | [
"python",
"networking",
"ip-address"
] |
Finding local IP addresses using Python's stdlib | 166,506 | <p>How can I find local IP addresses (i.e. 192.168.x.x or 10.0.x.x) in Python platform independently and using only the standard library?</p>
| 290 | 2008-10-03T12:03:36Z | 1,980,854 | <p>FYI I can verify that the method:</p>
<pre><code>import socket
addr = socket.gethostbyname(socket.gethostname())
</code></pre>
<p>Works in OS X (10.6,10.5), Windows XP, and on a well administered RHEL department server. It did not work on a very minimal CentOS VM that I just do some kernel hacking on. So for that instance you can just check for a 127.0.0.1 address and in that case do the following:</p>
<pre><code>if addr == "127.0.0.1":
import commands
output = commands.getoutput("/sbin/ifconfig")
addr = parseaddress(output)
</code></pre>
<p>And then parse the ip address from the output. It should be noted that ifconfig is not in a normal user's PATH by default and that is why I give the full path in the command. I hope this helps.</p>
| 5 | 2009-12-30T15:51:21Z | [
"python",
"networking",
"ip-address"
] |
Finding local IP addresses using Python's stdlib | 166,506 | <p>How can I find local IP addresses (i.e. 192.168.x.x or 10.0.x.x) in Python platform independently and using only the standard library?</p>
| 290 | 2008-10-03T12:03:36Z | 3,177,266 | <p>I use this on my ubuntu machines:</p>
<pre><code>import commands
commands.getoutput("/sbin/ifconfig").split("\n")[1].split()[1][5:]
</code></pre>
| 26 | 2010-07-05T04:45:47Z | [
"python",
"networking",
"ip-address"
] |
Finding local IP addresses using Python's stdlib | 166,506 | <p>How can I find local IP addresses (i.e. 192.168.x.x or 10.0.x.x) in Python platform independently and using only the standard library?</p>
| 290 | 2008-10-03T12:03:36Z | 5,111,878 | <p>For a list of IP addresses on *nix systems,</p>
<pre><code>import subprocess
co = subprocess.Popen(['ifconfig'], stdout = subprocess.PIPE)
ifconfig = co.stdout.read()
ip_regex = re.compile('((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-4]|2[0-5][0-9]|[01]?[0-9][0-9]?))')
[match[0] for match in ip_regex.findall(ifconfig, re.MULTILINE)]
</code></pre>
<p>Though it's a bit late for this answer, I thought someone else may find it useful :-)</p>
<p>PS : It'll return Broadcast addresses and Netmask as well.</p>
| 1 | 2011-02-24T23:31:49Z | [
"python",
"networking",
"ip-address"
] |
Finding local IP addresses using Python's stdlib | 166,506 | <p>How can I find local IP addresses (i.e. 192.168.x.x or 10.0.x.x) in Python platform independently and using only the standard library?</p>
| 290 | 2008-10-03T12:03:36Z | 6,327,620 | <p>One simple way to produce "clean" output via command line utils:</p>
<pre><code>import commands
ips = commands.getoutput("/sbin/ifconfig | grep -i \"inet\" | grep -iv \"inet6\" | " +
"awk {'print $2'} | sed -ne 's/addr\:/ /p'")
print ips
</code></pre>
<p>It will show all IPv4 addresses on the system.</p>
| 8 | 2011-06-13T07:21:56Z | [
"python",
"networking",
"ip-address"
] |
Finding local IP addresses using Python's stdlib | 166,506 | <p>How can I find local IP addresses (i.e. 192.168.x.x or 10.0.x.x) in Python platform independently and using only the standard library?</p>
| 290 | 2008-10-03T12:03:36Z | 6,452,999 | <p>A machine can have multiple network interfaces (including the local loopback 127.0.0.1) you mentioned. As far as the OS is concerned, it's also a "real IP address". </p>
<p>If you want to track all of interfaces, have a look at the following Puthon package : <a href="http://alastairs-place.net/netifaces/" rel="nofollow">http://alastairs-place.net/netifaces/</a></p>
<p>I think you can avoid having gethostbyname return 127.0.0.1 if you ommit the loopback entry from your hosts file. (to be verified).</p>
| 0 | 2011-06-23T11:02:21Z | [
"python",
"networking",
"ip-address"
] |
Finding local IP addresses using Python's stdlib | 166,506 | <p>How can I find local IP addresses (i.e. 192.168.x.x or 10.0.x.x) in Python platform independently and using only the standard library?</p>
| 290 | 2008-10-03T12:03:36Z | 6,453,024 | <p><code>127.0.1.1</code> <em>is</em> your real IP address. More generally speaking, a computer can have any number of IP addresses. You can filter them for private networks - 127.0.0.0/8, 10.0.0.0/8, 172.16.0.0/12 and 192.168.0.0/16.</p>
<p>However, there is no cross-platform way to get all IP addresses. On Linux, you can use the <a href="http://linux.die.net/man/7/netdevice" rel="nofollow"><code>SIOCGIFCONF</code></a> ioctl.</p>
| 3 | 2011-06-23T11:04:19Z | [
"python",
"networking",
"ip-address"
] |
Finding local IP addresses using Python's stdlib | 166,506 | <p>How can I find local IP addresses (i.e. 192.168.x.x or 10.0.x.x) in Python platform independently and using only the standard library?</p>
| 290 | 2008-10-03T12:03:36Z | 6,453,053 | <p><strong>Socket API method</strong></p>
<pre><code>import socket
# from http://commandline.org.uk/python/how-to-find-out-ip-address-in-python/
def getNetworkIp():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(('INSERT SOME TARGET WEBSITE.com', 0))
return s.getsockname()[0]
</code></pre>
<p>Downsides:</p>
<ul>
<li><em>Not cross-platform.</em></li>
<li>Requires more fallback code, tied to existence of particular addresses on the internet</li>
<li>This will also not work if you're behind a NAT</li>
<li>Probably creates a UDP connection, not independent of (usually ISP's) DNS availability (see other answers for ideas like using 8.8.8.8: Google's (coincidentally also DNS) server)</li>
<li>Very poor form to incorporate third-party dependency (like <code>google.com</code>) in code as a means of specifying the network interface, unless you specifically want the public IP of the interface which will route you to the specific website you want. <strong>Spamming innocent third parties is bad. Bad. BAD.</strong></li>
</ul>
<hr>
<p><strong>Reflector method</strong></p>
<p>(Do note that this does not answer the OP's question of the local IP address, e.g. 192.168...; it gives you your public IP address, which might be more desirable depending on use case.)</p>
<p>You can query some site like whatismyip.com (but with an API), such as:</p>
<pre><code>from urllib.request import urlopen
import re
def getPublicIp():
data = str(urlopen('http://checkip.dyndns.com/').read())
# data = '<html><head><title>Current IP Check</title></head><body>Current IP Address: 65.96.168.198</body></html>\r\n'
return re.compile(r'Address: (\d+\.\d+\.\d+\.\d+)').search(data).group(1)
</code></pre>
<p>or if using python2:</p>
<pre><code>from urllib import urlopen
import re
def getPublicIp():
data = str(urlopen('http://checkip.dyndns.com/').read())
# data = '<html><head><title>Current IP Check</title></head><body>Current IP Address: 65.96.168.198</body></html>\r\n'
return re.compile(r'Address: (\d+\.\d+\.\d+\.\d+)').search(data).group(1)
</code></pre>
<p>Advantages:</p>
<ul>
<li>One upside of this method is it's cross-platform</li>
<li>It works from behind ugly NATs (e.g. your home router).</li>
</ul>
<p>Disadvantages (and workarounds):</p>
<ul>
<li>Requires this website to be up, the format to not change (almost certainly won't), and your DNS servers to be working. One can mitigate this issue by also querying other third-party IP address reflectors in case of failure.</li>
<li>Possible attack vector if you don't query multiple reflectors (to prevent a compromised reflector from telling you that your address is something it's not), or if you don't use HTTPS (to prevent a man-in-the-middle attack pretending to be the server)</li>
</ul>
<hr>
<p><em>edit</em>: Though initially I thought these methods were really bad (unless you use many fallbacks, the code may be irrelevant many years from now), it does pose the question "what is the internet?". A computer may have many interfaces pointing to many different networks. For a more thorough description of the topic, google for <code>gateways and routes</code>. A computer may be able to access an internal network via an internal gateway, or access the world-wide web via a gateway on for example a router (usually the case). The local IP address that the OP asks about is only well-defined with respect to a single link layer, so you have to specify that ("is it the network card, or the ethernet cable, which we're talking about?"). There may be multiple non-unique answers to this question as posed. However the global IP address on the world-wide web is probably well-defined (in the absence of massive network fragmentation): probably the return path via the gateway which can access the TLDs.</p>
| 43 | 2011-06-23T11:07:11Z | [
"python",
"networking",
"ip-address"
] |
Finding local IP addresses using Python's stdlib | 166,506 | <p>How can I find local IP addresses (i.e. 192.168.x.x or 10.0.x.x) in Python platform independently and using only the standard library?</p>
| 290 | 2008-10-03T12:03:36Z | 9,267,833 | <p>On Linux:</p>
<pre><code>>>> import socket, struct, fcntl
>>> sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
>>> sockfd = sock.fileno()
>>> SIOCGIFADDR = 0x8915
>>>
>>> def get_ip(iface = 'eth0'):
... ifreq = struct.pack('16sH14s', iface, socket.AF_INET, '\x00'*14)
... try:
... res = fcntl.ioctl(sockfd, SIOCGIFADDR, ifreq)
... except:
... return None
... ip = struct.unpack('16sH2x4s8x', res)[2]
... return socket.inet_ntoa(ip)
...
>>> get_ip('eth0')
'10.80.40.234'
>>>
</code></pre>
| 33 | 2012-02-13T20:52:31Z | [
"python",
"networking",
"ip-address"
] |
Finding local IP addresses using Python's stdlib | 166,506 | <p>How can I find local IP addresses (i.e. 192.168.x.x or 10.0.x.x) in Python platform independently and using only the standard library?</p>
| 290 | 2008-10-03T12:03:36Z | 10,192,097 | <p>Ok so this is Windows specific, and requires the installation of the <a href="http://timgolden.me.uk/python/wmi/index.html" rel="nofollow">python WMI module</a>, but it seems much less hackish than constantly trying to call an external server. It's just another option, as there are already many good ones, but it might be a good fit for your project.</p>
<pre><code>Import WMI
def getlocalip():
local = wmi.WMI()
for interface in local.Win32_NetworkAdapterConfiguration(IPEnabled=1):
for ip_address in interface.IPAddress:
if ip_address != '0.0.0.0':
localip = ip_address
return localip
>>>getlocalip()
u'xxx.xxx.xxx.xxx'
>>>
</code></pre>
<p>By the way, WMI is very powerful... if you are doing any remote admin of window machines you should definitely check out what it can do.</p>
| 0 | 2012-04-17T13:21:38Z | [
"python",
"networking",
"ip-address"
] |
Finding local IP addresses using Python's stdlib | 166,506 | <p>How can I find local IP addresses (i.e. 192.168.x.x or 10.0.x.x) in Python platform independently and using only the standard library?</p>
| 290 | 2008-10-03T12:03:36Z | 10,325,724 | <p>I had to solve the problem "Figure out if an IP address is local or not", and my first thought was to build a list of IPs that were local and then match against it. This is what led me to this question. However, I later realized there is a more straightfoward way to do it: Try to bind on that IP and see if it works.</p>
<pre><code>_local_ip_cache = []
_nonlocal_ip_cache = []
def ip_islocal(ip):
if ip in _local_ip_cache:
return True
if ip in _nonlocal_ip_cache:
return False
s = socket.socket()
try:
try:
s.bind((ip, 0))
except socket.error, e:
if e.args[0] == errno.EADDRNOTAVAIL:
_nonlocal_ip_cache.append(ip)
return False
else:
raise
finally:
s.close()
_local_ip_cache.append(ip)
return True
</code></pre>
<p>I know this doesn't answer the question directly, but this should be helpful to anyone trying to solve the related question and who was following the same train of thought. This has the advantage of being a cross-platform solution (I think).</p>
| 2 | 2012-04-26T00:32:06Z | [
"python",
"networking",
"ip-address"
] |
Finding local IP addresses using Python's stdlib | 166,506 | <p>How can I find local IP addresses (i.e. 192.168.x.x or 10.0.x.x) in Python platform independently and using only the standard library?</p>
| 290 | 2008-10-03T12:03:36Z | 10,350,424 | <p>This will work on most linux boxes:</p>
<pre><code>import socket, subprocess, re
def get_ipv4_address():
"""
Returns IP address(es) of current machine.
:return:
"""
p = subprocess.Popen(["ifconfig"], stdout=subprocess.PIPE)
ifc_resp = p.communicate()
patt = re.compile(r'inet\s*\w*\S*:\s*(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})')
resp = patt.findall(ifc_resp[0])
print resp
get_ipv4_address()
</code></pre>
| 4 | 2012-04-27T12:14:01Z | [
"python",
"networking",
"ip-address"
] |
Finding local IP addresses using Python's stdlib | 166,506 | <p>How can I find local IP addresses (i.e. 192.168.x.x or 10.0.x.x) in Python platform independently and using only the standard library?</p>
| 290 | 2008-10-03T12:03:36Z | 10,377,262 | <p>A slight refinement of the commands version that uses the IP command, and returns IPv4 and IPv6 addresses:</p>
<pre><code>import commands,re,socket
#A generator that returns stripped lines of output from "ip address show"
iplines=(line.strip() for line in commands.getoutput("ip address show").split('\n'))
#Turn that into a list of IPv4 and IPv6 address/mask strings
addresses1=reduce(lambda a,v:a+v,(re.findall(r"inet ([\d.]+/\d+)",line)+re.findall(r"inet6 ([\:\da-f]+/\d+)",line) for line in iplines))
#addresses1 now looks like ['127.0.0.1/8', '::1/128', '10.160.114.60/23', 'fe80::1031:3fff:fe00:6dce/64']
#Get a list of IPv4 addresses as (IPstring,subnetsize) tuples
ipv4s=[(ip,int(subnet)) for ip,subnet in (addr.split('/') for addr in addresses1 if '.' in addr)]
#ipv4s now looks like [('127.0.0.1', 8), ('10.160.114.60', 23)]
#Get IPv6 addresses
ipv6s=[(ip,int(subnet)) for ip,subnet in (addr.split('/') for addr in addresses1 if ':' in addr)]
</code></pre>
| 3 | 2012-04-30T00:32:34Z | [
"python",
"networking",
"ip-address"
] |
Finding local IP addresses using Python's stdlib | 166,506 | <p>How can I find local IP addresses (i.e. 192.168.x.x or 10.0.x.x) in Python platform independently and using only the standard library?</p>
| 290 | 2008-10-03T12:03:36Z | 10,750,359 | <p>Another option is to ping whatismyip</p>
<p>the below script will return your public ip as a string - advantage is that they allow this
<a href="http://www.whatismyip.com/faq/automation.asp" rel="nofollow">http://www.whatismyip.com/faq/automation.asp</a></p>
<pre><code>def findIP():
headers = { 'User-Agent' : 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:12.0)' \
+ ' Gecko/20100101 Firefox/12.0' }
return = urllib2.urlopen(
urllib2.Request(
"http://automation.whatismyip.com/n09230945.asp",
None, headers )
).read()
</code></pre>
<p>executable version available at
<a href="https://gist.github.com/2786450" rel="nofollow">https://gist.github.com/2786450</a></p>
| 0 | 2012-05-25T07:35:08Z | [
"python",
"networking",
"ip-address"
] |
Finding local IP addresses using Python's stdlib | 166,506 | <p>How can I find local IP addresses (i.e. 192.168.x.x or 10.0.x.x) in Python platform independently and using only the standard library?</p>
| 290 | 2008-10-03T12:03:36Z | 10,946,468 | <pre><code>import socket
socket.gethostbyname(socket.getfqdn())
</code></pre>
| 3 | 2012-06-08T09:42:20Z | [
"python",
"networking",
"ip-address"
] |
Finding local IP addresses using Python's stdlib | 166,506 | <p>How can I find local IP addresses (i.e. 192.168.x.x or 10.0.x.x) in Python platform independently and using only the standard library?</p>
| 290 | 2008-10-03T12:03:36Z | 10,992,813 | <p>This answer is my personal attempt to solve the problem of getting the LAN IP, since <code>socket.gethostbyname(socket.gethostname())</code> also returned 127.0.0.1. This method does not require Internet just a LAN connection. Code is for Python 3.x but could easily be converted for 2.x. Using UDP Broadcast:</p>
<pre><code>import select
import socket
import threading
from queue import Queue, Empty
def get_local_ip():
def udp_listening_server():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind(('<broadcast>', 8888))
s.setblocking(0)
while True:
result = select.select([s],[],[])
msg, address = result[0][0].recvfrom(1024)
msg = str(msg, 'UTF-8')
if msg == 'What is my LAN IP address?':
break
queue.put(address)
queue = Queue()
thread = threading.Thread(target=udp_listening_server)
thread.queue = queue
thread.start()
s2 = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s2.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
waiting = True
while waiting:
s2.sendto(bytes('What is my LAN IP address?', 'UTF-8'), ('<broadcast>', 8888))
try:
address = queue.get(False)
except Empty:
pass
else:
waiting = False
return address[0]
if __name__ == '__main__':
print(get_local_ip())
</code></pre>
| 3 | 2012-06-12T08:15:13Z | [
"python",
"networking",
"ip-address"
] |
Finding local IP addresses using Python's stdlib | 166,506 | <p>How can I find local IP addresses (i.e. 192.168.x.x or 10.0.x.x) in Python platform independently and using only the standard library?</p>
| 290 | 2008-10-03T12:03:36Z | 16,412,954 | <pre><code>import socket
[i[4][0] for i in socket.getaddrinfo(socket.gethostname(), None)]
</code></pre>
| 4 | 2013-05-07T06:54:33Z | [
"python",
"networking",
"ip-address"
] |
Finding local IP addresses using Python's stdlib | 166,506 | <p>How can I find local IP addresses (i.e. 192.168.x.x or 10.0.x.x) in Python platform independently and using only the standard library?</p>
| 290 | 2008-10-03T12:03:36Z | 18,542,718 | <p>Note: This is not using the standard library, but quite simple.</p>
<p>$ pip install pif</p>
<pre><code>from pif import get_public_ip
get_public_ip()
</code></pre>
| 1 | 2013-08-30T23:09:13Z | [
"python",
"networking",
"ip-address"
] |
Finding local IP addresses using Python's stdlib | 166,506 | <p>How can I find local IP addresses (i.e. 192.168.x.x or 10.0.x.x) in Python platform independently and using only the standard library?</p>
| 290 | 2008-10-03T12:03:36Z | 20,275,076 | <p>Well you can use the command "ip route" on GNU/Linux to know your current IP address.</p>
<p>This shows the IP given to the interface by the DHCP server running on the router/modem. Usually "192.168.1.1/24" is the IP for local network where "24" means the range of posible IP addresses given by the DHCP server within the mask range.</p>
<p>Here's an example: Note that PyNotify is just an addition to get my point straight and is not required at all</p>
<pre><code>#! /usr/bin/env python
import sys , pynotify
if sys.version_info[1] != 7:
raise RuntimeError('Python 2.7 And Above Only')
from subprocess import check_output # Available on Python 2.7+ | N/A
IP = check_output(['ip', 'route'])
Split_Result = IP.split()
# print Split_Result[2] # Remove "#" to enable
pynotify.init("image")
notify = pynotify.Notification("Ip", "Server Running At:" + Split_Result[2] , "/home/User/wireless.png")
notify.show()
</code></pre>
<p>The advantage of this is that you don't need to specify the network interface. That's pretty useful when running a socket server</p>
<p>You can install PyNotify using easy_install or even Pip:</p>
<pre><code>easy_install py-notify
</code></pre>
<p>or</p>
<pre><code>pip install py-notify
</code></pre>
<p>or within python script/interpreter</p>
<pre><code>from pip import main
main(['install', 'py-notify'])
</code></pre>
| 2 | 2013-11-28T21:37:56Z | [
"python",
"networking",
"ip-address"
] |
Finding local IP addresses using Python's stdlib | 166,506 | <p>How can I find local IP addresses (i.e. 192.168.x.x or 10.0.x.x) in Python platform independently and using only the standard library?</p>
| 290 | 2008-10-03T12:03:36Z | 20,312,936 | <p>Simple yet sweet!</p>
<pre><code>def getip():
import socket
hostname= socket.gethostname()
ip=socket.gethostbyname(hostname)
return(ip)
</code></pre>
| 0 | 2013-12-01T14:02:04Z | [
"python",
"networking",
"ip-address"
] |
Finding local IP addresses using Python's stdlib | 166,506 | <p>How can I find local IP addresses (i.e. 192.168.x.x or 10.0.x.x) in Python platform independently and using only the standard library?</p>
| 290 | 2008-10-03T12:03:36Z | 20,710,035 | <p>This is a variant of UnkwnTech's answer -- it provides a <code>get_local_addr()</code> function, which returns the primary LAN ip address of the host. I'm posting it because this adds a number of things: ipv6 support, error handling, ignoring localhost/linklocal addrs, and uses a TESTNET addr (rfc5737) to connect to.</p>
<pre><code># imports
import errno
import socket
# localhost prefixes
_local_networks = ("127.", "0:0:0:0:0:0:0:1")
# ignore these prefixes -- localhost, unspecified, and link-local
_ignored_networks = _local_networks + ("0.", "0:0:0:0:0:0:0:0", "169.254.", "fe80:")
def detect_family(addr):
if "." in addr:
assert ":" not in addr
return socket.AF_INET
elif ":" in addr:
return socket.AF_INET6
else:
raise ValueError("invalid ipv4/6 address: %r" % addr)
def expand_addr(addr):
"""convert address into canonical expanded form --
no leading zeroes in groups, and for ipv6: lowercase hex, no collapsed groups.
"""
family = detect_family(addr)
addr = socket.inet_ntop(family, socket.inet_pton(family, addr))
if "::" in addr:
count = 8-addr.count(":")
addr = addr.replace("::", (":0" * count) + ":")
if addr.startswith(":"):
addr = "0" + addr
return addr
def _get_local_addr(family, remote):
try:
s = socket.socket(family, socket.SOCK_DGRAM)
try:
s.connect((remote, 9))
return s.getsockname()[0]
finally:
s.close()
except socket.error:
return None
def get_local_addr(remote=None, ipv6=True):
"""get LAN address of host
:param remote:
return LAN address that host would use to access that specific remote address.
by default, returns address it would use to access the public internet.
:param ipv6:
by default, attempts to find an ipv6 address first.
if set to False, only checks ipv4.
:returns:
primary LAN address for host, or ``None`` if couldn't be determined.
"""
if remote:
family = detect_family(remote)
local = _get_local_addr(family, remote)
if not local:
return None
if family == socket.AF_INET6:
# expand zero groups so the startswith() test works.
local = expand_addr(local)
if local.startswith(_local_networks):
# border case where remote addr belongs to host
return local
else:
# NOTE: the two addresses used here are TESTNET addresses,
# which should never exist in the real world.
if ipv6:
local = _get_local_addr(socket.AF_INET6, "2001:db8::1234")
# expand zero groups so the startswith() test works.
if local:
local = expand_addr(local)
else:
local = None
if not local:
local = _get_local_addr(socket.AF_INET, "192.0.2.123")
if not local:
return None
if local.startswith(_ignored_networks):
return None
return local
</code></pre>
| 4 | 2013-12-20T18:41:48Z | [
"python",
"networking",
"ip-address"
] |
Finding local IP addresses using Python's stdlib | 166,506 | <p>How can I find local IP addresses (i.e. 192.168.x.x or 10.0.x.x) in Python platform independently and using only the standard library?</p>
| 290 | 2008-10-03T12:03:36Z | 23,822,431 | <p>Variation on ninjagecko's answer. This should work on any LAN that allows UDP broadcast and doesn't require access to an address on the LAN or internet.</p>
<pre><code>import socket
def getNetworkIp():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
s.connect(('<broadcast>', 0))
return s.getsockname()[0]
print (getNetworkIp())
</code></pre>
| 3 | 2014-05-23T06:30:58Z | [
"python",
"networking",
"ip-address"
] |
Finding local IP addresses using Python's stdlib | 166,506 | <p>How can I find local IP addresses (i.e. 192.168.x.x or 10.0.x.x) in Python platform independently and using only the standard library?</p>
| 290 | 2008-10-03T12:03:36Z | 24,171,358 | <p>netifaces is available via pip and easy_install. (I know, it's not in base, but it could be worth the install.)</p>
<p>netifaces does have some oddities across platforms:</p>
<ul>
<li>The localhost/loop-back interface may not always be included (Cygwin).</li>
<li>Addresses are listed per-protocol (e.g., IPv4, IPv6) and protocols are listed per-interface. On some systems (Linux) each protocol-interface pair has its own associated interface (using the interface_name:n notation) while on other systems (Windows) a single interface will have a list of addresses for each protocol. In both cases there is a protocol list, but it may contain only a single element.</li>
</ul>
<p>Here's some netifaces code to play with:</p>
<pre><code>import netifaces
PROTO = netifaces.AF_INET # We want only IPv4, for now at least
# Get list of network interfaces
# Note: Can't filter for 'lo' here because Windows lacks it.
ifaces = netifaces.interfaces()
# Get all addresses (of all kinds) for each interface
if_addrs = [netifaces.ifaddresses(iface) for iface in ifaces]
# Filter for the desired address type
if_inet_addrs = [addr[PROTO] for addr in if_addrs if PROTO in addr]
iface_addrs = [s['addr'] for a in if_inet_addrs for s in a if 'addr' in s]
# Can filter for '127.0.0.1' here.
</code></pre>
<p>The above code doesn't map an address back to its interface name (useful for generating ebtables/iptables rules on the fly). So here's a version that keeps the above information with the interface name in a tuple:</p>
<pre><code>import netifaces
PROTO = netifaces.AF_INET # We want only IPv4, for now at least
# Get list of network interfaces
ifaces = netifaces.interfaces()
# Get addresses for each interface
if_addrs = [(netifaces.ifaddresses(iface), iface) for iface in ifaces]
# Filter for only IPv4 addresses
if_inet_addrs = [(tup[0][PROTO], tup[1]) for tup in if_addrs if PROTO in tup[0]]
iface_addrs = [(s['addr'], tup[1]) for tup in if_inet_addrs for s in tup[0] if 'addr' in s]
</code></pre>
<p>And, no, I'm not in love with list comprehensions. It's just the way my brain works these days.</p>
<p>The following snippet will print it all out:</p>
<pre><code>from __future__ import print_function # For 2.x folks
from pprint import pprint as pp
print('\nifaces = ', end='')
pp(ifaces)
print('\nif_addrs = ', end='')
pp(if_addrs)
print('\nif_inet_addrs = ', end='')
pp(if_inet_addrs)
print('\niface_addrs = ', end='')
pp(iface_addrs)
</code></pre>
<p>Enjoy!</p>
| 2 | 2014-06-11T19:47:26Z | [
"python",
"networking",
"ip-address"
] |
Finding local IP addresses using Python's stdlib | 166,506 | <p>How can I find local IP addresses (i.e. 192.168.x.x or 10.0.x.x) in Python platform independently and using only the standard library?</p>
| 290 | 2008-10-03T12:03:36Z | 24,564,613 | <p>On Debian (tested) and I suspect most Linux's..</p>
<pre><code>import commands
RetMyIP = commands.getoutput("hostname -I")
</code></pre>
<p>On MS Windows (tested) </p>
<pre><code>import socket
socket.gethostbyname(socket.gethostname())
</code></pre>
| 7 | 2014-07-03T23:19:34Z | [
"python",
"networking",
"ip-address"
] |
Finding local IP addresses using Python's stdlib | 166,506 | <p>How can I find local IP addresses (i.e. 192.168.x.x or 10.0.x.x) in Python platform independently and using only the standard library?</p>
| 290 | 2008-10-03T12:03:36Z | 25,850,698 | <p>If the computer has a route to the Internet, this will <em>always</em> work to get the preferred local ip address, even if /etc/hosts is not set correctly.</p>
<pre><code>import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(('8.8.8.8', 0)) # connecting to a UDP address doesn't send packets
local_ip_address = s.getsockname()[0]
</code></pre>
| 34 | 2014-09-15T14:43:47Z | [
"python",
"networking",
"ip-address"
] |
Finding local IP addresses using Python's stdlib | 166,506 | <p>How can I find local IP addresses (i.e. 192.168.x.x or 10.0.x.x) in Python platform independently and using only the standard library?</p>
| 290 | 2008-10-03T12:03:36Z | 27,788,672 | <p>A version I do not believe that has been posted yet.
I tested with python 2.7 on Ubuntu 12.04.</p>
<p>Found this solution at : <a href="http://code.activestate.com/recipes/439094-get-the-ip-address-associated-with-a-network-inter/">http://code.activestate.com/recipes/439094-get-the-ip-address-associated-with-a-network-inter/</a></p>
<pre><code>import socket
import fcntl
import struct
def get_ip_address(ifname):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
return socket.inet_ntoa(fcntl.ioctl(
s.fileno(),
0x8915, # SIOCGIFADDR
struct.pack('256s', ifname[:15])
)[20:24])
</code></pre>
<p>Example Result:</p>
<blockquote>
<blockquote>
<blockquote>
<p>get_ip_address('eth0')
'38.113.228.130'</p>
</blockquote>
</blockquote>
</blockquote>
| 8 | 2015-01-05T22:03:07Z | [
"python",
"networking",
"ip-address"
] |
Finding local IP addresses using Python's stdlib | 166,506 | <p>How can I find local IP addresses (i.e. 192.168.x.x or 10.0.x.x) in Python platform independently and using only the standard library?</p>
| 290 | 2008-10-03T12:03:36Z | 28,950,776 | <p>This works on Linux and Windows on both Python 2 and 3. Requires a working local interface with a default route (0.0.0.0), but that's it - no routable net access necessary, doesn't try or need to be able to actually <em>get</em> anywhere else. (This combines a bunch of ideas from above with modifications to not need external access.)</p>
<pre><code>import socket
def get_ip():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
# doesn't even have to be reachable
s.connect(('10.255.255.255', 0))
IP = s.getsockname()[0]
except:
IP = '127.0.0.1'
finally:
s.close()
return IP
</code></pre>
| 18 | 2015-03-09T20:02:27Z | [
"python",
"networking",
"ip-address"
] |
Finding local IP addresses using Python's stdlib | 166,506 | <p>How can I find local IP addresses (i.e. 192.168.x.x or 10.0.x.x) in Python platform independently and using only the standard library?</p>
| 290 | 2008-10-03T12:03:36Z | 29,931,604 | <p>This isn't very Pythonic, but it works reliably on Windows.</p>
<pre><code>def getWinIP(version = 'IPv4'):
import subprocess
if version not in ['IPv4', 'IPv6']:
print 'error - protocol version must be "IPv4" or "IPv6"'
return None
ipconfig = subprocess.check_output('ipconfig')
my_ip = []
for line in ipconfig.split('\n'):
if 'Address' in line and version in line:
my_ip.append(line.split(' : ')[1].strip())
return my_ip
print getWinIP()
</code></pre>
<p>Yeah, it's a hack, but at times I don't feel like second-guessing an operating system, and just go ahead and use what's built-in and works.</p>
| 0 | 2015-04-28T23:18:41Z | [
"python",
"networking",
"ip-address"
] |
Finding local IP addresses using Python's stdlib | 166,506 | <p>How can I find local IP addresses (i.e. 192.168.x.x or 10.0.x.x) in Python platform independently and using only the standard library?</p>
| 290 | 2008-10-03T12:03:36Z | 36,446,068 | <p>A Python 3.4 version utilizing the newly introduced asyncio package.</p>
<pre><code>async get_local_ip():
loop = asyncio.get_event_loop()
transport, protocol = await loop.create_datagram_endpoint(
asyncio.DatagramProtocol,
remote_addr=('8.8.8.8', 80))
result = transport.get_extra_info('sockname')[0])
transport.close()
return result
</code></pre>
<p>This is based on UnkwnTech's <a href="http://stackoverflow.com/a/166589/554283">excellent answer</a>.</p>
| 1 | 2016-04-06T08:51:58Z | [
"python",
"networking",
"ip-address"
] |
Finding local IP addresses using Python's stdlib | 166,506 | <p>How can I find local IP addresses (i.e. 192.168.x.x or 10.0.x.x) in Python platform independently and using only the standard library?</p>
| 290 | 2008-10-03T12:03:36Z | 37,618,645 | <p>To get the ip address you can use a <em>shell command</em> directly in <strong>python</strong>:</p>
<pre><code>import socket, subprocess
hostname = socket.gethostname()
shell_cmd = "ifconfig | awk '/inet addr/{print substr($2,6)}'"
proc = subprocess.Popen([shell_cmd], stdout=subprocess.PIPE, shell=True)
(out, err) = proc.communicate()
ip_addresses = out.split('\n')
ip_address = ip_addresses[0]
for x in xrange(0, len(ip_addresses)):
try:
if ip_addresses[x] != "127.0.0.1" and ip_addresses[x].split(".")[3] != "1":
ip_address = ip_addresses[x]
except:
pass
</code></pre>
| 3 | 2016-06-03T15:48:32Z | [
"python",
"networking",
"ip-address"
] |
Finding local IP addresses using Python's stdlib | 166,506 | <p>How can I find local IP addresses (i.e. 192.168.x.x or 10.0.x.x) in Python platform independently and using only the standard library?</p>
| 290 | 2008-10-03T12:03:36Z | 38,814,772 | <p>I settled for using the service and/or API of <strong>ipfy</strong>: <a href="https://www.ipify.org" rel="nofollow">https://www.ipify.org</a>.</p>
<pre><code>#!/usr/bin/env python3
from urllib.request import urlopen
def public_ip():
data = urlopen('https://api.ipify.org').read()
return str(data, encoding='utf-8')
print(public_ip())
</code></pre>
<p>The response can also be obtained in <em>JSON</em> and <em>JSONP</em> formats.</p>
<p>There's an <strong>ipify</strong> <a href="https://github.com/rdegges/python-ipify" rel="nofollow">Python library</a> on Github.</p>
| 0 | 2016-08-07T13:49:21Z | [
"python",
"networking",
"ip-address"
] |
Finding a public facing IP address in Python? | 166,545 | <p>How can I find the public facing IP for my net work in Python?</p>
| 14 | 2008-10-03T12:20:07Z | 166,552 | <p>This will fetch your remote IP address</p>
<pre><code>import urllib
ip = urllib.urlopen('http://automation.whatismyip.com/n09230945.asp').read()
</code></pre>
<p>If you don't want to rely on someone else, then just upload something like this PHP script:</p>
<pre><code><?php echo $_SERVER['REMOTE_ADDR']; ?>
</code></pre>
<p>and change the URL in the Python or if you prefer ASP:</p>
<pre><code><%
Dim UserIPAddress
UserIPAddress = Request.ServerVariables("REMOTE_ADDR")
%>
</code></pre>
<p>Note: I don't know ASP, but I figured it might be useful to have here so I googled.</p>
| 12 | 2008-10-03T12:22:07Z | [
"python",
"ip-address"
] |
Finding a public facing IP address in Python? | 166,545 | <p>How can I find the public facing IP for my net work in Python?</p>
| 14 | 2008-10-03T12:20:07Z | 166,563 | <p>whatismyip.org is better... it just tosses back the ip as plaintext with no extraneous crap.</p>
<pre><code>import urllib
ip = urllib.urlopen('http://whatismyip.org').read()
</code></pre>
<p>But yeah, it's impossible to do it easily without relying on something outside the network itself.</p>
| 8 | 2008-10-03T12:25:55Z | [
"python",
"ip-address"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.