title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
How do I get a Cron like scheduler in Python?
373,335
<p>I'm looking for a library in Python which will provide <code>at</code> and <code>cron</code> like functionality.</p> <p>I'd quite like have a pure Python solution, rather than relying on tools installed on the box; this way I run on machines with no cron.</p> <p>For those unfamiliar with <code>cron</code>: you can schedule tasks based upon an expression like: </p> <pre><code> 0 2 * * 7 /usr/bin/run-backup # run the backups at 0200 on Every Sunday 0 9-17/2 * * 1-5 /usr/bin/purge-temps # run the purge temps command, every 2 hours between 9am and 5pm on Mondays to Fridays. </code></pre> <p>The cron time expression syntax is less important, but I would like to have something with this sort of flexibility. </p> <p>If there isn't something that does this for me out-the-box, any suggestions for the building blocks to make something like this would be gratefully received.</p> <p><strong>Edit</strong> I'm not interested in launching processes, just "jobs" also written in Python - python functions. By necessity I think this would be a different thread, but not in a different process.</p> <p>To this end, I'm looking for the expressivity of the cron time expression, but in Python. </p> <p>Cron <em>has</em> been around for years, but I'm trying to be as portable as possible. I cannot rely on its presence.</p>
137
2008-12-17T00:56:31Z
373,743
<p>There isn't a "pure python" way to do this because some other process would have to launch python in order to run your solution. Every platform will have one or twenty different ways to launch processes and monitor their progress. On unix platforms, cron is the old standard. On Mac OS X there is also launchd, which combines cron-like launching with watchdog functionality that can keep your process alive if that's what you want. Once python is running, then you can use the <a href="http://docs.python.org/library/sched.html" rel="nofollow" title="sched">sched module</a> to schedule tasks.</p>
2
2008-12-17T05:45:01Z
[ "python", "cron" ]
How do I get a Cron like scheduler in Python?
373,335
<p>I'm looking for a library in Python which will provide <code>at</code> and <code>cron</code> like functionality.</p> <p>I'd quite like have a pure Python solution, rather than relying on tools installed on the box; this way I run on machines with no cron.</p> <p>For those unfamiliar with <code>cron</code>: you can schedule tasks based upon an expression like: </p> <pre><code> 0 2 * * 7 /usr/bin/run-backup # run the backups at 0200 on Every Sunday 0 9-17/2 * * 1-5 /usr/bin/purge-temps # run the purge temps command, every 2 hours between 9am and 5pm on Mondays to Fridays. </code></pre> <p>The cron time expression syntax is less important, but I would like to have something with this sort of flexibility. </p> <p>If there isn't something that does this for me out-the-box, any suggestions for the building blocks to make something like this would be gratefully received.</p> <p><strong>Edit</strong> I'm not interested in launching processes, just "jobs" also written in Python - python functions. By necessity I think this would be a different thread, but not in a different process.</p> <p>To this end, I'm looking for the expressivity of the cron time expression, but in Python. </p> <p>Cron <em>has</em> been around for years, but I'm trying to be as portable as possible. I cannot rely on its presence.</p>
137
2008-12-17T00:56:31Z
373,747
<p>Just in case, if you are using windows, there exists a pycron. Check out <a href="http://sourceforge.net/projects/pycron/" rel="nofollow">http://sourceforge.net/projects/pycron/</a> . For linux,I will go by either cron or sched.</p>
1
2008-12-17T05:49:29Z
[ "python", "cron" ]
How do I get a Cron like scheduler in Python?
373,335
<p>I'm looking for a library in Python which will provide <code>at</code> and <code>cron</code> like functionality.</p> <p>I'd quite like have a pure Python solution, rather than relying on tools installed on the box; this way I run on machines with no cron.</p> <p>For those unfamiliar with <code>cron</code>: you can schedule tasks based upon an expression like: </p> <pre><code> 0 2 * * 7 /usr/bin/run-backup # run the backups at 0200 on Every Sunday 0 9-17/2 * * 1-5 /usr/bin/purge-temps # run the purge temps command, every 2 hours between 9am and 5pm on Mondays to Fridays. </code></pre> <p>The cron time expression syntax is less important, but I would like to have something with this sort of flexibility. </p> <p>If there isn't something that does this for me out-the-box, any suggestions for the building blocks to make something like this would be gratefully received.</p> <p><strong>Edit</strong> I'm not interested in launching processes, just "jobs" also written in Python - python functions. By necessity I think this would be a different thread, but not in a different process.</p> <p>To this end, I'm looking for the expressivity of the cron time expression, but in Python. </p> <p>Cron <em>has</em> been around for years, but I'm trying to be as portable as possible. I cannot rely on its presence.</p>
137
2008-12-17T00:56:31Z
373,789
<p><a href="http://turbogears.com/">TurboGears</a> ships with scheduled task capability based on <a href="http://www.razorvine.net/download/kronos.py">Kronos</a></p> <p>I've never used Kronos directly, but the scheduling in TG has a decent set of features and is solid.</p>
9
2008-12-17T06:23:28Z
[ "python", "cron" ]
How do I get a Cron like scheduler in Python?
373,335
<p>I'm looking for a library in Python which will provide <code>at</code> and <code>cron</code> like functionality.</p> <p>I'd quite like have a pure Python solution, rather than relying on tools installed on the box; this way I run on machines with no cron.</p> <p>For those unfamiliar with <code>cron</code>: you can schedule tasks based upon an expression like: </p> <pre><code> 0 2 * * 7 /usr/bin/run-backup # run the backups at 0200 on Every Sunday 0 9-17/2 * * 1-5 /usr/bin/purge-temps # run the purge temps command, every 2 hours between 9am and 5pm on Mondays to Fridays. </code></pre> <p>The cron time expression syntax is less important, but I would like to have something with this sort of flexibility. </p> <p>If there isn't something that does this for me out-the-box, any suggestions for the building blocks to make something like this would be gratefully received.</p> <p><strong>Edit</strong> I'm not interested in launching processes, just "jobs" also written in Python - python functions. By necessity I think this would be a different thread, but not in a different process.</p> <p>To this end, I'm looking for the expressivity of the cron time expression, but in Python. </p> <p>Cron <em>has</em> been around for years, but I'm trying to be as portable as possible. I cannot rely on its presence.</p>
137
2008-12-17T00:56:31Z
374,207
<p>You could just use normal Python argument passing syntax to specify your crontab. For example, suppose we define an Event class as below:</p> <pre><code>from datetime import datetime, timedelta import time # Some utility classes / functions first class AllMatch(set): """Universal set - match everything""" def __contains__(self, item): return True allMatch = AllMatch() def conv_to_set(obj): # Allow single integer to be provided if isinstance(obj, (int,long)): return set([obj]) # Single item if not isinstance(obj, set): obj = set(obj) return obj # The actual Event class class Event(object): def __init__(self, action, min=allMatch, hour=allMatch, day=allMatch, month=allMatch, dow=allMatch, args=(), kwargs={}): self.mins = conv_to_set(min) self.hours= conv_to_set(hour) self.days = conv_to_set(day) self.months = conv_to_set(month) self.dow = conv_to_set(dow) self.action = action self.args = args self.kwargs = kwargs def matchtime(self, t): """Return True if this event should trigger at the specified datetime""" return ((t.minute in self.mins) and (t.hour in self.hours) and (t.day in self.days) and (t.month in self.months) and (t.weekday() in self.dow)) def check(self, t): if self.matchtime(t): self.action(*self.args, **self.kwargs) </code></pre> <p>(Note: Not thoroughly tested)</p> <p>Then your CronTab can be specified in normal python syntax as:</p> <pre><code>c = CronTab( Event(perform_backup, 0, 2, dow=6 ), Event(purge_temps, 0, range(9,18,2), dow=range(0,5)) ) </code></pre> <p>This way you get the full power of Python's argument mechanics (mixing positional and keyword args, and can use symbolic names for names of weeks and months)</p> <p>The CronTab class would be defined as simply sleeping in minute increments, and calling check() on each event. (There are probably some subtleties with daylight savings time / timezones to be wary of though). Here's a quick implementation:</p> <pre><code>class CronTab(object): def __init__(self, *events): self.events = events def run(self): t=datetime(*datetime.now().timetuple()[:5]) while 1: for e in self.events: e.check(t) t += timedelta(minutes=1) while datetime.now() &lt; t: time.sleep((t - datetime.now()).seconds) </code></pre> <p>A few things to note: Python's weekdays / months are zero indexed (unlike cron), and that range excludes the last element, hence syntax like "1-5" becomes range(0,5) - ie [0,1,2,3,4]. If you prefer cron syntax, parsing it shouldn't be too difficult however.</p>
48
2008-12-17T10:48:11Z
[ "python", "cron" ]
How do I get a Cron like scheduler in Python?
373,335
<p>I'm looking for a library in Python which will provide <code>at</code> and <code>cron</code> like functionality.</p> <p>I'd quite like have a pure Python solution, rather than relying on tools installed on the box; this way I run on machines with no cron.</p> <p>For those unfamiliar with <code>cron</code>: you can schedule tasks based upon an expression like: </p> <pre><code> 0 2 * * 7 /usr/bin/run-backup # run the backups at 0200 on Every Sunday 0 9-17/2 * * 1-5 /usr/bin/purge-temps # run the purge temps command, every 2 hours between 9am and 5pm on Mondays to Fridays. </code></pre> <p>The cron time expression syntax is less important, but I would like to have something with this sort of flexibility. </p> <p>If there isn't something that does this for me out-the-box, any suggestions for the building blocks to make something like this would be gratefully received.</p> <p><strong>Edit</strong> I'm not interested in launching processes, just "jobs" also written in Python - python functions. By necessity I think this would be a different thread, but not in a different process.</p> <p>To this end, I'm looking for the expressivity of the cron time expression, but in Python. </p> <p>Cron <em>has</em> been around for years, but I'm trying to be as portable as possible. I cannot rely on its presence.</p>
137
2008-12-17T00:56:31Z
2,216,614
<p>I have a minor fix for the <a href="http://stackoverflow.com/a/374207/50776">CronTab class run method suggested by Brian</a>.</p> <p>The timing was out by one second leading to a one-second, hard loop at the end of each minute.</p> <pre><code>class CronTab(object): def __init__(self, *events): self.events = events def run(self): t=datetime(*datetime.now().timetuple()[:5]) while 1: for e in self.events: e.check(t) t += timedelta(minutes=1) n = datetime.now() while n &lt; t: s = (t - n).seconds + 1 time.sleep(s) n = datetime.now() </code></pre>
4
2010-02-07T09:59:23Z
[ "python", "cron" ]
How do I get a Cron like scheduler in Python?
373,335
<p>I'm looking for a library in Python which will provide <code>at</code> and <code>cron</code> like functionality.</p> <p>I'd quite like have a pure Python solution, rather than relying on tools installed on the box; this way I run on machines with no cron.</p> <p>For those unfamiliar with <code>cron</code>: you can schedule tasks based upon an expression like: </p> <pre><code> 0 2 * * 7 /usr/bin/run-backup # run the backups at 0200 on Every Sunday 0 9-17/2 * * 1-5 /usr/bin/purge-temps # run the purge temps command, every 2 hours between 9am and 5pm on Mondays to Fridays. </code></pre> <p>The cron time expression syntax is less important, but I would like to have something with this sort of flexibility. </p> <p>If there isn't something that does this for me out-the-box, any suggestions for the building blocks to make something like this would be gratefully received.</p> <p><strong>Edit</strong> I'm not interested in launching processes, just "jobs" also written in Python - python functions. By necessity I think this would be a different thread, but not in a different process.</p> <p>To this end, I'm looking for the expressivity of the cron time expression, but in Python. </p> <p>Cron <em>has</em> been around for years, but I'm trying to be as portable as possible. I cannot rely on its presence.</p>
137
2008-12-17T00:56:31Z
2,946,908
<p>More or less same as above but concurrent using gevent :)</p> <pre><code>"""Gevent based crontab implementation""" from datetime import datetime, timedelta import gevent # Some utility classes / functions first def conv_to_set(obj): """Converts to set allowing single integer to be provided""" if isinstance(obj, (int, long)): return set([obj]) # Single item if not isinstance(obj, set): obj = set(obj) return obj class AllMatch(set): """Universal set - match everything""" def __contains__(self, item): return True allMatch = AllMatch() class Event(object): """The Actual Event Class""" def __init__(self, action, minute=allMatch, hour=allMatch, day=allMatch, month=allMatch, daysofweek=allMatch, args=(), kwargs={}): self.mins = conv_to_set(minute) self.hours = conv_to_set(hour) self.days = conv_to_set(day) self.months = conv_to_set(month) self.daysofweek = conv_to_set(daysofweek) self.action = action self.args = args self.kwargs = kwargs def matchtime(self, t1): """Return True if this event should trigger at the specified datetime""" return ((t1.minute in self.mins) and (t1.hour in self.hours) and (t1.day in self.days) and (t1.month in self.months) and (t1.weekday() in self.daysofweek)) def check(self, t): """Check and run action if needed""" if self.matchtime(t): self.action(*self.args, **self.kwargs) class CronTab(object): """The crontab implementation""" def __init__(self, *events): self.events = events def _check(self): """Check all events in separate greenlets""" t1 = datetime(*datetime.now().timetuple()[:5]) for event in self.events: gevent.spawn(event.check, t1) t1 += timedelta(minutes=1) s1 = (t1 - datetime.now()).seconds + 1 print "Checking again in %s seconds" % s1 job = gevent.spawn_later(s1, self._check) def run(self): """Run the cron forever""" self._check() while True: gevent.sleep(60) import os def test_task(): """Just an example that sends a bell and asd to all terminals""" os.system('echo asd | wall') cron = CronTab( Event(test_task, 22, 1 ), Event(test_task, 0, range(9,18,2), daysofweek=range(0,5)), ) cron.run() </code></pre>
9
2010-06-01T02:01:21Z
[ "python", "cron" ]
How do I get a Cron like scheduler in Python?
373,335
<p>I'm looking for a library in Python which will provide <code>at</code> and <code>cron</code> like functionality.</p> <p>I'd quite like have a pure Python solution, rather than relying on tools installed on the box; this way I run on machines with no cron.</p> <p>For those unfamiliar with <code>cron</code>: you can schedule tasks based upon an expression like: </p> <pre><code> 0 2 * * 7 /usr/bin/run-backup # run the backups at 0200 on Every Sunday 0 9-17/2 * * 1-5 /usr/bin/purge-temps # run the purge temps command, every 2 hours between 9am and 5pm on Mondays to Fridays. </code></pre> <p>The cron time expression syntax is less important, but I would like to have something with this sort of flexibility. </p> <p>If there isn't something that does this for me out-the-box, any suggestions for the building blocks to make something like this would be gratefully received.</p> <p><strong>Edit</strong> I'm not interested in launching processes, just "jobs" also written in Python - python functions. By necessity I think this would be a different thread, but not in a different process.</p> <p>To this end, I'm looking for the expressivity of the cron time expression, but in Python. </p> <p>Cron <em>has</em> been around for years, but I'm trying to be as portable as possible. I cannot rely on its presence.</p>
137
2008-12-17T00:56:31Z
3,292,913
<p>Check out <a href="http://celery.readthedocs.org/en/latest/userguide/periodic-tasks.html">Celery</a>, they have periodic tasks like cron.</p>
17
2010-07-20T18:03:41Z
[ "python", "cron" ]
How do I get a Cron like scheduler in Python?
373,335
<p>I'm looking for a library in Python which will provide <code>at</code> and <code>cron</code> like functionality.</p> <p>I'd quite like have a pure Python solution, rather than relying on tools installed on the box; this way I run on machines with no cron.</p> <p>For those unfamiliar with <code>cron</code>: you can schedule tasks based upon an expression like: </p> <pre><code> 0 2 * * 7 /usr/bin/run-backup # run the backups at 0200 on Every Sunday 0 9-17/2 * * 1-5 /usr/bin/purge-temps # run the purge temps command, every 2 hours between 9am and 5pm on Mondays to Fridays. </code></pre> <p>The cron time expression syntax is less important, but I would like to have something with this sort of flexibility. </p> <p>If there isn't something that does this for me out-the-box, any suggestions for the building blocks to make something like this would be gratefully received.</p> <p><strong>Edit</strong> I'm not interested in launching processes, just "jobs" also written in Python - python functions. By necessity I think this would be a different thread, but not in a different process.</p> <p>To this end, I'm looking for the expressivity of the cron time expression, but in Python. </p> <p>Cron <em>has</em> been around for years, but I'm trying to be as portable as possible. I cannot rely on its presence.</p>
137
2008-12-17T00:56:31Z
3,490,779
<p>You can also try this: <a href="http://bitbucket.org/marnold/py-cron" rel="nofollow">http://bitbucket.org/marnold/py-cron</a></p>
0
2010-08-16T05:24:08Z
[ "python", "cron" ]
How do I get a Cron like scheduler in Python?
373,335
<p>I'm looking for a library in Python which will provide <code>at</code> and <code>cron</code> like functionality.</p> <p>I'd quite like have a pure Python solution, rather than relying on tools installed on the box; this way I run on machines with no cron.</p> <p>For those unfamiliar with <code>cron</code>: you can schedule tasks based upon an expression like: </p> <pre><code> 0 2 * * 7 /usr/bin/run-backup # run the backups at 0200 on Every Sunday 0 9-17/2 * * 1-5 /usr/bin/purge-temps # run the purge temps command, every 2 hours between 9am and 5pm on Mondays to Fridays. </code></pre> <p>The cron time expression syntax is less important, but I would like to have something with this sort of flexibility. </p> <p>If there isn't something that does this for me out-the-box, any suggestions for the building blocks to make something like this would be gratefully received.</p> <p><strong>Edit</strong> I'm not interested in launching processes, just "jobs" also written in Python - python functions. By necessity I think this would be a different thread, but not in a different process.</p> <p>To this end, I'm looking for the expressivity of the cron time expression, but in Python. </p> <p>Cron <em>has</em> been around for years, but I'm trying to be as portable as possible. I cannot rely on its presence.</p>
137
2008-12-17T00:56:31Z
4,074,157
<p><a href="http://stackoverflow.com/questions/373335/suggestions-for-a-cron-like-scheduler-in-python/374207#374207">Brian's solution</a> is working quite well. However, as others have pointed out, there is a subtle bug in the run code. Also i found it overly complicated for the needs.</p> <p>Here is my simpler and functional alternative for the run code in case anybody needs it:</p> <pre><code>def run(self): while 1: t = datetime.now() for e in self.events: e.check(t) time.sleep(60 - t.second - t.microsecond / 1000000.0) </code></pre>
0
2010-11-02T00:27:45Z
[ "python", "cron" ]
How do I get a Cron like scheduler in Python?
373,335
<p>I'm looking for a library in Python which will provide <code>at</code> and <code>cron</code> like functionality.</p> <p>I'd quite like have a pure Python solution, rather than relying on tools installed on the box; this way I run on machines with no cron.</p> <p>For those unfamiliar with <code>cron</code>: you can schedule tasks based upon an expression like: </p> <pre><code> 0 2 * * 7 /usr/bin/run-backup # run the backups at 0200 on Every Sunday 0 9-17/2 * * 1-5 /usr/bin/purge-temps # run the purge temps command, every 2 hours between 9am and 5pm on Mondays to Fridays. </code></pre> <p>The cron time expression syntax is less important, but I would like to have something with this sort of flexibility. </p> <p>If there isn't something that does this for me out-the-box, any suggestions for the building blocks to make something like this would be gratefully received.</p> <p><strong>Edit</strong> I'm not interested in launching processes, just "jobs" also written in Python - python functions. By necessity I think this would be a different thread, but not in a different process.</p> <p>To this end, I'm looking for the expressivity of the cron time expression, but in Python. </p> <p>Cron <em>has</em> been around for years, but I'm trying to be as portable as possible. I cannot rely on its presence.</p>
137
2008-12-17T00:56:31Z
4,523,531
<p>I took Brian's solution, made a few changes, added the beginnings of a standard crontab file parser, and put it at <a href="https://bitbucket.org/dbenamy/devcron" rel="nofollow">https://bitbucket.org/dbenamy/devcron</a>.</p>
0
2010-12-24T00:43:18Z
[ "python", "cron" ]
How do I get a Cron like scheduler in Python?
373,335
<p>I'm looking for a library in Python which will provide <code>at</code> and <code>cron</code> like functionality.</p> <p>I'd quite like have a pure Python solution, rather than relying on tools installed on the box; this way I run on machines with no cron.</p> <p>For those unfamiliar with <code>cron</code>: you can schedule tasks based upon an expression like: </p> <pre><code> 0 2 * * 7 /usr/bin/run-backup # run the backups at 0200 on Every Sunday 0 9-17/2 * * 1-5 /usr/bin/purge-temps # run the purge temps command, every 2 hours between 9am and 5pm on Mondays to Fridays. </code></pre> <p>The cron time expression syntax is less important, but I would like to have something with this sort of flexibility. </p> <p>If there isn't something that does this for me out-the-box, any suggestions for the building blocks to make something like this would be gratefully received.</p> <p><strong>Edit</strong> I'm not interested in launching processes, just "jobs" also written in Python - python functions. By necessity I think this would be a different thread, but not in a different process.</p> <p>To this end, I'm looking for the expressivity of the cron time expression, but in Python. </p> <p>Cron <em>has</em> been around for years, but I'm trying to be as portable as possible. I cannot rely on its presence.</p>
137
2008-12-17T00:56:31Z
5,256,822
<p>maybe this has come up only after the question was asked; I thought I just mention it for completeness sake: <a href="https://apscheduler.readthedocs.org/en/latest/">https://apscheduler.readthedocs.org/en/latest/</a></p>
28
2011-03-10T07:46:32Z
[ "python", "cron" ]
How do I get a Cron like scheduler in Python?
373,335
<p>I'm looking for a library in Python which will provide <code>at</code> and <code>cron</code> like functionality.</p> <p>I'd quite like have a pure Python solution, rather than relying on tools installed on the box; this way I run on machines with no cron.</p> <p>For those unfamiliar with <code>cron</code>: you can schedule tasks based upon an expression like: </p> <pre><code> 0 2 * * 7 /usr/bin/run-backup # run the backups at 0200 on Every Sunday 0 9-17/2 * * 1-5 /usr/bin/purge-temps # run the purge temps command, every 2 hours between 9am and 5pm on Mondays to Fridays. </code></pre> <p>The cron time expression syntax is less important, but I would like to have something with this sort of flexibility. </p> <p>If there isn't something that does this for me out-the-box, any suggestions for the building blocks to make something like this would be gratefully received.</p> <p><strong>Edit</strong> I'm not interested in launching processes, just "jobs" also written in Python - python functions. By necessity I think this would be a different thread, but not in a different process.</p> <p>To this end, I'm looking for the expressivity of the cron time expression, but in Python. </p> <p>Cron <em>has</em> been around for years, but I'm trying to be as portable as possible. I cannot rely on its presence.</p>
137
2008-12-17T00:56:31Z
12,360,518
<p>Another trivial solution would be:</p> <pre><code>from aqcron import At from time import sleep from datetime import datetime # Event scheduling event_1 = At( second=5 ) event_2 = At( second=[0,20,40] ) while True: now = datetime.now() # Event check if now in event_1: print "event_1" if now in event_2: print "event_2" sleep(1) </code></pre> <p>And the class aqcron.At is:</p> <pre><code># aqcron.py class At(object): def __init__(self, year=None, month=None, day=None, weekday=None, hour=None, minute=None, second=None): loc = locals() loc.pop("self") self.at = dict((k, v) for k, v in loc.iteritems() if v != None) def __contains__(self, now): for k in self.at.keys(): try: if not getattr(now, k) in self.at[k]: return False except TypeError: if self.at[k] != getattr(now, k): return False return True </code></pre>
1
2012-09-10T22:51:04Z
[ "python", "cron" ]
How do I get a Cron like scheduler in Python?
373,335
<p>I'm looking for a library in Python which will provide <code>at</code> and <code>cron</code> like functionality.</p> <p>I'd quite like have a pure Python solution, rather than relying on tools installed on the box; this way I run on machines with no cron.</p> <p>For those unfamiliar with <code>cron</code>: you can schedule tasks based upon an expression like: </p> <pre><code> 0 2 * * 7 /usr/bin/run-backup # run the backups at 0200 on Every Sunday 0 9-17/2 * * 1-5 /usr/bin/purge-temps # run the purge temps command, every 2 hours between 9am and 5pm on Mondays to Fridays. </code></pre> <p>The cron time expression syntax is less important, but I would like to have something with this sort of flexibility. </p> <p>If there isn't something that does this for me out-the-box, any suggestions for the building blocks to make something like this would be gratefully received.</p> <p><strong>Edit</strong> I'm not interested in launching processes, just "jobs" also written in Python - python functions. By necessity I think this would be a different thread, but not in a different process.</p> <p>To this end, I'm looking for the expressivity of the cron time expression, but in Python. </p> <p>Cron <em>has</em> been around for years, but I'm trying to be as portable as possible. I cannot rely on its presence.</p>
137
2008-12-17T00:56:31Z
13,831,944
<p><em>"... Crontab module for read and writing crontab files and accessing the system cron automatically and simply using a direct API. ..."</em></p> <p><a href="http://pypi.python.org/pypi/python-crontab">http://pypi.python.org/pypi/python-crontab</a></p> <p>and also APScheduler, a python package. Already written &amp; debugged.</p> <p><a href="http://packages.python.org/APScheduler/cronschedule.html">http://packages.python.org/APScheduler/cronschedule.html</a></p>
13
2012-12-12T02:39:58Z
[ "python", "cron" ]
How do I get a Cron like scheduler in Python?
373,335
<p>I'm looking for a library in Python which will provide <code>at</code> and <code>cron</code> like functionality.</p> <p>I'd quite like have a pure Python solution, rather than relying on tools installed on the box; this way I run on machines with no cron.</p> <p>For those unfamiliar with <code>cron</code>: you can schedule tasks based upon an expression like: </p> <pre><code> 0 2 * * 7 /usr/bin/run-backup # run the backups at 0200 on Every Sunday 0 9-17/2 * * 1-5 /usr/bin/purge-temps # run the purge temps command, every 2 hours between 9am and 5pm on Mondays to Fridays. </code></pre> <p>The cron time expression syntax is less important, but I would like to have something with this sort of flexibility. </p> <p>If there isn't something that does this for me out-the-box, any suggestions for the building blocks to make something like this would be gratefully received.</p> <p><strong>Edit</strong> I'm not interested in launching processes, just "jobs" also written in Python - python functions. By necessity I think this would be a different thread, but not in a different process.</p> <p>To this end, I'm looking for the expressivity of the cron time expression, but in Python. </p> <p>Cron <em>has</em> been around for years, but I'm trying to be as portable as possible. I cannot rely on its presence.</p>
137
2008-12-17T00:56:31Z
16,204,433
<p>You can check out PiCloud's [1] Crons [2], but do note that your jobs won't be running on your own machine. It's also a service that you'll need to pay for if you use more than 20 hours of compute time a month.</p> <p>[1] <a href="http://www.picloud.com" rel="nofollow">http://www.picloud.com</a></p> <p>[2] <a href="http://docs.picloud.com/cron.html" rel="nofollow">http://docs.picloud.com/cron.html</a></p>
0
2013-04-25T00:23:47Z
[ "python", "cron" ]
How do I get a Cron like scheduler in Python?
373,335
<p>I'm looking for a library in Python which will provide <code>at</code> and <code>cron</code> like functionality.</p> <p>I'd quite like have a pure Python solution, rather than relying on tools installed on the box; this way I run on machines with no cron.</p> <p>For those unfamiliar with <code>cron</code>: you can schedule tasks based upon an expression like: </p> <pre><code> 0 2 * * 7 /usr/bin/run-backup # run the backups at 0200 on Every Sunday 0 9-17/2 * * 1-5 /usr/bin/purge-temps # run the purge temps command, every 2 hours between 9am and 5pm on Mondays to Fridays. </code></pre> <p>The cron time expression syntax is less important, but I would like to have something with this sort of flexibility. </p> <p>If there isn't something that does this for me out-the-box, any suggestions for the building blocks to make something like this would be gratefully received.</p> <p><strong>Edit</strong> I'm not interested in launching processes, just "jobs" also written in Python - python functions. By necessity I think this would be a different thread, but not in a different process.</p> <p>To this end, I'm looking for the expressivity of the cron time expression, but in Python. </p> <p>Cron <em>has</em> been around for years, but I'm trying to be as portable as possible. I cannot rely on its presence.</p>
137
2008-12-17T00:56:31Z
16,786,600
<p>If you're looking for something lightweight checkout <a href="https://github.com/dbader/schedule">schedule</a>:</p> <pre><code>import schedule import time def job(): print("I'm working...") schedule.every(10).minutes.do(job) schedule.every().hour.do(job) schedule.every().day.at("10:30").do(job) while 1: schedule.run_pending() time.sleep(1) </code></pre> <p><em>Disclosure</em>: I'm the author of that library.</p>
153
2013-05-28T07:48:31Z
[ "python", "cron" ]
How do I get a Cron like scheduler in Python?
373,335
<p>I'm looking for a library in Python which will provide <code>at</code> and <code>cron</code> like functionality.</p> <p>I'd quite like have a pure Python solution, rather than relying on tools installed on the box; this way I run on machines with no cron.</p> <p>For those unfamiliar with <code>cron</code>: you can schedule tasks based upon an expression like: </p> <pre><code> 0 2 * * 7 /usr/bin/run-backup # run the backups at 0200 on Every Sunday 0 9-17/2 * * 1-5 /usr/bin/purge-temps # run the purge temps command, every 2 hours between 9am and 5pm on Mondays to Fridays. </code></pre> <p>The cron time expression syntax is less important, but I would like to have something with this sort of flexibility. </p> <p>If there isn't something that does this for me out-the-box, any suggestions for the building blocks to make something like this would be gratefully received.</p> <p><strong>Edit</strong> I'm not interested in launching processes, just "jobs" also written in Python - python functions. By necessity I think this would be a different thread, but not in a different process.</p> <p>To this end, I'm looking for the expressivity of the cron time expression, but in Python. </p> <p>Cron <em>has</em> been around for years, but I'm trying to be as portable as possible. I cannot rely on its presence.</p>
137
2008-12-17T00:56:31Z
19,099,711
<p>Check out luigi (<a href="https://github.com/spotify/luigi" rel="nofollow">https://github.com/spotify/luigi</a>). It's written in python and has a nice web UI for monitoring tasks. It also has a dependency graph. Might be overkill for what you need but it will probably do the trick.</p>
4
2013-09-30T16:57:26Z
[ "python", "cron" ]
How do I get a Cron like scheduler in Python?
373,335
<p>I'm looking for a library in Python which will provide <code>at</code> and <code>cron</code> like functionality.</p> <p>I'd quite like have a pure Python solution, rather than relying on tools installed on the box; this way I run on machines with no cron.</p> <p>For those unfamiliar with <code>cron</code>: you can schedule tasks based upon an expression like: </p> <pre><code> 0 2 * * 7 /usr/bin/run-backup # run the backups at 0200 on Every Sunday 0 9-17/2 * * 1-5 /usr/bin/purge-temps # run the purge temps command, every 2 hours between 9am and 5pm on Mondays to Fridays. </code></pre> <p>The cron time expression syntax is less important, but I would like to have something with this sort of flexibility. </p> <p>If there isn't something that does this for me out-the-box, any suggestions for the building blocks to make something like this would be gratefully received.</p> <p><strong>Edit</strong> I'm not interested in launching processes, just "jobs" also written in Python - python functions. By necessity I think this would be a different thread, but not in a different process.</p> <p>To this end, I'm looking for the expressivity of the cron time expression, but in Python. </p> <p>Cron <em>has</em> been around for years, but I'm trying to be as portable as possible. I cannot rely on its presence.</p>
137
2008-12-17T00:56:31Z
20,948,123
<p>I have modified the script.</p> <ol> <li><p>Easy to use:</p> <pre><code>cron = Cron() cron.add('* * * * *' , minute_task) # every minute cron.add('33 * * * *' , day_task) # every hour cron.add('34 18 * * *' , day_task) # every day cron.run() </code></pre></li> <li><p>Try to start task in the first second of a minute.</p></li> </ol> <p><a href="https://github.com/idning/pcl/blob/master/pcl/crontab.py" rel="nofollow">Code on Github</a></p>
3
2014-01-06T10:38:03Z
[ "python", "cron" ]
How do I get a Cron like scheduler in Python?
373,335
<p>I'm looking for a library in Python which will provide <code>at</code> and <code>cron</code> like functionality.</p> <p>I'd quite like have a pure Python solution, rather than relying on tools installed on the box; this way I run on machines with no cron.</p> <p>For those unfamiliar with <code>cron</code>: you can schedule tasks based upon an expression like: </p> <pre><code> 0 2 * * 7 /usr/bin/run-backup # run the backups at 0200 on Every Sunday 0 9-17/2 * * 1-5 /usr/bin/purge-temps # run the purge temps command, every 2 hours between 9am and 5pm on Mondays to Fridays. </code></pre> <p>The cron time expression syntax is less important, but I would like to have something with this sort of flexibility. </p> <p>If there isn't something that does this for me out-the-box, any suggestions for the building blocks to make something like this would be gratefully received.</p> <p><strong>Edit</strong> I'm not interested in launching processes, just "jobs" also written in Python - python functions. By necessity I think this would be a different thread, but not in a different process.</p> <p>To this end, I'm looking for the expressivity of the cron time expression, but in Python. </p> <p>Cron <em>has</em> been around for years, but I'm trying to be as portable as possible. I cannot rely on its presence.</p>
137
2008-12-17T00:56:31Z
34,103,997
<p>Jython? </p> <p>I just searched here and found that this word has not been mentioned on this page. Real multithreading (not multi-process), Futures, ExecutorService, and all the other tools in the concurrency toolbox, etc. </p>
0
2015-12-05T10:54:03Z
[ "python", "cron" ]
How do I get a Cron like scheduler in Python?
373,335
<p>I'm looking for a library in Python which will provide <code>at</code> and <code>cron</code> like functionality.</p> <p>I'd quite like have a pure Python solution, rather than relying on tools installed on the box; this way I run on machines with no cron.</p> <p>For those unfamiliar with <code>cron</code>: you can schedule tasks based upon an expression like: </p> <pre><code> 0 2 * * 7 /usr/bin/run-backup # run the backups at 0200 on Every Sunday 0 9-17/2 * * 1-5 /usr/bin/purge-temps # run the purge temps command, every 2 hours between 9am and 5pm on Mondays to Fridays. </code></pre> <p>The cron time expression syntax is less important, but I would like to have something with this sort of flexibility. </p> <p>If there isn't something that does this for me out-the-box, any suggestions for the building blocks to make something like this would be gratefully received.</p> <p><strong>Edit</strong> I'm not interested in launching processes, just "jobs" also written in Python - python functions. By necessity I think this would be a different thread, but not in a different process.</p> <p>To this end, I'm looking for the expressivity of the cron time expression, but in Python. </p> <p>Cron <em>has</em> been around for years, but I'm trying to be as portable as possible. I cannot rely on its presence.</p>
137
2008-12-17T00:56:31Z
35,833,199
<p>None of the listed solutions even attempt to parse a complex cron schedule string. So, here is my version, using <a href="https://github.com/taichino/croniter" rel="nofollow">croniter</a>. Basic gist:</p> <pre><code>schedule = "*/5 * * * *" # Run every five minutes nextRunTime = getNextCronRunTime(schedule) while True: roundedDownTime = roundDownTime() if (roundedDownTime == nextRunTime): #################################### ### Do your periodic thing here. ### #################################### nextRunTime = getNextCronRunTime(schedule) elif (roundedDownTime &gt; nextRunTime): # We missed an execution. Error. Re initialize. nextRunTime = getNextCronRunTime(schedule) sleepTillTopOfNextMinute() </code></pre> <p>Helper routines:</p> <pre><code>from croniter import croniter from datetime import datetime, timedelta # Round time down to the top of the previous minute def roundDownTime(dt=None, dateDelta=timedelta(minutes=1)): roundTo = dateDelta.total_seconds() if dt == None : dt = datetime.now() seconds = (dt - dt.min).seconds rounding = (seconds+roundTo/2) // roundTo * roundTo return dt + timedelta(0,rounding-seconds,-dt.microsecond) # Get next run time from now, based on schedule specified by cron string def getNextCronRunTime(schedule): return croniter(schedule, datetime.now()).get_next(datetime) # Sleep till the top of the next minute def sleepTillTopOfNextMinute(): t = datetime.utcnow() sleeptime = 60 - (t.second + t.microsecond/1000000.0) time.sleep(sleeptime) </code></pre>
1
2016-03-06T22:06:16Z
[ "python", "cron" ]
How do I get the UTC time of "midnight" for a given timezone?
373,370
<p>The best I can come up with for now is this monstrosity:</p> <pre><code>&gt;&gt;&gt; datetime.utcnow() \ ... .replace(tzinfo=pytz.UTC) \ ... .astimezone(pytz.timezone("Australia/Melbourne")) \ ... .replace(hour=0,minute=0,second=0,microsecond=0) \ ... .astimezone(pytz.UTC) \ ... .replace(tzinfo=None) datetime.datetime(2008, 12, 16, 13, 0) </code></pre> <p>I.e., in English, get the current time (in UTC), convert it to some other timezone, set the time to midnight, then convert back to UTC.</p> <p>I'm not just using now() or localtime() as that would use the server's timezone, not the user's timezone.</p> <p>I can't help feeling I'm missing something, any ideas?</p>
20
2008-12-17T01:11:07Z
373,379
<p>Setting the TZ environment variable modifies what timezone Python's date and time functions work with.</p> <pre><code>&gt;&gt;&gt; time.gmtime() (2008, 12, 17, 1, 16, 46, 2, 352, 0) &gt;&gt;&gt; time.localtime() (2008, 12, 16, 20, 16, 47, 1, 351, 0) &gt;&gt;&gt; os.environ['TZ']='Australia/Melbourne' &gt;&gt;&gt; time.localtime() (2008, 12, 17, 12, 16, 53, 2, 352, 1) </code></pre>
0
2008-12-17T01:17:26Z
[ "python", "datetime", "timezone", "utc", "pytz" ]
How do I get the UTC time of "midnight" for a given timezone?
373,370
<p>The best I can come up with for now is this monstrosity:</p> <pre><code>&gt;&gt;&gt; datetime.utcnow() \ ... .replace(tzinfo=pytz.UTC) \ ... .astimezone(pytz.timezone("Australia/Melbourne")) \ ... .replace(hour=0,minute=0,second=0,microsecond=0) \ ... .astimezone(pytz.UTC) \ ... .replace(tzinfo=None) datetime.datetime(2008, 12, 16, 13, 0) </code></pre> <p>I.e., in English, get the current time (in UTC), convert it to some other timezone, set the time to midnight, then convert back to UTC.</p> <p>I'm not just using now() or localtime() as that would use the server's timezone, not the user's timezone.</p> <p>I can't help feeling I'm missing something, any ideas?</p>
20
2008-12-17T01:11:07Z
373,384
<p>Each time zone has a number, eg US/Central = -6. This is defined as the offset in hours from UTC. Since 0000 is midnight, you can simply use this offset to find the time in any time zone when it is midnight UTC. To access that, I believe you can use <pre> time.timezone</pre></p> <p>According to <a href="http://docs.python.org/library/time.html" rel="nofollow">The Python Docs</a>, time.timezone actually gives the negative value of this number:</p> <blockquote> <blockquote> <p>time.timezone</p> <blockquote> <p>The offset of the local (non-DST) timezone, in seconds west of UTC (negative in most of Western Europe, positive in the US, zero in the UK).</p> </blockquote> </blockquote> </blockquote> <p>So you would simply use that number for the time in hours if it's positive (i.e., if it's midnight in Chicago (which has a +6 timezone value), then it's 6000 = 6am UTC).</p> <p>If the number is negative, subtract from 24. For example, Berlin would give -1, so 24 - 1 => 2300 = 11pm.</p>
0
2008-12-17T01:20:06Z
[ "python", "datetime", "timezone", "utc", "pytz" ]
How do I get the UTC time of "midnight" for a given timezone?
373,370
<p>The best I can come up with for now is this monstrosity:</p> <pre><code>&gt;&gt;&gt; datetime.utcnow() \ ... .replace(tzinfo=pytz.UTC) \ ... .astimezone(pytz.timezone("Australia/Melbourne")) \ ... .replace(hour=0,minute=0,second=0,microsecond=0) \ ... .astimezone(pytz.UTC) \ ... .replace(tzinfo=None) datetime.datetime(2008, 12, 16, 13, 0) </code></pre> <p>I.e., in English, get the current time (in UTC), convert it to some other timezone, set the time to midnight, then convert back to UTC.</p> <p>I'm not just using now() or localtime() as that would use the server's timezone, not the user's timezone.</p> <p>I can't help feeling I'm missing something, any ideas?</p>
20
2008-12-17T01:11:07Z
381,788
<p>I think you can shave off a few method calls if you do it like this:</p> <pre><code>&gt;&gt;&gt; from datetime import datetime &gt;&gt;&gt; datetime.now(pytz.timezone("Australia/Melbourne")) \ .replace(hour=0, minute=0, second=0, microsecond=0) \ .astimezone(pytz.utc) </code></pre> <p>BUT… there is a bigger problem than aesthetics in your code: it will give the wrong result on the day of the switch to or from Daylight Saving Time.</p> <p>The reason for this is that neither the datetime constructors nor <code>replace()</code> take DST changes into account.</p> <p>For example:</p> <pre><code>&gt;&gt;&gt; now = datetime(2012, 4, 1, 5, 0, 0, 0, tzinfo=pytz.timezone("Australia/Melbourne")) &gt;&gt;&gt; print now 2012-04-01 05:00:00+10:00 &gt;&gt;&gt; print now.replace(hour=0) 2012-04-01 00:00:00+10:00 # wrong! midnight was at 2012-04-01 00:00:00+11:00 &gt;&gt;&gt; print datetime(2012, 3, 1, 0, 0, 0, 0, tzinfo=tz) 2012-03-01 00:00:00+10:00 # wrong again! </code></pre> <p>However, the documentation for <code>tz.localize()</code> states:</p> <blockquote> <p>This method should be used to construct localtimes, rather than passing a tzinfo argument to a datetime constructor.</p> </blockquote> <p>Thus, your problem is solved like so:</p> <pre><code>&gt;&gt;&gt; import pytz &gt;&gt;&gt; from datetime import datetime, date, time &gt;&gt;&gt; tz = pytz.timezone("Australia/Melbourne") &gt;&gt;&gt; the_date = date(2012, 4, 1) # use date.today() here &gt;&gt;&gt; midnight_without_tzinfo = datetime.combine(the_date, time()) &gt;&gt;&gt; print midnight_without_tzinfo 2012-04-01 00:00:00 &gt;&gt;&gt; midnight_with_tzinfo = tz.localize(midnight_without_tzinfo) &gt;&gt;&gt; print midnight_with_tzinfo 2012-04-01 00:00:00+11:00 &gt;&gt;&gt; print midnight_with_tzinfo.astimezone(pytz.utc) 2012-03-31 13:00:00+00:00 </code></pre> <p>No guarantees for dates before 1582, though.</p>
29
2008-12-19T18:29:13Z
[ "python", "datetime", "timezone", "utc", "pytz" ]
How do I get the UTC time of "midnight" for a given timezone?
373,370
<p>The best I can come up with for now is this monstrosity:</p> <pre><code>&gt;&gt;&gt; datetime.utcnow() \ ... .replace(tzinfo=pytz.UTC) \ ... .astimezone(pytz.timezone("Australia/Melbourne")) \ ... .replace(hour=0,minute=0,second=0,microsecond=0) \ ... .astimezone(pytz.UTC) \ ... .replace(tzinfo=None) datetime.datetime(2008, 12, 16, 13, 0) </code></pre> <p>I.e., in English, get the current time (in UTC), convert it to some other timezone, set the time to midnight, then convert back to UTC.</p> <p>I'm not just using now() or localtime() as that would use the server's timezone, not the user's timezone.</p> <p>I can't help feeling I'm missing something, any ideas?</p>
20
2008-12-17T01:11:07Z
11,236,372
<p><a href="http://stackoverflow.com/a/381788/4279">@hop's answer</a> is wrong on the day of transition from Daylight Saving Time (DST) e.g., Apr 1, 2012. To fix it <a href="http://pytz.sourceforge.net/#localized-times-and-date-arithmetic"><code>tz.localize()</code></a> could be used:</p> <pre><code>tz = pytz.timezone("Australia/Melbourne") today = datetime.now(tz).date() midnight = tz.localize(datetime.combine(today, time(0, 0)), is_dst=None) utc_dt = midnight.astimezone(pytz.utc) </code></pre> <p>The same with comments:</p> <pre><code>#!/usr/bin/env python from datetime import datetime, time import pytz # pip instal pytz tz = pytz.timezone("Australia/Melbourne") # choose timezone # 1. get correct date for the midnight using given timezone. today = datetime.now(tz).date() # 2. get midnight in the correct timezone (taking into account DST) #NOTE: tzinfo=None and tz.localize() # assert that there is no dst transition at midnight (`is_dst=None`) midnight = tz.localize(datetime.combine(today, time(0, 0)), is_dst=None) # 3. convert to UTC (no need to call `utc.normalize()` due to UTC has no # DST transitions) fmt = '%Y-%m-%d %H:%M:%S %Z%z' print midnight.astimezone(pytz.utc).strftime(fmt) </code></pre>
20
2012-06-27T23:57:46Z
[ "python", "datetime", "timezone", "utc", "pytz" ]
Secure, sandboxable user exposed programming language / environment?
373,406
<p>Beyond offering an API for my website, I'd like to offer users the ability to write simple scripts that would run on my servers . The scripts would have access to objects owned by the user and be able to manipulate, modify, and otherwise process their data.</p> <p>I'd like to be able to limit resources taken by these scripts at a fine level (eg. max execution time should be 100ms). I'd also like to ensure a secure sandbox such that each user will have access to only a limited set of data and resources, and be prevented from accessing disk, other people's data, etc.</p> <p>Generally the scripts will be very simple (eg. create the sum or average of the values that match certain criteria), and they'll often be used in templates (eg. fill in the value of this cell or html element with the average or sum).</p> <p>Ideally I'd like to use a sandboxed subset of a well know, commonly available programming language so it's easy for users to pick up. The backend is written in Python, so a Python based language could have benefits, but I'm open to other languages and technologies. Javascript is also attractive due to its simple nature and common availability.</p> <p>The languages should support creation of DSLs and libraries. </p> <p>The target audience is a general user base for a web based application, not necessarily very technical. In other words, it's not targeted at a base with particular knowledge of any particular programming language. My expectation is a subset of users will create scripts that will be used by the larger majority. </p> <p>Any ideas or recommendations for the language and technology? Any examples of others trying this and the successes and failures they encountered?</p>
7
2008-12-17T01:38:54Z
373,415
<p>I use Lua for this, but it's directed at a Lua capable community. So my answer would be who are your users?</p> <p>If your users are internal, like my case, and proficient with Python use Python. However if this is something for the world wide web, I'd probably choose javascript, because its the lingua franca, (every developer knows it, and its easy to pickup). As for an Engine... well V8 would be nice, but its not 100% thread safe, in that you can't run several engine within the same process in a lock free manner, as you can with SpiderMonkey. So You might want to use that. Also since javascript is sandboxed by default you won't have to worry about implementing much on your side.</p>
2
2008-12-17T01:48:12Z
[ "javascript", "python", "sandbox" ]
split string on a number of different characters
373,459
<p>I'd like to split a string using one or more separator characters.</p> <p>E.g. "a b.c", split on " " and "." would give the list ["a", "b", "c"].</p> <p>At the moment, I can't see anything in the standard library to do this, and my own attempts are a bit clumsy. E.g.</p> <pre><code>def my_split(string, split_chars): if isinstance(string_L, basestring): string_L = [string_L] try: split_char = split_chars[0] except IndexError: return string_L res = [] for s in string_L: res.extend(s.split(split_char)) return my_split(res, split_chars[1:]) print my_split("a b.c", [' ', '.']) </code></pre> <p>Horrible! Any better suggestions?</p>
11
2008-12-17T02:06:01Z
373,474
<pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; re.split('[ .]', 'a b.c') ['a', 'b', 'c'] </code></pre>
37
2008-12-17T02:16:43Z
[ "python", "string", "split" ]
split string on a number of different characters
373,459
<p>I'd like to split a string using one or more separator characters.</p> <p>E.g. "a b.c", split on " " and "." would give the list ["a", "b", "c"].</p> <p>At the moment, I can't see anything in the standard library to do this, and my own attempts are a bit clumsy. E.g.</p> <pre><code>def my_split(string, split_chars): if isinstance(string_L, basestring): string_L = [string_L] try: split_char = split_chars[0] except IndexError: return string_L res = [] for s in string_L: res.extend(s.split(split_char)) return my_split(res, split_chars[1:]) print my_split("a b.c", [' ', '.']) </code></pre> <p>Horrible! Any better suggestions?</p>
11
2008-12-17T02:06:01Z
373,576
<p>This one replaces all of the separators with the first separator in the list, and then "splits" using that character.</p> <pre><code>def split(string, divs): for d in divs[1:]: string = string.replace(d, divs[0]) return string.split(divs[0]) </code></pre> <p>output:</p> <pre><code>&gt;&gt;&gt; split("a b.c", " .") ['a', 'b', 'c'] &gt;&gt;&gt; split("a b.c", ".") ['a b', 'c'] </code></pre> <p>I do like that 're' solution though.</p>
2
2008-12-17T03:31:13Z
[ "python", "string", "split" ]
split string on a number of different characters
373,459
<p>I'd like to split a string using one or more separator characters.</p> <p>E.g. "a b.c", split on " " and "." would give the list ["a", "b", "c"].</p> <p>At the moment, I can't see anything in the standard library to do this, and my own attempts are a bit clumsy. E.g.</p> <pre><code>def my_split(string, split_chars): if isinstance(string_L, basestring): string_L = [string_L] try: split_char = split_chars[0] except IndexError: return string_L res = [] for s in string_L: res.extend(s.split(split_char)) return my_split(res, split_chars[1:]) print my_split("a b.c", [' ', '.']) </code></pre> <p>Horrible! Any better suggestions?</p>
11
2008-12-17T02:06:01Z
1,000,600
<p>Not very fast but does the job:</p> <pre><code>def my_split(text, seps): for sep in seps: text = text.replace(sep, seps[0]) return text.split(seps[0]) </code></pre>
1
2009-06-16T10:09:29Z
[ "python", "string", "split" ]
split string on a number of different characters
373,459
<p>I'd like to split a string using one or more separator characters.</p> <p>E.g. "a b.c", split on " " and "." would give the list ["a", "b", "c"].</p> <p>At the moment, I can't see anything in the standard library to do this, and my own attempts are a bit clumsy. E.g.</p> <pre><code>def my_split(string, split_chars): if isinstance(string_L, basestring): string_L = [string_L] try: split_char = split_chars[0] except IndexError: return string_L res = [] for s in string_L: res.extend(s.split(split_char)) return my_split(res, split_chars[1:]) print my_split("a b.c", [' ', '.']) </code></pre> <p>Horrible! Any better suggestions?</p>
11
2008-12-17T02:06:01Z
19,211,830
<p>Solution without re:</p> <pre><code>from itertools import groupby sep = ' .,' s = 'a b.c,d' print [''.join(g) for k, g in groupby(s, sep.__contains__) if not k] </code></pre> <p>An explanation is here <a href="http://stackoverflow.com/a/19211729/2468006">http://stackoverflow.com/a/19211729/2468006</a></p>
2
2013-10-06T17:41:01Z
[ "python", "string", "split" ]
Running interactive commands in Paramiko
373,639
<p>I'm trying to run an interactive command through paramiko. The cmd execution tries to prompt for a password but I do not know how to supply the password through paramiko's exec_command and the execution hangs. Is there a way to send values to the terminal if a cmd execution expects input interactively?</p> <pre><code>ssh = paramiko.SSHClient() ssh.connect(server, username=username, password=password) ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command("psql -U factory -d factory -f /tmp/data.sql") </code></pre> <p>Does anyone know how this can addressed? Thank you.</p>
20
2008-12-17T04:16:02Z
373,742
<p>I'm not familiar with paramiko, but this may work: </p> <pre><code>ssh_stdin.write('input value') ssh_stdin.flush() </code></pre> <p>For information on stdin:</p> <p><a href="http://docs.python.org/library/sys.html?highlight=stdin#sys.stdin" rel="nofollow">http://docs.python.org/library/sys.html?highlight=stdin#sys.stdin</a></p>
3
2008-12-17T05:44:53Z
[ "python", "ssh", "paramiko" ]
Running interactive commands in Paramiko
373,639
<p>I'm trying to run an interactive command through paramiko. The cmd execution tries to prompt for a password but I do not know how to supply the password through paramiko's exec_command and the execution hangs. Is there a way to send values to the terminal if a cmd execution expects input interactively?</p> <pre><code>ssh = paramiko.SSHClient() ssh.connect(server, username=username, password=password) ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command("psql -U factory -d factory -f /tmp/data.sql") </code></pre> <p>Does anyone know how this can addressed? Thank you.</p>
20
2008-12-17T04:16:02Z
373,870
<p>The full paramiko distribution ships with a lot of good <a href="https://github.com/paramiko/paramiko/tree/master/demos">demos</a>.</p> <p>In the demos subdirectory, <code>demo.py</code> and <code>interactive.py</code> have full interactive TTY examples which would probably be overkill for your situation.</p> <p>In your example above <code>ssh_stdin</code> acts like a standard Python file object, so <code>ssh_stdin.write</code> should work so long as the channel is still open.</p> <p>I've never needed to write to stdin, but the docs suggest that a channel is closed as soon as a command exits, so using the standard <code>stdin.write</code> method to send a password up probably won't work. There are lower level paramiko commands on the channel itself that give you more control - see how the <a href="http://docs.paramiko.org/paramiko.SSHClient-class.html#exec_command"><code>SSHClient.exec_command</code></a> method is implemented for all the gory details.</p>
22
2008-12-17T07:12:19Z
[ "python", "ssh", "paramiko" ]
Running interactive commands in Paramiko
373,639
<p>I'm trying to run an interactive command through paramiko. The cmd execution tries to prompt for a password but I do not know how to supply the password through paramiko's exec_command and the execution hangs. Is there a way to send values to the terminal if a cmd execution expects input interactively?</p> <pre><code>ssh = paramiko.SSHClient() ssh.connect(server, username=username, password=password) ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command("psql -U factory -d factory -f /tmp/data.sql") </code></pre> <p>Does anyone know how this can addressed? Thank you.</p>
20
2008-12-17T04:16:02Z
3,096,204
<p>You need Pexpect to get the best of both worlds (expect and ssh wrappers).</p>
4
2010-06-22T18:51:33Z
[ "python", "ssh", "paramiko" ]
Running interactive commands in Paramiko
373,639
<p>I'm trying to run an interactive command through paramiko. The cmd execution tries to prompt for a password but I do not know how to supply the password through paramiko's exec_command and the execution hangs. Is there a way to send values to the terminal if a cmd execution expects input interactively?</p> <pre><code>ssh = paramiko.SSHClient() ssh.connect(server, username=username, password=password) ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command("psql -U factory -d factory -f /tmp/data.sql") </code></pre> <p>Does anyone know how this can addressed? Thank you.</p>
20
2008-12-17T04:16:02Z
12,431,170
<p>I had the same problem trying to make an interactive ssh session using <a href="https://github.com/bitprophet/ssh/">ssh</a>, a fork of Paramiko.</p> <p>I dug around and found this article:</p> <p><a href="http://jessenoller.com/2009/02/05/ssh-programming-with-paramiko-completely-different/">http://jessenoller.com/2009/02/05/ssh-programming-with-paramiko-completely-different/</a></p> <p>To continue your example you could do</p> <pre><code>ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command("psql -U factory -d factory -f /tmp/data.sql") ssh_stdin.write('password\n') ssh_stdin.flush() output = ssh_stdout.read() </code></pre> <p>The article goes more in depth, describing a fully interactive shell around exec_command. I found this a lot easier to use than the examples in the source.</p>
5
2012-09-14T19:58:35Z
[ "python", "ssh", "paramiko" ]
Running interactive commands in Paramiko
373,639
<p>I'm trying to run an interactive command through paramiko. The cmd execution tries to prompt for a password but I do not know how to supply the password through paramiko's exec_command and the execution hangs. Is there a way to send values to the terminal if a cmd execution expects input interactively?</p> <pre><code>ssh = paramiko.SSHClient() ssh.connect(server, username=username, password=password) ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command("psql -U factory -d factory -f /tmp/data.sql") </code></pre> <p>Does anyone know how this can addressed? Thank you.</p>
20
2008-12-17T04:16:02Z
37,521,010
<p>Take a look at example and do in similar way </p> <p>(sorce from <a href="http://jessenoller.com/2009/02/05/ssh-programming-with-paramiko-completely-different/" rel="nofollow">http://jessenoller.com/2009/02/05/ssh-programming-with-paramiko-completely-different/</a>):</p> <pre><code> ssh.connect('127.0.0.1', username='jesse', password='lol') stdin, stdout, stderr = ssh.exec_command( "sudo dmesg") stdin.write('lol\n') stdin.flush() data = stdout.read.splitlines() for line in data: if line.split(':')[0] == 'AirPort': print line </code></pre>
0
2016-05-30T08:28:50Z
[ "python", "ssh", "paramiko" ]
Running interactive commands in Paramiko
373,639
<p>I'm trying to run an interactive command through paramiko. The cmd execution tries to prompt for a password but I do not know how to supply the password through paramiko's exec_command and the execution hangs. Is there a way to send values to the terminal if a cmd execution expects input interactively?</p> <pre><code>ssh = paramiko.SSHClient() ssh.connect(server, username=username, password=password) ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command("psql -U factory -d factory -f /tmp/data.sql") </code></pre> <p>Does anyone know how this can addressed? Thank you.</p>
20
2008-12-17T04:16:02Z
39,741,016
<pre><code>ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(server_IP,22,username, password) stdin, stdout, stderr = ssh.exec_command('/Users/lteue/Downloads/uecontrol-CXC_173_6456-R32A01/uecontrol.sh -host localhost ') alldata = "" while not stdout.channel.exit_status_ready(): solo_line = "" # Print stdout data when available if stdout.channel.recv_ready(): # Retrieve the first 1024 bytes solo_line = stdout.channel.recv(1024) alldata += solo_line if(cmp(solo_line,'uec&gt; ') ==0 ): #Change Conditionals to your code here if num_of_input == 0 : data_buffer = "" for cmd in commandList : #print cmd stdin.channel.send(cmd) # send input commmand 1 num_of_input += 1 if num_of_input == 1 : stdin.channel.send('q \n') # send input commmand 2 , in my code is exit the interactive session, the connect will close. num_of_input += 1 print alldata ssh.close() </code></pre> <p>Why the stdout.read() will hang if use dierectly without checking stdout.channel.recv_ready(): in while stdout.channel.exit_status_ready(): </p> <p>For my case ,after run command on remote server , the session is waiting for user input , after input 'q' ,it will close the connection . But before inputting 'q' , the stdout.read() will waiting for EOF,seems this methord does not works if buffer is larger .</p> <ul> <li><strong>I tried stdout.read(1) in while , it works<br> I tried stdout.readline() in while , it works also.<br> stdin, stdout, stderr = ssh.exec_command('/Users/lteue/Downloads/uecontrol')<br> stdout.read() will hang</strong></li> </ul>
0
2016-09-28T07:39:47Z
[ "python", "ssh", "paramiko" ]
Convert C++ Header Files To Python
374,217
<p>I have a C++ header that contains #define statements, Enums and Structures. I have tried using the h2py.py script that is included with Python to no avail (except giving me the #defines converted). Any help would be greatly appreciated.</p>
7
2008-12-17T10:53:00Z
375,098
<p>From what I can tell, h2py.py isn't intended to convert anything other than #define macros. I did run across <a href="http://sourceforge.net/projects/cppheaderparser/" rel="nofollow">cppheaderparser</a>, which might be worth a look.</p>
1
2008-12-17T16:18:18Z
[ "c++", "python", "data-structures", "enums", "header" ]
Convert C++ Header Files To Python
374,217
<p>I have a C++ header that contains #define statements, Enums and Structures. I have tried using the h2py.py script that is included with Python to no avail (except giving me the #defines converted). Any help would be greatly appreciated.</p>
7
2008-12-17T10:53:00Z
375,101
<p>Where did you get the idea that h2py had anything to do with structs or enums?</p> <p>From the source</p> <pre><code># Read #define's and translate to Python code. # Handle #include statements. # Handle #define macros with one argument. </code></pre> <p>The words 'enum' and 'struct' never appear in the module.</p>
-1
2008-12-17T16:19:19Z
[ "c++", "python", "data-structures", "enums", "header" ]
Convert C++ Header Files To Python
374,217
<p>I have a C++ header that contains #define statements, Enums and Structures. I have tried using the h2py.py script that is included with Python to no avail (except giving me the #defines converted). Any help would be greatly appreciated.</p>
7
2008-12-17T10:53:00Z
375,270
<p>I don't know h2py, but you may want to look at 'ctypes' and 'ctypeslib'. ctypes is included with python 2.5+, and is targeted at creating binary compatibility with c-structs.</p> <p>If you add ctypeslib, you get a sub-tool called codegen, which has a 'h2xml.py' script, and a 'xml2py.py', the combination of which will auto-generate the python code you're looking for from C++ headers.</p> <p>ctypeslib:<a href="http://pypi.python.org/pypi/ctypeslib/0.5.4a" rel="nofollow">http://pypi.python.org/pypi/ctypeslib/0.5.4a</a></p> <p>h2xml.py will require another tool called gccxml: <a href="http://www.gccxml.org/HTML/Index.html" rel="nofollow">http://www.gccxml.org/HTML/Index.html</a></p> <p>it's best to check out (via CVS) the latest version of gccxml and build it yourself (actually easier done than said). The pre-packaged version is old.</p>
11
2008-12-17T17:06:54Z
[ "c++", "python", "data-structures", "enums", "header" ]
Convert C++ Header Files To Python
374,217
<p>I have a C++ header that contains #define statements, Enums and Structures. I have tried using the h2py.py script that is included with Python to no avail (except giving me the #defines converted). Any help would be greatly appreciated.</p>
7
2008-12-17T10:53:00Z
848,137
<p>Just found <a href="http://code.google.com/p/pycparser/" rel="nofollow">pycparser</a>. May be useful.</p>
2
2009-05-11T13:39:54Z
[ "c++", "python", "data-structures", "enums", "header" ]
How to retrieve the parent node using cElementTree?
374,245
<p>for the xml </p> <pre><code>&lt;grandparent&gt; &lt;parent1&gt; &lt;child&gt;data1&lt;/child&gt; &lt;/parent1&gt; &lt;parent2&gt; &lt;child&gt;data2&lt;/child&gt; &lt;/parent2&gt; &lt;/grandparent&gt; </code></pre> <p>I need the list containing tuples of parent,data for each parent in xml.</p> <p>Is there a way to do it USING cElementTree? I am able to do it for child,data, but unfortunately child is identical in all the values, hence it is of not much use.</p>
8
2008-12-17T11:11:33Z
374,565
<p>It seems you can get access to the parent from the child using version 1.3 of ElementTree (check <a href="http://effbot.org/zone/element-xpath.htm" rel="nofollow">http://effbot.org/zone/element-xpath.htm</a>), by using xpath commands like <code>child.find('../parent')</code>. But I think python ships with version 1.2 or something.</p> <p>You should also check for lxml which is compatible with etree and has full Xpath support <a href="http://lxml.de/" rel="nofollow">http://lxml.de/</a></p>
4
2008-12-17T13:46:40Z
[ "python", "celementtree" ]
How to retrieve the parent node using cElementTree?
374,245
<p>for the xml </p> <pre><code>&lt;grandparent&gt; &lt;parent1&gt; &lt;child&gt;data1&lt;/child&gt; &lt;/parent1&gt; &lt;parent2&gt; &lt;child&gt;data2&lt;/child&gt; &lt;/parent2&gt; &lt;/grandparent&gt; </code></pre> <p>I need the list containing tuples of parent,data for each parent in xml.</p> <p>Is there a way to do it USING cElementTree? I am able to do it for child,data, but unfortunately child is identical in all the values, hence it is of not much use.</p>
8
2008-12-17T11:11:33Z
12,533,735
<pre><code>parent_map = dict((c, p) for p in tree.getiterator() for c in p) parent_map[el].remove(el) </code></pre>
5
2012-09-21T15:39:38Z
[ "python", "celementtree" ]
How to retrieve the parent node using cElementTree?
374,245
<p>for the xml </p> <pre><code>&lt;grandparent&gt; &lt;parent1&gt; &lt;child&gt;data1&lt;/child&gt; &lt;/parent1&gt; &lt;parent2&gt; &lt;child&gt;data2&lt;/child&gt; &lt;/parent2&gt; &lt;/grandparent&gt; </code></pre> <p>I need the list containing tuples of parent,data for each parent in xml.</p> <p>Is there a way to do it USING cElementTree? I am able to do it for child,data, but unfortunately child is identical in all the values, hence it is of not much use.</p>
8
2008-12-17T11:11:33Z
38,211,083
<p>This syntax seemed to work for cElementTree </p> <pre><code>ET.fromstring("&lt;c&gt;&lt;a&gt;&lt;b&gt;&lt;/b&gt;&lt;/a&gt;&lt;/c&gt;").find('.//b/..') </code></pre> <p>No going to base parent, and using double slash then single slash in path.<br> (would have posted as a comment to above thread but it seems I have no privilege to)</p>
0
2016-07-05T19:20:56Z
[ "python", "celementtree" ]
conversion of unicode string in python
374,318
<p>I need to convert unicode strings in Python to other types such as unsigned and signed int 8 bits,unsigned and signed int 16 bits,unsigned and signed int 32 bits,unsigned and signed int 64 bits,double,float,string,unsigned and signed 8 bit,unsigned and signed 16 bit, unsigned and signed 32 bit,unsigned and signed 64 bit.</p> <p>I need help from u people.</p>
3
2008-12-17T11:52:51Z
374,335
<p>use <a href="http://docs.python.org/library/functions.html#int"><code>int()</code></a> to convert the string to an integer. Python doesn't have different fixed-width integers so you'll just get one type of thing out.</p> <p>Then use <a href="http://docs.python.org/library/struct.html"><code>struct</code></a> to pack the integer into a fixed width:</p> <pre><code>res = struct.pack("=B",i) ## uint8_t res = struct.pack("=b",i) ## int8_t res = struct.pack("=H",i) ## uint16_t res = struct.pack("=h",i) ## int16_t res = struct.pack("=I",i) ## uint32_t res = struct.pack("=i",i) ## int32_t res = struct.pack("=Q",i) ## uint64_t res = struct.pack("=q",i) ## int64_t res = struct.pack("=f",i) ## float res = struct.pack("=d",i) ## double </code></pre> <p><code>struct</code> produces a byte-string containing the number in binary.</p> <p>EDIT: From the comments it sounds like you just want to convert the string (of decimal digits) into an integer. Just use <code>int()</code> for that, however you won't get all the complicated overflow/underflow semantics of the specified types. You can't reproduce that in python, at least not without writing a whole lot of code.</p> <p>I think if you want any more help you'll have to be more precise about what you want to achieve. </p>
10
2008-12-17T11:58:56Z
[ "python", "string", "unicode", "unsigned", "signed" ]
Where is a python real project to be used as example for the unit-test part?
374,480
<p>I'm looking for a python project to use as example to copy the design of the unit test parts.</p> <p>The project should have these features:</p> <ol> <li>its code is almost fully unit tested</li> <li>the code is distributed in many packages, there are more that one level of packages </li> <li>all the test can be run with a single command, for example with <code>python test.py</code></li> </ol> <p>I need that the project should use the same test convention for all the code contained. I saw the whole python project but the the various packages are tested with different conventions. For example the setuptools packages uses an ad hoc adaption of unittest library while the other packages doesn't. </p> <p>I need that the project doesn't use a ad-hoc or a highly customized testing framework, because I want reuse its test architecture in my project.</p>
4
2008-12-17T13:05:08Z
374,514
<p>Maybe <a href="http://code.google.com/p/python-nose/" rel="nofollow">Nose</a> itself?</p>
4
2008-12-17T13:23:52Z
[ "python", "unit-testing" ]
Where is a python real project to be used as example for the unit-test part?
374,480
<p>I'm looking for a python project to use as example to copy the design of the unit test parts.</p> <p>The project should have these features:</p> <ol> <li>its code is almost fully unit tested</li> <li>the code is distributed in many packages, there are more that one level of packages </li> <li>all the test can be run with a single command, for example with <code>python test.py</code></li> </ol> <p>I need that the project should use the same test convention for all the code contained. I saw the whole python project but the the various packages are tested with different conventions. For example the setuptools packages uses an ad hoc adaption of unittest library while the other packages doesn't. </p> <p>I need that the project doesn't use a ad-hoc or a highly customized testing framework, because I want reuse its test architecture in my project.</p>
4
2008-12-17T13:05:08Z
374,521
<p>Well, your specs point directly at a somewhat famous open source project, the <a href="http://svn.python.org/view/python/trunk/Lib/" rel="nofollow">Python Library</a>. Have a look at <a href="http://svn.python.org/view/python/trunk/Lib/test/regrtest.py?rev=63042&amp;view=markup" rel="nofollow">python/trunk/Lib/test/regrtest.py</a>, which will find all modules whose name is "test_*" in the <a href="http://svn.python.org/view/python/trunk/Lib/test/" rel="nofollow">test directory</a>, and run them.</p>
1
2008-12-17T13:27:04Z
[ "python", "unit-testing" ]
Where is a python real project to be used as example for the unit-test part?
374,480
<p>I'm looking for a python project to use as example to copy the design of the unit test parts.</p> <p>The project should have these features:</p> <ol> <li>its code is almost fully unit tested</li> <li>the code is distributed in many packages, there are more that one level of packages </li> <li>all the test can be run with a single command, for example with <code>python test.py</code></li> </ol> <p>I need that the project should use the same test convention for all the code contained. I saw the whole python project but the the various packages are tested with different conventions. For example the setuptools packages uses an ad hoc adaption of unittest library while the other packages doesn't. </p> <p>I need that the project doesn't use a ad-hoc or a highly customized testing framework, because I want reuse its test architecture in my project.</p>
4
2008-12-17T13:05:08Z
374,532
<p>First, read about <a href="http://www.python.org/doc/2.5.2/lib/module-unittest.html" rel="nofollow">unittest</a>. The documentation contains examples.</p> <p>Second, since you want packages (not modules) the list is shorter. There are 15 packages in Python 2.5 distribution. Pick One At Random. Here's a subset that might meet some of your criteria. </p> <ul> <li><p>bsddb: 7 modules - many test - test_all.py</p></li> <li><p>ctypes: 4 modules - tests - runtests.py</p></li> <li><p>distutils: many modules - tests - test_dist.py</p></li> <li><p>email: many modules - tests - test_email.py</p></li> <li><p>sqlite3 - 2 modules - tests - (not clear if there's an overall test, I got bored of looking)</p></li> </ul>
0
2008-12-17T13:33:06Z
[ "python", "unit-testing" ]
Where is a python real project to be used as example for the unit-test part?
374,480
<p>I'm looking for a python project to use as example to copy the design of the unit test parts.</p> <p>The project should have these features:</p> <ol> <li>its code is almost fully unit tested</li> <li>the code is distributed in many packages, there are more that one level of packages </li> <li>all the test can be run with a single command, for example with <code>python test.py</code></li> </ol> <p>I need that the project should use the same test convention for all the code contained. I saw the whole python project but the the various packages are tested with different conventions. For example the setuptools packages uses an ad hoc adaption of unittest library while the other packages doesn't. </p> <p>I need that the project doesn't use a ad-hoc or a highly customized testing framework, because I want reuse its test architecture in my project.</p>
4
2008-12-17T13:05:08Z
382,862
<p><a href="http://www.djangoproject.com/" rel="nofollow">Django</a> is a clean project that has a nice range of unit testing.</p> <p><a href="http://docs.djangoproject.com/en/dev/topics/testing/#topics-testing" rel="nofollow">Have a look</a> at how they propose you test your own projects.</p> <p><a href="http://code.djangoproject.com/browser/django/trunk/tests" rel="nofollow">Have a look</a> at the unit testing code of the framework itself.</p>
4
2008-12-20T03:43:25Z
[ "python", "unit-testing" ]
Where is a python real project to be used as example for the unit-test part?
374,480
<p>I'm looking for a python project to use as example to copy the design of the unit test parts.</p> <p>The project should have these features:</p> <ol> <li>its code is almost fully unit tested</li> <li>the code is distributed in many packages, there are more that one level of packages </li> <li>all the test can be run with a single command, for example with <code>python test.py</code></li> </ol> <p>I need that the project should use the same test convention for all the code contained. I saw the whole python project but the the various packages are tested with different conventions. For example the setuptools packages uses an ad hoc adaption of unittest library while the other packages doesn't. </p> <p>I need that the project doesn't use a ad-hoc or a highly customized testing framework, because I want reuse its test architecture in my project.</p>
4
2008-12-17T13:05:08Z
32,449,439
<p>You can check python's source. Most of it is written in python. specially the unittest modules.</p> <p>&lt;rant>python module organization and unittest in particular is a black art. It reminds me of a mix of perl (odd, undocumented workarounds for every basic thing --the unittest manual never even show how to import an external module) and java (restrictive directory and naming conventions)&lt;/rant></p> <p>take a look at the unit test setup for the <a href="https://hg.python.org/unittest2" rel="nofollow">unittest module</a>. (there is no source browse, you have to <code>hg clone</code> that url)</p> <p>here is the setup.py portion to kick unittests, besides all the rest there:</p> <pre><code># above here, juggle paths from setuptools import setup params['entry_points'] = { 'console_scripts': [ 'unit2 = unittest2.__main__:main_', ], } params['test_suite'] = 'unittest2.collector' setup(**params) </code></pre> <p>and even all they did is still not enough to simply run <code>setup.py test</code>. You will learn that most teams already gave up having what you are asking for and simply add a test_run.py or such to the project. I know all the project i contribute to did.</p> <p>Take also a look at the nose answer above, that is a good one, their setup.py is very clean despite some 2, 3, 2to3 support craze. that is a project that aims to make unittest (and general testing) easier and more convenient. well, even them have a <code>selftest.py</code> script in the project root to try to kick the tests.</p>
0
2015-09-08T04:49:19Z
[ "python", "unit-testing" ]
need help-variable creation in Python
374,572
<p>I want to create variables as <code>a1</code>,<code>a2</code>,<code>a3</code>...<code>a10</code>. For that I used a for loop. As the variable in loop increments I need to create a variable as above.</p> <p>Can anyone give me an idea?</p> <p>At the time of creation I also need to be able to assign values to them.</p> <p>That's where I'm getting syntax error.</p>
-1
2008-12-17T13:47:51Z
374,579
<p>Usually, we use a list, not a bunch of individual variables.</p> <pre><code>a = 10*[0] a[0], a[1], a[2], a[9] </code></pre>
13
2008-12-17T13:50:42Z
[ "python", "variables" ]
need help-variable creation in Python
374,572
<p>I want to create variables as <code>a1</code>,<code>a2</code>,<code>a3</code>...<code>a10</code>. For that I used a for loop. As the variable in loop increments I need to create a variable as above.</p> <p>Can anyone give me an idea?</p> <p>At the time of creation I also need to be able to assign values to them.</p> <p>That's where I'm getting syntax error.</p>
-1
2008-12-17T13:47:51Z
374,604
<p>You can use the exec function:</p> <pre><code>for i in range(0,10): exec("a%d=%d" % (i,i)) </code></pre> <p>Not very pythonic way of doing things.</p>
-1
2008-12-17T13:59:16Z
[ "python", "variables" ]
need help-variable creation in Python
374,572
<p>I want to create variables as <code>a1</code>,<code>a2</code>,<code>a3</code>...<code>a10</code>. For that I used a for loop. As the variable in loop increments I need to create a variable as above.</p> <p>Can anyone give me an idea?</p> <p>At the time of creation I also need to be able to assign values to them.</p> <p>That's where I'm getting syntax error.</p>
-1
2008-12-17T13:47:51Z
374,636
<p>Following what S.Lott said, you can also use a dict, if you really nead unique names and that the order of the items is not important:</p> <pre><code>data = {} for i in range(0, 10): data['a%d' % i] = i &gt;&gt;&gt;data {'a1': 1, 'a0': 0, 'a3': 3, 'a2': 2, 'a5': 5, 'a4': 4, 'a7': 7, 'a6': 6, 'a9': 9, 'a8': 8} </code></pre> <p>I would add that this is very dangerous to automate variable creation like you want to do, as you might overwrite variables that could already exist.</p>
4
2008-12-17T14:11:45Z
[ "python", "variables" ]
need help-variable creation in Python
374,572
<p>I want to create variables as <code>a1</code>,<code>a2</code>,<code>a3</code>...<code>a10</code>. For that I used a for loop. As the variable in loop increments I need to create a variable as above.</p> <p>Can anyone give me an idea?</p> <p>At the time of creation I also need to be able to assign values to them.</p> <p>That's where I'm getting syntax error.</p>
-1
2008-12-17T13:47:51Z
374,803
<p><code>globals()</code> returns the global dictionary of variables:</p> <pre><code>for i in range(1,6): globals()["a%i" % i] = i print a1, a2, a3, a4, a5 # -&gt; 1 2 3 4 5 </code></pre> <p>But frankly: I'd never do this, polluting the namespace automagically is harmful. I'd rather use a list or a dict.</p>
2
2008-12-17T14:59:54Z
[ "python", "variables" ]
How can I find all the subsets of a set, with exactly n elements?
374,626
<p>I am writing a program in Python, and I realized that a problem I need to solve requires me, given a set <code>S</code> with <code>n</code> elements (|S|=n), to test a function on all possible subsets of a certain order <code>m</code> (i.e. with <em>m</em> number of elements). To use the answer to produce a partial solution, and then try again with the next order m=m+1, until m=n.</p> <p>I am on my way to write a solution of the form:</p> <pre><code>def findsubsets(S, m): subsets = set([]) ... return subsets </code></pre> <p>But knowing Python I expected a solution to be already there.</p> <p>What is the best way to accomplish this?</p>
30
2008-12-17T14:09:18Z
374,645
<p><a href="http://docs.python.org/library/itertools.html#itertools.combinations">itertools.combinations</a> is your friend if you have Python 2.6 or greater. Otherwise, check the link for an implementation of an equivalent function.</p> <pre><code>import itertools def findsubsets(S,m): return set(itertools.combinations(S, m)) </code></pre>
73
2008-12-17T14:15:07Z
[ "python" ]
How can I find all the subsets of a set, with exactly n elements?
374,626
<p>I am writing a program in Python, and I realized that a problem I need to solve requires me, given a set <code>S</code> with <code>n</code> elements (|S|=n), to test a function on all possible subsets of a certain order <code>m</code> (i.e. with <em>m</em> number of elements). To use the answer to produce a partial solution, and then try again with the next order m=m+1, until m=n.</p> <p>I am on my way to write a solution of the form:</p> <pre><code>def findsubsets(S, m): subsets = set([]) ... return subsets </code></pre> <p>But knowing Python I expected a solution to be already there.</p> <p>What is the best way to accomplish this?</p>
30
2008-12-17T14:09:18Z
374,652
<p>It seems like this recipe does the trick: <a href="http://code.activestate.com/recipes/500268/" rel="nofollow">http://code.activestate.com/recipes/500268/</a></p>
2
2008-12-17T14:18:19Z
[ "python" ]
How can I find all the subsets of a set, with exactly n elements?
374,626
<p>I am writing a program in Python, and I realized that a problem I need to solve requires me, given a set <code>S</code> with <code>n</code> elements (|S|=n), to test a function on all possible subsets of a certain order <code>m</code> (i.e. with <em>m</em> number of elements). To use the answer to produce a partial solution, and then try again with the next order m=m+1, until m=n.</p> <p>I am on my way to write a solution of the form:</p> <pre><code>def findsubsets(S, m): subsets = set([]) ... return subsets </code></pre> <p>But knowing Python I expected a solution to be already there.</p> <p>What is the best way to accomplish this?</p>
30
2008-12-17T14:09:18Z
14,285,114
<p>Here's a one-liner that gives you all subsets of the integers [0..n], not just the subsets of a given length:</p> <pre><code>from itertools import combinations, chain allsubsets = lambda n: list(chain(*[combinations(range(n), ni) for ni in range(n+1)])) </code></pre> <p>so e.g.</p> <pre><code>&gt;&gt; allsubsets(3) [(), (0,), (1,), (2,), (0, 1), (0, 2), (1, 2), (0, 1, 2)] </code></pre>
16
2013-01-11T19:16:23Z
[ "python" ]
How can I find all the subsets of a set, with exactly n elements?
374,626
<p>I am writing a program in Python, and I realized that a problem I need to solve requires me, given a set <code>S</code> with <code>n</code> elements (|S|=n), to test a function on all possible subsets of a certain order <code>m</code> (i.e. with <em>m</em> number of elements). To use the answer to produce a partial solution, and then try again with the next order m=m+1, until m=n.</p> <p>I am on my way to write a solution of the form:</p> <pre><code>def findsubsets(S, m): subsets = set([]) ... return subsets </code></pre> <p>But knowing Python I expected a solution to be already there.</p> <p>What is the best way to accomplish this?</p>
30
2008-12-17T14:09:18Z
14,906,199
<p>Here's some pseudocode - you can cut same recursive calls by storing the values for each call as you go and before recursive call checking if the call value is already present.</p> <p>The following algorithm will have all the subsets excluding the empty set.</p> <pre><code>list * subsets(string s, list * v) { if(s.length() == 1) { list.add(s); return v; } else { list * temp = subsets(s[1 to length-1], v); int length = temp-&gt;size(); for(int i=0;i&lt;length;i++) { temp.add(s[0]+temp[i]); } list.add(s[0]); return temp; } } </code></pre> <p>So, for example if s = "123" then output is:</p> <pre><code>1 2 3 12 13 23 123 </code></pre>
2
2013-02-16T02:10:51Z
[ "python" ]
How can I find all the subsets of a set, with exactly n elements?
374,626
<p>I am writing a program in Python, and I realized that a problem I need to solve requires me, given a set <code>S</code> with <code>n</code> elements (|S|=n), to test a function on all possible subsets of a certain order <code>m</code> (i.e. with <em>m</em> number of elements). To use the answer to produce a partial solution, and then try again with the next order m=m+1, until m=n.</p> <p>I am on my way to write a solution of the form:</p> <pre><code>def findsubsets(S, m): subsets = set([]) ... return subsets </code></pre> <p>But knowing Python I expected a solution to be already there.</p> <p>What is the best way to accomplish this?</p>
30
2008-12-17T14:09:18Z
16,915,734
<p>Using the canonical function to get the <a href="http://en.wikipedia.org/wiki/Power_set">powerset</a> from the <a href="http://docs.python.org/2/library/itertools.html#recipes">the itertools recipe</a> page:</p> <pre><code>from itertools import chain, combinations def powerset(iterable): xs = list(iterable) # note we return an iterator rather than a list return chain.from_iterable( combinations(xs,n) for n in range(len(xs)+1) ) </code></pre> <p>Used like:</p> <pre><code>&gt;&gt;&gt; list(powerset("abc")) [(), ('a',), ('b',), ('c',), ('a', 'b'), ('a', 'c'), ('b', 'c'), ('a', 'b', 'c')] &gt;&gt;&gt; list(powerset(set([1,2,3]))) [(), (1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3)] </code></pre> <p>map to sets if you want so you can use union, intersection, etc...:</p> <pre><code>&gt;&gt;&gt; map(set, powerset(set([1,2,3]))) [set([]), set([1]), set([2]), set([3]), set([1, 2]), set([1, 3]), set([2, 3]), set([1, 2, 3])] &gt;&gt;&gt; reduce(lambda x,y: x.union(y), map(set, powerset(set([1,2,3])))) set([1, 2, 3]) </code></pre>
26
2013-06-04T10:41:13Z
[ "python" ]
How can I find all the subsets of a set, with exactly n elements?
374,626
<p>I am writing a program in Python, and I realized that a problem I need to solve requires me, given a set <code>S</code> with <code>n</code> elements (|S|=n), to test a function on all possible subsets of a certain order <code>m</code> (i.e. with <em>m</em> number of elements). To use the answer to produce a partial solution, and then try again with the next order m=m+1, until m=n.</p> <p>I am on my way to write a solution of the form:</p> <pre><code>def findsubsets(S, m): subsets = set([]) ... return subsets </code></pre> <p>But knowing Python I expected a solution to be already there.</p> <p>What is the best way to accomplish this?</p>
30
2008-12-17T14:09:18Z
36,796,196
<p><strong>Without using <code>itertools</code></strong>:</p> <p>In Python 3 you can use <code>yield from</code> to add a subset generator method to buit-in <code>set</code> class:</p> <pre><code>class SetWithSubet(set): def subsets(self): s1 = [] s2 = list(self) def recfunc(i=0): if i == len(s2): yield frozenset(s1) else: yield from recfunc(i + 1) s1.append(s2[ i ]) yield from recfunc(i + 1) s1.pop() yield from recfunc() </code></pre> <p>For example below snippet works as expected:</p> <pre><code>x = SetWithSubet({1,2,3,5,6}) {2,3} in x.subsets() #True set() in x.subsets() #True x in x.subsets() #True x|{7} in x.subsets() #False set([5,3]) in x.subsets() #True - better alternative: set([5,3]) &lt; x len(x.subsets()) #32 </code></pre>
0
2016-04-22T14:14:51Z
[ "python" ]
Should I use get_/set_ prefixes in Python method names?
374,763
<p>In Python properties are used instead of the Java-style getters, setters. So one rarely sees get... or set.. methods in the public interfaces of classes.</p> <p>But in cases were a property is not appropriate one might still end up with methods that behave like getters or setters. Now my questions: Should these method names start with <code>get_</code> / <code>set_</code>? Or is this unpythonic vebosity since it is often obvious what is meant (and one can still use the docstring to clarify non-obvious situations)?</p> <p>This might be a matter of personal taste, but I would be interested in what the majority thinks about this? What would you prefer as an API user?</p> <p>Example: Say we have an object representing multiple cities. One might have a method <code>get_city_by_postalcode(postalcode)</code> or one could use the shorter name <code>city_by_postalcode</code>. I tend towards the later.</p>
7
2008-12-17T14:49:54Z
374,856
<p>I think shorter is better, so I tend to prefer the later. But what's important is to consistent with your project: don't mix the two methods. If you jump into someone else's project, keep what the other developers chose initially.</p>
2
2008-12-17T15:16:03Z
[ "python", "coding-style" ]
Should I use get_/set_ prefixes in Python method names?
374,763
<p>In Python properties are used instead of the Java-style getters, setters. So one rarely sees get... or set.. methods in the public interfaces of classes.</p> <p>But in cases were a property is not appropriate one might still end up with methods that behave like getters or setters. Now my questions: Should these method names start with <code>get_</code> / <code>set_</code>? Or is this unpythonic vebosity since it is often obvious what is meant (and one can still use the docstring to clarify non-obvious situations)?</p> <p>This might be a matter of personal taste, but I would be interested in what the majority thinks about this? What would you prefer as an API user?</p> <p>Example: Say we have an object representing multiple cities. One might have a method <code>get_city_by_postalcode(postalcode)</code> or one could use the shorter name <code>city_by_postalcode</code>. I tend towards the later.</p>
7
2008-12-17T14:49:54Z
374,860
<p>I've seen it done both ways. Coming from an Objective-C background, I usually do <code>foo()/set_foo()</code> if I can't use a property (although I try to use properties whenever possible). It doesn't really matter that much, though, <em>as long as you're consistent</em>.</p> <p>(Of course, in your example, I wouldn't call the method <code>get_city_by_postalcode()</code> at all; I'd probably go with <code>translate_postalcode</code> or something similar that uses a better action verb in the name.)</p>
1
2008-12-17T15:17:01Z
[ "python", "coding-style" ]
Should I use get_/set_ prefixes in Python method names?
374,763
<p>In Python properties are used instead of the Java-style getters, setters. So one rarely sees get... or set.. methods in the public interfaces of classes.</p> <p>But in cases were a property is not appropriate one might still end up with methods that behave like getters or setters. Now my questions: Should these method names start with <code>get_</code> / <code>set_</code>? Or is this unpythonic vebosity since it is often obvious what is meant (and one can still use the docstring to clarify non-obvious situations)?</p> <p>This might be a matter of personal taste, but I would be interested in what the majority thinks about this? What would you prefer as an API user?</p> <p>Example: Say we have an object representing multiple cities. One might have a method <code>get_city_by_postalcode(postalcode)</code> or one could use the shorter name <code>city_by_postalcode</code>. I tend towards the later.</p>
7
2008-12-17T14:49:54Z
375,037
<p>You won't ever loose the chance to make your property behave like a getter/setter later by using <a href="http://users.rcn.com/python/download/Descriptor.htm" rel="nofollow">descriptors</a>. If you want to change a property to be read only you can also replace it with a getter method with the same name as the property and decorate it with @property. So my advice is to avoid getters/setters unless the project you are working on already uses them, because you can always change your mind later and make properties read-only, write-only or whatever without modifying the interface to your class.</p>
4
2008-12-17T16:01:57Z
[ "python", "coding-style" ]
Should I use get_/set_ prefixes in Python method names?
374,763
<p>In Python properties are used instead of the Java-style getters, setters. So one rarely sees get... or set.. methods in the public interfaces of classes.</p> <p>But in cases were a property is not appropriate one might still end up with methods that behave like getters or setters. Now my questions: Should these method names start with <code>get_</code> / <code>set_</code>? Or is this unpythonic vebosity since it is often obvious what is meant (and one can still use the docstring to clarify non-obvious situations)?</p> <p>This might be a matter of personal taste, but I would be interested in what the majority thinks about this? What would you prefer as an API user?</p> <p>Example: Say we have an object representing multiple cities. One might have a method <code>get_city_by_postalcode(postalcode)</code> or one could use the shorter name <code>city_by_postalcode</code>. I tend towards the later.</p>
7
2008-12-17T14:49:54Z
375,160
<p>If it's usable as a property (one value to get or set, and no other parameters, I usually do:</p> <pre><code>class Foo(object): def _get_x(self): pass def _set_x(self, value): pass x = property(_get_x, _set_x) </code></pre> <p>If the getter/setter is any more complex than that, I would use get_x and set_x:</p>
3
2008-12-17T16:35:53Z
[ "python", "coding-style" ]
Should I use get_/set_ prefixes in Python method names?
374,763
<p>In Python properties are used instead of the Java-style getters, setters. So one rarely sees get... or set.. methods in the public interfaces of classes.</p> <p>But in cases were a property is not appropriate one might still end up with methods that behave like getters or setters. Now my questions: Should these method names start with <code>get_</code> / <code>set_</code>? Or is this unpythonic vebosity since it is often obvious what is meant (and one can still use the docstring to clarify non-obvious situations)?</p> <p>This might be a matter of personal taste, but I would be interested in what the majority thinks about this? What would you prefer as an API user?</p> <p>Example: Say we have an object representing multiple cities. One might have a method <code>get_city_by_postalcode(postalcode)</code> or one could use the shorter name <code>city_by_postalcode</code>. I tend towards the later.</p>
7
2008-12-17T14:49:54Z
375,661
<p>If I have to use a getter/setter, I like it this way:</p> <p>Suppose you have a variable self._x. Then x() would return the value of self._x, and setX(x) would set the value of self._x</p>
0
2008-12-17T19:05:50Z
[ "python", "coding-style" ]
How do you test a file.read() error in Python?
374,768
<p>I have the following code (adapted from an example given in <a href="http://diveintopython.net/file_handling/file_objects.html#d0e14928" rel="nofollow">Dive Into Python</a>) that reads the entire contents of a file into a buffer.</p> <pre><code>buffer = "" try: file = open(postFileName, 'rU') try: # Read the entire POST log file into a buffer buffer += file.read() finally: file.close() except IOError: buffer += "The POST file could not be opened." </code></pre> <p>What's bothering me about this code is the inner try/finally block without an except block. Do I need an except block in there? Can the call to <code>read()</code> fail after the call to <code>open()</code> was successful? I know the try-except-finally is now unified, so adding one, at least syntactically, is not a problem.</p> <p>If I add an except block, under what conditions will it be executed, and how do I write a test to make sure it runs under those conditions?</p> <p>Additionally, if I <em>don't</em> need an except block, then why do I need the inner try/finally block at all?</p>
4
2008-12-17T14:51:23Z
374,821
<p>With a recent version of Python, you don't need to nest try-except and try-finally. try-except-finally has been unified:</p> <pre><code>try: non_existing_var except: print 'error' finally: print 'finished' </code></pre>
0
2008-12-17T15:05:38Z
[ "python", "file-io", "error-handling" ]
How do you test a file.read() error in Python?
374,768
<p>I have the following code (adapted from an example given in <a href="http://diveintopython.net/file_handling/file_objects.html#d0e14928" rel="nofollow">Dive Into Python</a>) that reads the entire contents of a file into a buffer.</p> <pre><code>buffer = "" try: file = open(postFileName, 'rU') try: # Read the entire POST log file into a buffer buffer += file.read() finally: file.close() except IOError: buffer += "The POST file could not be opened." </code></pre> <p>What's bothering me about this code is the inner try/finally block without an except block. Do I need an except block in there? Can the call to <code>read()</code> fail after the call to <code>open()</code> was successful? I know the try-except-finally is now unified, so adding one, at least syntactically, is not a problem.</p> <p>If I add an except block, under what conditions will it be executed, and how do I write a test to make sure it runs under those conditions?</p> <p>Additionally, if I <em>don't</em> need an except block, then why do I need the inner try/finally block at all?</p>
4
2008-12-17T14:51:23Z
374,853
<p>Googling a little bit got this <a href="http://www.python.org/doc/2.5/whatsnew/pep-341.html" rel="nofollow">Unified try/except/finally </a></p> <p>Hope it helps ;)</p>
0
2008-12-17T15:15:49Z
[ "python", "file-io", "error-handling" ]
How do you test a file.read() error in Python?
374,768
<p>I have the following code (adapted from an example given in <a href="http://diveintopython.net/file_handling/file_objects.html#d0e14928" rel="nofollow">Dive Into Python</a>) that reads the entire contents of a file into a buffer.</p> <pre><code>buffer = "" try: file = open(postFileName, 'rU') try: # Read the entire POST log file into a buffer buffer += file.read() finally: file.close() except IOError: buffer += "The POST file could not be opened." </code></pre> <p>What's bothering me about this code is the inner try/finally block without an except block. Do I need an except block in there? Can the call to <code>read()</code> fail after the call to <code>open()</code> was successful? I know the try-except-finally is now unified, so adding one, at least syntactically, is not a problem.</p> <p>If I add an except block, under what conditions will it be executed, and how do I write a test to make sure it runs under those conditions?</p> <p>Additionally, if I <em>don't</em> need an except block, then why do I need the inner try/finally block at all?</p>
4
2008-12-17T14:51:23Z
374,895
<p>I find that finally blocks are often overused. The file close (and a few other similar patterns) are so important that Python 3.0 will have a <strong>with</strong> statement just to cover this base in a slightly less obscure way.</p> <ul> <li><p>Do I need an except with a finally? </p> <p>That hits on the confusing nature of this specific example, and why they added the <strong>with</strong> statement. </p> <p>The <strong>finally</strong> does "no matter what" cleanup. Exception or no exception, the <strong>finally</strong> is always executed.</p></li> <li><p>Can the call to read() fail after the call to open() was successful? </p> <p>All OS calls, all I/O calls (almost everything) can raise an exception. All kinds of bad things can happen after open and before read.</p></li> <li><p>If I add an <strong>except</strong> block, under what conditions will it be executed?</p> <p>Read up on files. There are lots of goofy I/O errors that can occur between open and read. Also, read up on the built-in exceptions. <a href="https://docs.python.org/2/library/exceptions.html" rel="nofollow">https://docs.python.org/2/library/exceptions.html</a></p></li> <li><p>How do I write a test to make sure it runs under those conditions?</p> <p>You'll need a mock file object. This object will responds to <code>open</code> but raises an <code>IOError</code> or <code>OSError</code> on every <code>read</code>.</p></li> <li><p>If I don't need an except block, then why do I need the inner try/finally block at all?</p> <p>Cleanup. The <strong>finally</strong> will be executed no matter what exception is raised. </p></li> </ul> <p>Try this. See what it does.</p> <pre><code>try: raise OSError("hi mom") finally: print "Hmmm" </code></pre>
6
2008-12-17T15:29:27Z
[ "python", "file-io", "error-handling" ]
How do you test a file.read() error in Python?
374,768
<p>I have the following code (adapted from an example given in <a href="http://diveintopython.net/file_handling/file_objects.html#d0e14928" rel="nofollow">Dive Into Python</a>) that reads the entire contents of a file into a buffer.</p> <pre><code>buffer = "" try: file = open(postFileName, 'rU') try: # Read the entire POST log file into a buffer buffer += file.read() finally: file.close() except IOError: buffer += "The POST file could not be opened." </code></pre> <p>What's bothering me about this code is the inner try/finally block without an except block. Do I need an except block in there? Can the call to <code>read()</code> fail after the call to <code>open()</code> was successful? I know the try-except-finally is now unified, so adding one, at least syntactically, is not a problem.</p> <p>If I add an except block, under what conditions will it be executed, and how do I write a test to make sure it runs under those conditions?</p> <p>Additionally, if I <em>don't</em> need an except block, then why do I need the inner try/finally block at all?</p>
4
2008-12-17T14:51:23Z
374,904
<p>I disagree with the other answers mentioning unifying the try / except / finally blocks. That would change the behaviour, as you wouldn't want the finally block to try to close the file if the open failed. The split blocks are correct here (though it may be better using the new "<code>with open(filename,'rU') as f</code>" syntax instead).</p> <p>There are reasons the read() could fail. For instance the data could be too big to fit into memory, or the user may have signalled an interrupt with control-C. Those cases won't be caught by the IOError, but are left to be handled (or not) by the caller who may want to do different things depending on the nature of the application. However, the code does still have an obligation to clean up the file, even where it doesn't deal with the error, hence the finally without the except.</p>
3
2008-12-17T15:31:43Z
[ "python", "file-io", "error-handling" ]
How to send clip names using LiveAPI (of Ableton Live)
375,052
<p>When an audio or midi clip is played (triggered), its name needs to be sent using OSC to <a href="http://vvvv.org/" rel="nofollow">another application</a>.</p> <p><a href="http://www.assembla.com/wiki/show/live-api" rel="nofollow">LiveAPI</a> is an interface which allows one to explore and automate <a href="http://www.ableton.com/" rel="nofollow">Ableton Live</a> using python scripts.</p> <p>The code to do this must be written in a python script, which must be placed in a specific folder where Ableton Live can find it, selected in Live's Preferences.</p> <p>More information about the LiveAPI can be found on these sites:<br/> <a href="http://www.assembla.com/wiki/show/live-api" rel="nofollow">http://www.assembla.com/wiki/show/live-api</a><br/> <a href="http://groups.google.com/group/liveapi" rel="nofollow">http://groups.google.com/group/liveapi</a></p>
4
2008-12-17T16:05:31Z
491,274
<p>According to <a href="http://svn2.assembla.com/svn/live-api/trunk/docs/Ableton%20Live%20API/modules/Clip.Clip.html" rel="nofollow">the LiveAPI documentation</a>, the Clip object has a "name" attribute which holds the clip name. Presumably that's what you want to send in your OSC packets.</p> <p>Also, it's worth mentioning that the Max/MSP support in Live8 will probably be a lot more comfortable to work with than LiveAPI, which is pretty much a dead project. Max/MSP supposedly has OSC support, which was added to support the JazzMutant Lemur, but I'm not sure how much of that made it into Live. Anyways, it's worth keeping in mind for when Live8 is released.</p>
2
2009-01-29T11:30:36Z
[ "python", "api", "osc", "ableton-live" ]
How to send clip names using LiveAPI (of Ableton Live)
375,052
<p>When an audio or midi clip is played (triggered), its name needs to be sent using OSC to <a href="http://vvvv.org/" rel="nofollow">another application</a>.</p> <p><a href="http://www.assembla.com/wiki/show/live-api" rel="nofollow">LiveAPI</a> is an interface which allows one to explore and automate <a href="http://www.ableton.com/" rel="nofollow">Ableton Live</a> using python scripts.</p> <p>The code to do this must be written in a python script, which must be placed in a specific folder where Ableton Live can find it, selected in Live's Preferences.</p> <p>More information about the LiveAPI can be found on these sites:<br/> <a href="http://www.assembla.com/wiki/show/live-api" rel="nofollow">http://www.assembla.com/wiki/show/live-api</a><br/> <a href="http://groups.google.com/group/liveapi" rel="nofollow">http://groups.google.com/group/liveapi</a></p>
4
2008-12-17T16:05:31Z
496,286
<p>I know about Max 4 Live, but as I see it, it's kind of a different thing. Yes, it will probably be able to interface with Live to do all the stuff which people do now with LiveAPI. Some even think that M4L may not even go through LiveAPI, and use some internal interface instead (since Ableton and Cycling 74 are developing it together). From the promo videos on ableton.com site I think that M4L will mostly be about making and modifying sound, and not so much about controlling/reading other instruments, effects, clips etc.</p> <p>I would not say that LiveAPI project is dead, because a lot of hardware MIDI controllers rely on LiveAPI to do some auto-mapping magic. When you look at the MIDI Remote Scripts folder in Live, you'll see that each controller has it's own folder with a python script. So I definitely think that LiveAPI is going to stay, and that this door into Live will remain open. They even created a new folder called Framework which contains some newer code, probably required for the new Akai controller to work with Live (that is what people believe in theory).</p> <p>The application I plan to use the playing clip's name is called vvvv, so I don't want to have to bring Max into this, because it is not really needed.</p> <p>I had some success with someone's modification of the original LiveAPI code, but only worked when I request all the clips' names, not when I asked for just a single one. I didn't have time to play with it later, and the thing for which I was preparing this has passed. I plan to work that out eventually, but it's not that urgent anymore.</p>
0
2009-01-30T16:57:08Z
[ "python", "api", "osc", "ableton-live" ]
How do I get the time a file was last modified in Python?
375,154
<p>Assuming the file exists (using <code>os.path.exists(filename)</code> to first make sure that it does), how do I display the time a file was last modified? This is on Linux if that makes any difference.</p>
30
2008-12-17T16:33:41Z
375,168
<p><a href="http://docs.python.org/library/os.html#os.stat">os.stat()</a></p> <pre><code>import os filename = "/etc/fstab" statbuf = os.stat(filename) print "Modification time:",statbuf.st_mtime </code></pre> <p>Linux does not record the creation time of a file (<a href="http://unix.stackexchange.com/q/24441/61642">for most fileystems</a>).</p>
30
2008-12-17T16:38:08Z
[ "python", "file", "time" ]
How do I get the time a file was last modified in Python?
375,154
<p>Assuming the file exists (using <code>os.path.exists(filename)</code> to first make sure that it does), how do I display the time a file was last modified? This is on Linux if that makes any difference.</p>
30
2008-12-17T16:33:41Z
375,186
<pre><code>&gt;&gt;&gt; import os &gt;&gt;&gt; f = os.path.getmtime('test1.jpg') &gt;&gt;&gt; f 1223995325.0 </code></pre> <p>since the beginning of (epoch)</p>
79
2008-12-17T16:41:59Z
[ "python", "file", "time" ]
Non-blocking read on a subprocess.PIPE in python
375,427
<p>I'm using the <a href="http://docs.python.org/library/subprocess.html">subprocess module</a> to start a subprocess and connect to it's output stream (stdout). I want to be able to execute non-blocking reads on its stdout. Is there a way to make .readline non-blocking or to check if there is data on the stream before I invoke <code>.readline</code>? I'd like this to be portable or at least work under Windows and Linux.</p> <p>here is how I do it for now (It's blocking on the <code>.readline</code> if no data is avaible):</p> <pre><code>p = subprocess.Popen('myprogram.exe', stdout = subprocess.PIPE) output_str = p.stdout.readline() </code></pre>
327
2008-12-17T17:56:34Z
375,503
<p>One solution is to make another process to perform your read of the process, or make a thread of the process with a timeout.</p> <p>Here's the threaded version of a timeout function:</p> <p><a href="http://code.activestate.com/recipes/473878/">http://code.activestate.com/recipes/473878/</a></p> <p>However, do you need to read the stdout as it's coming in? Another solution may be to dump the output to a file and wait for the process to finish using <strong>p.wait()</strong>.</p> <pre><code>f = open('myprogram_output.txt','w') p = subprocess.Popen('myprogram.exe', stdout=f) p.wait() f.close() str = open('myprogram_output.txt','r').read() </code></pre>
8
2008-12-17T18:16:48Z
[ "python", "io", "subprocess", "nonblocking" ]
Non-blocking read on a subprocess.PIPE in python
375,427
<p>I'm using the <a href="http://docs.python.org/library/subprocess.html">subprocess module</a> to start a subprocess and connect to it's output stream (stdout). I want to be able to execute non-blocking reads on its stdout. Is there a way to make .readline non-blocking or to check if there is data on the stream before I invoke <code>.readline</code>? I'd like this to be portable or at least work under Windows and Linux.</p> <p>here is how I do it for now (It's blocking on the <code>.readline</code> if no data is avaible):</p> <pre><code>p = subprocess.Popen('myprogram.exe', stdout = subprocess.PIPE) output_str = p.stdout.readline() </code></pre>
327
2008-12-17T17:56:34Z
375,511
<p>The <a href="http://www.python.org/doc/2.5.2/lib/module-select.html" rel="nofollow">select</a> module helps you determine where the next useful input is.</p> <p>However, you're almost always happier with separate threads. One does a blocking read the stdin, another does wherever it is you don't want blocked.</p>
1
2008-12-17T18:19:25Z
[ "python", "io", "subprocess", "nonblocking" ]
Non-blocking read on a subprocess.PIPE in python
375,427
<p>I'm using the <a href="http://docs.python.org/library/subprocess.html">subprocess module</a> to start a subprocess and connect to it's output stream (stdout). I want to be able to execute non-blocking reads on its stdout. Is there a way to make .readline non-blocking or to check if there is data on the stream before I invoke <code>.readline</code>? I'd like this to be portable or at least work under Windows and Linux.</p> <p>here is how I do it for now (It's blocking on the <code>.readline</code> if no data is avaible):</p> <pre><code>p = subprocess.Popen('myprogram.exe', stdout = subprocess.PIPE) output_str = p.stdout.readline() </code></pre>
327
2008-12-17T17:56:34Z
437,888
<p>Try the <a href="http://www.lysator.liu.se/~bellman/download/asyncproc.py">asyncproc</a> module. For example:</p> <pre><code>import os from asyncproc import Process myProc = Process("myprogram.app") while True: # check to see if process has ended poll = myProc.wait(os.WNOHANG) if poll != None: break # print any new output out = myProc.read() if out != "": print out </code></pre> <p>The module takes care of all the threading as suggested by S.Lott.</p>
19
2009-01-13T03:36:16Z
[ "python", "io", "subprocess", "nonblocking" ]
Non-blocking read on a subprocess.PIPE in python
375,427
<p>I'm using the <a href="http://docs.python.org/library/subprocess.html">subprocess module</a> to start a subprocess and connect to it's output stream (stdout). I want to be able to execute non-blocking reads on its stdout. Is there a way to make .readline non-blocking or to check if there is data on the stream before I invoke <code>.readline</code>? I'd like this to be portable or at least work under Windows and Linux.</p> <p>here is how I do it for now (It's blocking on the <code>.readline</code> if no data is avaible):</p> <pre><code>p = subprocess.Popen('myprogram.exe', stdout = subprocess.PIPE) output_str = p.stdout.readline() </code></pre>
327
2008-12-17T17:56:34Z
1,810,703
<p>I have often had a similar problem; Python programs I write frequently need to have the ability to execute some primary functionality while simultaneously accepting user input from the command line (stdin). Simply putting the user input handling functionality in another thread doesn't solve the problem because <code>readline()</code> blocks and has no timeout. If the primary functionality is complete and there is no longer any need to wait for further user input I typically want my program to exit, but it can't because <code>readline()</code> is still blocking in the other thread waiting for a line. A solution I have found to this problem is to make stdin a non-blocking file using the fcntl module:</p> <pre><code>import fcntl import os import sys # make stdin a non-blocking file fd = sys.stdin.fileno() fl = fcntl.fcntl(fd, fcntl.F_GETFL) fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK) # user input handling thread while mainThreadIsRunning: try: input = sys.stdin.readline() except: continue handleInput(input) </code></pre> <p>In my opinion this is a bit cleaner than using the select or signal modules to solve this problem but then again it only works on UNIX...</p>
56
2009-11-27T21:33:52Z
[ "python", "io", "subprocess", "nonblocking" ]
Non-blocking read on a subprocess.PIPE in python
375,427
<p>I'm using the <a href="http://docs.python.org/library/subprocess.html">subprocess module</a> to start a subprocess and connect to it's output stream (stdout). I want to be able to execute non-blocking reads on its stdout. Is there a way to make .readline non-blocking or to check if there is data on the stream before I invoke <code>.readline</code>? I'd like this to be portable or at least work under Windows and Linux.</p> <p>here is how I do it for now (It's blocking on the <code>.readline</code> if no data is avaible):</p> <pre><code>p = subprocess.Popen('myprogram.exe', stdout = subprocess.PIPE) output_str = p.stdout.readline() </code></pre>
327
2008-12-17T17:56:34Z
4,800,541
<p>Use select &amp; read(1). </p> <pre><code>import subprocess #no new requirements def readAllSoFar(proc, retVal=''): while (select.select([proc.stdout],[],[],0)[0]!=[]): retVal+=proc.stdout.read(1) return retVal p = subprocess.Popen(['/bin/ls'], stdout=subprocess.PIPE) while not p.poll(): print (readAllSoFar(p)) </code></pre> <p>For readline()-like:</p> <pre><code>lines = [''] while not p.poll(): lines = readAllSoFar(p, lines[-1]).split('\n') for a in range(len(lines)-1): print a lines = readAllSoFar(p, lines[-1]).split('\n') for a in range(len(lines)-1): print a </code></pre>
12
2011-01-26T01:02:08Z
[ "python", "io", "subprocess", "nonblocking" ]
Non-blocking read on a subprocess.PIPE in python
375,427
<p>I'm using the <a href="http://docs.python.org/library/subprocess.html">subprocess module</a> to start a subprocess and connect to it's output stream (stdout). I want to be able to execute non-blocking reads on its stdout. Is there a way to make .readline non-blocking or to check if there is data on the stream before I invoke <code>.readline</code>? I'd like this to be portable or at least work under Windows and Linux.</p> <p>here is how I do it for now (It's blocking on the <code>.readline</code> if no data is avaible):</p> <pre><code>p = subprocess.Popen('myprogram.exe', stdout = subprocess.PIPE) output_str = p.stdout.readline() </code></pre>
327
2008-12-17T17:56:34Z
4,896,288
<p><a href="http://stackoverflow.com/questions/375427/non-blocking-read-on-a-stream-in-python/4025909#4025909"><code>fcntl</code></a>, <a href="http://stackoverflow.com/questions/375427/non-blocking-read-on-a-stream-in-python/375511#375511"><code>select</code></a>, <a href="http://stackoverflow.com/questions/375427/non-blocking-read-on-a-stream-in-python/437888#437888"><code>asyncproc</code></a> won't help in this case.</p> <p>A reliable way to read a stream without blocking regardless of operating system is to use <a href="http://docs.python.org/library/queue.html#Queue.Queue.get"><code>Queue.get_nowait()</code></a>:</p> <pre><code>import sys from subprocess import PIPE, Popen from threading import Thread try: from Queue import Queue, Empty except ImportError: from queue import Queue, Empty # python 3.x ON_POSIX = 'posix' in sys.builtin_module_names def enqueue_output(out, queue): for line in iter(out.readline, b''): queue.put(line) out.close() p = Popen(['myprogram.exe'], stdout=PIPE, bufsize=1, close_fds=ON_POSIX) q = Queue() t = Thread(target=enqueue_output, args=(p.stdout, q)) t.daemon = True # thread dies with the program t.start() # ... do other things here # read line without blocking try: line = q.get_nowait() # or q.get(timeout=.1) except Empty: print('no output yet') else: # got line # ... do something with line </code></pre>
263
2011-02-04T09:14:38Z
[ "python", "io", "subprocess", "nonblocking" ]
Non-blocking read on a subprocess.PIPE in python
375,427
<p>I'm using the <a href="http://docs.python.org/library/subprocess.html">subprocess module</a> to start a subprocess and connect to it's output stream (stdout). I want to be able to execute non-blocking reads on its stdout. Is there a way to make .readline non-blocking or to check if there is data on the stream before I invoke <code>.readline</code>? I'd like this to be portable or at least work under Windows and Linux.</p> <p>here is how I do it for now (It's blocking on the <code>.readline</code> if no data is avaible):</p> <pre><code>p = subprocess.Popen('myprogram.exe', stdout = subprocess.PIPE) output_str = p.stdout.readline() </code></pre>
327
2008-12-17T17:56:34Z
5,749,687
<p>I add this problem to read some subprocess.Popen stdout. Here is my non blocking read solution:</p> <pre><code>import fcntl def non_block_read(output): fd = output.fileno() fl = fcntl.fcntl(fd, fcntl.F_GETFL) fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK) try: return output.read() except: return "" # Use example from subprocess import * sb = Popen("echo test &amp;&amp; sleep 1000", shell=True, stdout=PIPE) sb.kill() # sb.stdout.read() # &lt;-- This will block non_block_read(sb.stdout) 'test\n' </code></pre>
3
2011-04-21T20:51:57Z
[ "python", "io", "subprocess", "nonblocking" ]
Non-blocking read on a subprocess.PIPE in python
375,427
<p>I'm using the <a href="http://docs.python.org/library/subprocess.html">subprocess module</a> to start a subprocess and connect to it's output stream (stdout). I want to be able to execute non-blocking reads on its stdout. Is there a way to make .readline non-blocking or to check if there is data on the stream before I invoke <code>.readline</code>? I'd like this to be portable or at least work under Windows and Linux.</p> <p>here is how I do it for now (It's blocking on the <code>.readline</code> if no data is avaible):</p> <pre><code>p = subprocess.Popen('myprogram.exe', stdout = subprocess.PIPE) output_str = p.stdout.readline() </code></pre>
327
2008-12-17T17:56:34Z
5,750,194
<p>You can do this really easily in <a href="http://twistedmatrix.com/trac/">Twisted</a>. Depending upon your existing code base, this might not be that easy to use, but if you are building a twisted application, then things like this become almost trivial. You create a <code>ProcessProtocol</code> class, and override the <code>outReceived()</code> method. Twisted (depending upon the reactor used) is usually just a big <code>select()</code> loop with callbacks installed to handle data from different file descriptors (often network sockets). So the <code>outReceived()</code> method is simply installing a callback for handling data coming from <code>STDOUT</code>. A simple example demonstrating this behavior is as follows:</p> <pre><code>from twisted.internet import protocol, reactor class MyProcessProtocol(protocol.ProcessProtocol): def outReceived(self, data): print data proc = MyProcessProtocol() reactor.spawnProcess(proc, './myprogram', ['./myprogram', 'arg1', 'arg2', 'arg3']) reactor.run() </code></pre> <p>The <a href="http://twistedmatrix.com/documents/current/core/howto/process.html">Twisted documentation</a> has some good information on this.</p> <p>If you build your entire application around Twisted, it makes asynchronous communication with other processes, local or remote, really elegant like this. On the other hand, if your program isn't built on top of Twisted, this isn't really going to be that helpful. Hopefully this can be helpful to other readers, even if it isn't applicable for your particular application.</p>
15
2011-04-21T21:54:55Z
[ "python", "io", "subprocess", "nonblocking" ]
Non-blocking read on a subprocess.PIPE in python
375,427
<p>I'm using the <a href="http://docs.python.org/library/subprocess.html">subprocess module</a> to start a subprocess and connect to it's output stream (stdout). I want to be able to execute non-blocking reads on its stdout. Is there a way to make .readline non-blocking or to check if there is data on the stream before I invoke <code>.readline</code>? I'd like this to be portable or at least work under Windows and Linux.</p> <p>here is how I do it for now (It's blocking on the <code>.readline</code> if no data is avaible):</p> <pre><code>p = subprocess.Popen('myprogram.exe', stdout = subprocess.PIPE) output_str = p.stdout.readline() </code></pre>
327
2008-12-17T17:56:34Z
11,362,426
<p>Disclaimer: this works only for tornado</p> <p>You can do this by setting the fd to be nonblocking and then use ioloop to register callbacks. I have packaged this in an egg called <a href="http://pypi.python.org/pypi/tornado_subprocess/0.1.3">tornado_subprocess</a> and you can install it via PyPI:</p> <pre><code>easy_install tornado_subprocess </code></pre> <p>now you can do something like this:</p> <pre><code>import tornado_subprocess import tornado.ioloop def print_res( status, stdout, stderr ) : print status, stdout, stderr if status == 0: print "OK:" print stdout else: print "ERROR:" print stderr t = tornado_subprocess.Subprocess( print_res, timeout=30, args=[ "cat", "/etc/passwd" ] ) t.start() tornado.ioloop.IOLoop.instance().start() </code></pre> <p>you can also use it with a RequestHandler</p> <pre><code>class MyHandler(tornado.web.RequestHandler): def on_done(self, status, stdout, stderr): self.write( stdout ) self.finish() @tornado.web.asynchronous def get(self): t = tornado_subprocess.Subprocess( self.on_done, timeout=30, args=[ "cat", "/etc/passwd" ] ) t.start() </code></pre>
7
2012-07-06T12:42:26Z
[ "python", "io", "subprocess", "nonblocking" ]
Non-blocking read on a subprocess.PIPE in python
375,427
<p>I'm using the <a href="http://docs.python.org/library/subprocess.html">subprocess module</a> to start a subprocess and connect to it's output stream (stdout). I want to be able to execute non-blocking reads on its stdout. Is there a way to make .readline non-blocking or to check if there is data on the stream before I invoke <code>.readline</code>? I'd like this to be portable or at least work under Windows and Linux.</p> <p>here is how I do it for now (It's blocking on the <code>.readline</code> if no data is avaible):</p> <pre><code>p = subprocess.Popen('myprogram.exe', stdout = subprocess.PIPE) output_str = p.stdout.readline() </code></pre>
327
2008-12-17T17:56:34Z
15,424,877
<p>Existing solutions did not work for me (details below). What finally worked was to implement readline using read(1) (based on <a href="http://stackoverflow.com/a/883166/2039589">this answer</a>). The latter does not block:</p> <pre><code>from subprocess import Popen, PIPE from threading import Thread def process_output(myprocess): #output-consuming thread nextline = None buf = '' while True: #--- extract line using read(1) out = myprocess.stdout.read(1) if out == '' and myprocess.poll() != None: break if out != '': buf += out if out == '\n': nextline = buf buf = '' if not nextline: continue line = nextline nextline = None #--- do whatever you want with line here print 'Line is:', line myprocess.stdout.close() myprocess = Popen('myprogram.exe', stdout=PIPE) #output-producing process p1 = Thread(target=process_output, args=(dcmpid,)) #output-consuming thread p1.daemon = True p1.start() #--- do whatever here and then kill process and thread if needed if myprocess.poll() == None: #kill process; will automatically stop thread myprocess.kill() myprocess.wait() if p1 and p1.is_alive(): #wait for thread to finish p1.join() </code></pre> <p>Why existing solutions did not work:</p> <ol> <li>Solutions that require readline (including the Queue based ones) always block. It is difficult (impossible?) to kill the thread that executes readline. It only gets killed when the process that created it finishes, but not when the output-producing process is killed.</li> <li>Mixing low-level fcntl with high-level readline calls may not work properly as anonnn has pointed out.</li> <li>Using select.poll() is neat, but doesn't work on Windows according to python docs.</li> <li>Using third-party libraries seems overkill for this task and adds additional dependencies.</li> </ol>
5
2013-03-15T04:40:40Z
[ "python", "io", "subprocess", "nonblocking" ]
Non-blocking read on a subprocess.PIPE in python
375,427
<p>I'm using the <a href="http://docs.python.org/library/subprocess.html">subprocess module</a> to start a subprocess and connect to it's output stream (stdout). I want to be able to execute non-blocking reads on its stdout. Is there a way to make .readline non-blocking or to check if there is data on the stream before I invoke <code>.readline</code>? I'd like this to be portable or at least work under Windows and Linux.</p> <p>here is how I do it for now (It's blocking on the <code>.readline</code> if no data is avaible):</p> <pre><code>p = subprocess.Popen('myprogram.exe', stdout = subprocess.PIPE) output_str = p.stdout.readline() </code></pre>
327
2008-12-17T17:56:34Z
16,256,473
<p>I have created a library based on <a href="http://stackoverflow.com/a/4896288/242451">J. F. Sebastian's solution</a>. You can use it.</p> <p><a href="https://github.com/cenkalti/what" rel="nofollow">https://github.com/cenkalti/what</a></p>
0
2013-04-27T20:14:51Z
[ "python", "io", "subprocess", "nonblocking" ]
Non-blocking read on a subprocess.PIPE in python
375,427
<p>I'm using the <a href="http://docs.python.org/library/subprocess.html">subprocess module</a> to start a subprocess and connect to it's output stream (stdout). I want to be able to execute non-blocking reads on its stdout. Is there a way to make .readline non-blocking or to check if there is data on the stream before I invoke <code>.readline</code>? I'd like this to be portable or at least work under Windows and Linux.</p> <p>here is how I do it for now (It's blocking on the <code>.readline</code> if no data is avaible):</p> <pre><code>p = subprocess.Popen('myprogram.exe', stdout = subprocess.PIPE) output_str = p.stdout.readline() </code></pre>
327
2008-12-17T17:56:34Z
16,425,237
<p>EDIT: This implementation still blocks. Use J.F.Sebastian's <a href="http://stackoverflow.com/a/4896288/2359288">answer</a> instead.</p> <p><strike>I tried the <a href="http://stackoverflow.com/a/4896288/2359288">top answer</a>, but the additional risk and maintenance of thread code was worrisome.</p> <p>Looking through the <a href="http://docs.python.org/2.6/library/io.html" rel="nofollow">io module</a> (and being limited to 2.6), I found BufferedReader. This is my threadless, non-blocking solution.</strike> </p> <pre><code>import io from subprocess import PIPE, Popen p = Popen(['myprogram.exe'], stdout=PIPE) SLEEP_DELAY = 0.001 # Create an io.BufferedReader on the file descriptor for stdout with io.open(p.stdout.fileno(), 'rb', closefd=False) as buffer: while p.poll() == None: time.sleep(SLEEP_DELAY) while '\n' in bufferedStdout.peek(bufferedStdout.buffer_size): line = buffer.readline() # do stuff with the line # Handle any remaining output after the process has ended while buffer.peek(): line = buffer.readline() # do stuff with the line </code></pre>
0
2013-05-07T17:38:40Z
[ "python", "io", "subprocess", "nonblocking" ]
Non-blocking read on a subprocess.PIPE in python
375,427
<p>I'm using the <a href="http://docs.python.org/library/subprocess.html">subprocess module</a> to start a subprocess and connect to it's output stream (stdout). I want to be able to execute non-blocking reads on its stdout. Is there a way to make .readline non-blocking or to check if there is data on the stream before I invoke <code>.readline</code>? I'd like this to be portable or at least work under Windows and Linux.</p> <p>here is how I do it for now (It's blocking on the <code>.readline</code> if no data is avaible):</p> <pre><code>p = subprocess.Popen('myprogram.exe', stdout = subprocess.PIPE) output_str = p.stdout.readline() </code></pre>
327
2008-12-17T17:56:34Z
17,051,876
<p>Here is my code, used to catch every output from subprocess ASAP, including partial lines. It pumps at same time and stdout and stderr in almost correct order.</p> <p>Tested and correctly worked on Python 2.7 linux &amp; windows. </p> <pre><code>#!/usr/bin/python # # Runner with stdout/stderr catcher # from sys import argv from subprocess import Popen, PIPE import os, io from threading import Thread import Queue def __main__(): if (len(argv) &gt; 1) and (argv[-1] == "-sub-"): import time, sys print "Application runned!" time.sleep(2) print "Slept 2 second" time.sleep(1) print "Slept 1 additional second", time.sleep(2) sys.stderr.write("Stderr output after 5 seconds") print "Eol on stdin" sys.stderr.write("Eol on stderr\n") time.sleep(1) print "Wow, we have end of work!", else: os.environ["PYTHONUNBUFFERED"]="1" try: p = Popen( argv + ["-sub-"], bufsize=0, # line-buffered stdin=PIPE, stdout=PIPE, stderr=PIPE ) except WindowsError, W: if W.winerror==193: p = Popen( argv + ["-sub-"], shell=True, # Try to run via shell bufsize=0, # line-buffered stdin=PIPE, stdout=PIPE, stderr=PIPE ) else: raise inp = Queue.Queue() sout = io.open(p.stdout.fileno(), 'rb', closefd=False) serr = io.open(p.stderr.fileno(), 'rb', closefd=False) def Pump(stream, category): queue = Queue.Queue() def rdr(): while True: buf = stream.read1(8192) if len(buf)&gt;0: queue.put( buf ) else: queue.put( None ) return def clct(): active = True while active: r = queue.get() try: while True: r1 = queue.get(timeout=0.005) if r1 is None: active = False break else: r += r1 except Queue.Empty: pass inp.put( (category, r) ) for tgt in [rdr, clct]: th = Thread(target=tgt) th.setDaemon(True) th.start() Pump(sout, 'stdout') Pump(serr, 'stderr') while p.poll() is None: # App still working try: chan,line = inp.get(timeout = 1.0) if chan=='stdout': print "STDOUT&gt;&gt;", line, "&lt;?&lt;" elif chan=='stderr': print " ERROR==", line, "=?=" except Queue.Empty: pass print "Finish" if __name__ == '__main__': __main__() </code></pre>
3
2013-06-11T19:09:11Z
[ "python", "io", "subprocess", "nonblocking" ]
Non-blocking read on a subprocess.PIPE in python
375,427
<p>I'm using the <a href="http://docs.python.org/library/subprocess.html">subprocess module</a> to start a subprocess and connect to it's output stream (stdout). I want to be able to execute non-blocking reads on its stdout. Is there a way to make .readline non-blocking or to check if there is data on the stream before I invoke <code>.readline</code>? I'd like this to be portable or at least work under Windows and Linux.</p> <p>here is how I do it for now (It's blocking on the <code>.readline</code> if no data is avaible):</p> <pre><code>p = subprocess.Popen('myprogram.exe', stdout = subprocess.PIPE) output_str = p.stdout.readline() </code></pre>
327
2008-12-17T17:56:34Z
19,703,560
<p>Working from J.F. Sebastian's answer, and several other sources, I've put together a simple subprocess manager. It provides the request non-blocking reading, as well as running several processes in parallel. It doesn't use any OS-specific call (that I'm aware) and thus should work anywhere.</p> <p>It's available from pypi, so just <code>pip install shelljob</code>. Refer to the <a href="https://pypi.python.org/pypi/shelljob" rel="nofollow">project page</a> for examples and full docs.</p>
0
2013-10-31T10:09:25Z
[ "python", "io", "subprocess", "nonblocking" ]
Non-blocking read on a subprocess.PIPE in python
375,427
<p>I'm using the <a href="http://docs.python.org/library/subprocess.html">subprocess module</a> to start a subprocess and connect to it's output stream (stdout). I want to be able to execute non-blocking reads on its stdout. Is there a way to make .readline non-blocking or to check if there is data on the stream before I invoke <code>.readline</code>? I'd like this to be portable or at least work under Windows and Linux.</p> <p>here is how I do it for now (It's blocking on the <code>.readline</code> if no data is avaible):</p> <pre><code>p = subprocess.Popen('myprogram.exe', stdout = subprocess.PIPE) output_str = p.stdout.readline() </code></pre>
327
2008-12-17T17:56:34Z
20,697,159
<p>Python 3.4 introduces new <a href="http://www.python.org/dev/peps/pep-0411/">provisional API</a> for asynchronous IO -- <a href="http://docs.python.org/3/library/asyncio.html"><code>asyncio</code> module</a>. </p> <p>The approach is similar to <a href="http://stackoverflow.com/a/5750194/4279"><code>twisted</code>-based answer by @Bryan Ward</a> -- define a protocol and its methods are called as soon as data is ready:</p> <pre><code>#!/usr/bin/env python3 import asyncio import os class SubprocessProtocol(asyncio.SubprocessProtocol): def pipe_data_received(self, fd, data): if fd == 1: # got stdout data (bytes) print(data) def connection_lost(self, exc): loop.stop() # end loop.run_forever() if os.name == 'nt': loop = asyncio.ProactorEventLoop() # for subprocess' pipes on Windows asyncio.set_event_loop(loop) else: loop = asyncio.get_event_loop() try: loop.run_until_complete(loop.subprocess_exec(SubprocessProtocol, "myprogram.exe", "arg1", "arg2")) loop.run_forever() finally: loop.close() </code></pre> <p>See <a href="https://docs.python.org/3/library/asyncio-subprocess.html">"Subprocess" in the docs</a>.</p> <p>There is a high-level interface <code>asyncio.create_subprocess_exec()</code> that returns <a href="https://docs.python.org/3/library/asyncio-subprocess.html#process"><code>Process</code> objects</a> that allows to read a line asynchroniosly using <a href="https://docs.python.org/3/library/asyncio-stream.html#asyncio.StreamReader"><code>StreamReader.readline()</code> coroutine</a> (with <a href="https://www.python.org/dev/peps/pep-0492/"><code>async</code>/<code>await</code> Python 3.5+ syntax</a>):</p> <pre><code>#!/usr/bin/env python3.5 import asyncio import locale import sys from asyncio.subprocess import PIPE from contextlib import closing async def readline_and_kill(*args): # start child process process = await asyncio.create_subprocess_exec(*args, stdout=PIPE) # read line (sequence of bytes ending with b'\n') asynchronously async for line in process.stdout: print("got line:", line.decode(locale.getpreferredencoding(False))) break process.kill() return await process.wait() # wait for the child process to exit if sys.platform == "win32": loop = asyncio.ProactorEventLoop() asyncio.set_event_loop(loop) else: loop = asyncio.get_event_loop() with closing(loop): sys.exit(loop.run_until_complete(readline_and_kill( "myprogram.exe", "arg1", "arg2"))) </code></pre> <p><code>readline_and_kill()</code> performs the following tasks:</p> <ul> <li>start subprocess, redirect its stdout to a pipe</li> <li>read a line from subprocess' stdout asynchronously</li> <li>kill subprocess</li> <li>wait for it to exit</li> </ul> <p>Each step could be limited by timeout seconds if necessary.</p>
24
2013-12-20T05:50:15Z
[ "python", "io", "subprocess", "nonblocking" ]
Non-blocking read on a subprocess.PIPE in python
375,427
<p>I'm using the <a href="http://docs.python.org/library/subprocess.html">subprocess module</a> to start a subprocess and connect to it's output stream (stdout). I want to be able to execute non-blocking reads on its stdout. Is there a way to make .readline non-blocking or to check if there is data on the stream before I invoke <code>.readline</code>? I'd like this to be portable or at least work under Windows and Linux.</p> <p>here is how I do it for now (It's blocking on the <code>.readline</code> if no data is avaible):</p> <pre><code>p = subprocess.Popen('myprogram.exe', stdout = subprocess.PIPE) output_str = p.stdout.readline() </code></pre>
327
2008-12-17T17:56:34Z
27,887,083
<p>I recently stumbled upon on the same problem I need to read one line at time from stream ( tail run in subprocess ) in non-blocking mode I wanted to avoid next problems: not to burn cpu, don't read stream by one byte (like readline did ), etc</p> <p>Here is my implementation <a href="https://gist.github.com/grubberr/5501e1a9760c3eab5e0a" rel="nofollow">https://gist.github.com/grubberr/5501e1a9760c3eab5e0a</a> it don't support windows (poll), don't handle EOF, but it works for me well</p>
0
2015-01-11T12:33:31Z
[ "python", "io", "subprocess", "nonblocking" ]
Non-blocking read on a subprocess.PIPE in python
375,427
<p>I'm using the <a href="http://docs.python.org/library/subprocess.html">subprocess module</a> to start a subprocess and connect to it's output stream (stdout). I want to be able to execute non-blocking reads on its stdout. Is there a way to make .readline non-blocking or to check if there is data on the stream before I invoke <code>.readline</code>? I'd like this to be portable or at least work under Windows and Linux.</p> <p>here is how I do it for now (It's blocking on the <code>.readline</code> if no data is avaible):</p> <pre><code>p = subprocess.Popen('myprogram.exe', stdout = subprocess.PIPE) output_str = p.stdout.readline() </code></pre>
327
2008-12-17T17:56:34Z
28,019,908
<p>why bothering thread&amp;queue? unlike readline(), BufferedReader.read1() wont block waiting for \r\n, it returns ASAP if there is any output coming in.</p> <pre><code>#!/usr/bin/python from subprocess import Popen, PIPE, STDOUT import io def __main__(): try: p = Popen( ["ping", "-n", "3", "127.0.0.1"], stdin=PIPE, stdout=PIPE, stderr=STDOUT ) except: print("Popen failed"); quit() sout = io.open(p.stdout.fileno(), 'rb', closefd=False) while True: buf = sout.read1(1024) if len(buf) == 0: break print buf, if __name__ == '__main__': __main__() </code></pre>
-1
2015-01-19T07:39:26Z
[ "python", "io", "subprocess", "nonblocking" ]
Non-blocking read on a subprocess.PIPE in python
375,427
<p>I'm using the <a href="http://docs.python.org/library/subprocess.html">subprocess module</a> to start a subprocess and connect to it's output stream (stdout). I want to be able to execute non-blocking reads on its stdout. Is there a way to make .readline non-blocking or to check if there is data on the stream before I invoke <code>.readline</code>? I'd like this to be portable or at least work under Windows and Linux.</p> <p>here is how I do it for now (It's blocking on the <code>.readline</code> if no data is avaible):</p> <pre><code>p = subprocess.Popen('myprogram.exe', stdout = subprocess.PIPE) output_str = p.stdout.readline() </code></pre>
327
2008-12-17T17:56:34Z
28,264,979
<p>In my case I needed a logging module that catches the output from the background applications and augments it(adding time-stamps, colors, etc.).</p> <p>I ended up with a background thread that does the actual I/O. Following code is only for POSIX platforms. I stripped non-essential parts. </p> <p>If someone is going to use this beast for long runs consider managing open descriptors. In my case it was not a big problem.</p> <pre><code># -*- python -*- import fcntl import threading import sys, os, errno import subprocess class Logger(threading.Thread): def __init__(self, *modules): threading.Thread.__init__(self) try: from select import epoll, EPOLLIN self.__poll = epoll() self.__evt = EPOLLIN self.__to = -1 except: from select import poll, POLLIN print 'epoll is not available' self.__poll = poll() self.__evt = POLLIN self.__to = 100 self.__fds = {} self.daemon = True self.start() def run(self): while True: events = self.__poll.poll(self.__to) for fd, ev in events: if (ev&amp;self.__evt) != self.__evt: continue try: self.__fds[fd].run() except Exception, e: print e def add(self, fd, log): assert not self.__fds.has_key(fd) self.__fds[fd] = log self.__poll.register(fd, self.__evt) class log: logger = Logger() def __init__(self, name): self.__name = name self.__piped = False def fileno(self): if self.__piped: return self.write self.read, self.write = os.pipe() fl = fcntl.fcntl(self.read, fcntl.F_GETFL) fcntl.fcntl(self.read, fcntl.F_SETFL, fl | os.O_NONBLOCK) self.fdRead = os.fdopen(self.read) self.logger.add(self.read, self) self.__piped = True return self.write def __run(self, line): self.chat(line, nl=False) def run(self): while True: try: line = self.fdRead.readline() except IOError, exc: if exc.errno == errno.EAGAIN: return raise self.__run(line) def chat(self, line, nl=True): if nl: nl = '\n' else: nl = '' sys.stdout.write('[%s] %s%s' % (self.__name, line, nl)) def system(command, param=[], cwd=None, env=None, input=None, output=None): args = [command] + param p = subprocess.Popen(args, cwd=cwd, stdout=output, stderr=output, stdin=input, env=env, bufsize=0) p.wait() ls = log('ls') ls.chat('go') system("ls", ['-l', '/'], output=ls) date = log('date') date.chat('go') system("date", output=date) </code></pre>
0
2015-02-01T16:32:43Z
[ "python", "io", "subprocess", "nonblocking" ]
Non-blocking read on a subprocess.PIPE in python
375,427
<p>I'm using the <a href="http://docs.python.org/library/subprocess.html">subprocess module</a> to start a subprocess and connect to it's output stream (stdout). I want to be able to execute non-blocking reads on its stdout. Is there a way to make .readline non-blocking or to check if there is data on the stream before I invoke <code>.readline</code>? I'd like this to be portable or at least work under Windows and Linux.</p> <p>here is how I do it for now (It's blocking on the <code>.readline</code> if no data is avaible):</p> <pre><code>p = subprocess.Popen('myprogram.exe', stdout = subprocess.PIPE) output_str = p.stdout.readline() </code></pre>
327
2008-12-17T17:56:34Z
34,832,502
<p>Here is a module that supports non-blocking reads and background writes in python:</p> <p><a href="https://pypi.python.org/pypi/python-nonblock" rel="nofollow">https://pypi.python.org/pypi/python-nonblock</a></p> <p>Provides a function,</p> <p>nonblock_read which will read data from the stream, if available, otherwise return an empty string (or None if the stream is closed on the other side and all possible data has been read)</p> <p>You may also consider the python-subprocess2 module,</p> <p><a href="https://pypi.python.org/pypi/python-subprocess2" rel="nofollow">https://pypi.python.org/pypi/python-subprocess2</a></p> <p>which adds to the subprocess module. So on the object returned from "subprocess.Popen" is added an additional method, runInBackground. This starts a thread and returns an object which will automatically be populated as stuff is written to stdout/stderr, without blocking your main thread.</p> <p>Enjoy!</p>
-2
2016-01-16T21:47:15Z
[ "python", "io", "subprocess", "nonblocking" ]
Non-blocking read on a subprocess.PIPE in python
375,427
<p>I'm using the <a href="http://docs.python.org/library/subprocess.html">subprocess module</a> to start a subprocess and connect to it's output stream (stdout). I want to be able to execute non-blocking reads on its stdout. Is there a way to make .readline non-blocking or to check if there is data on the stream before I invoke <code>.readline</code>? I'd like this to be portable or at least work under Windows and Linux.</p> <p>here is how I do it for now (It's blocking on the <code>.readline</code> if no data is avaible):</p> <pre><code>p = subprocess.Popen('myprogram.exe', stdout = subprocess.PIPE) output_str = p.stdout.readline() </code></pre>
327
2008-12-17T17:56:34Z
35,052,424
<p>Adding this answer here since it provides ability to set non-blocking pipes on Windows and Unix.</p> <p>All the <code>ctypes</code> details are thanks to <a href="http://stackoverflow.com/questions/34504970">@techtonik's answer</a>.</p> <p>There is a slightly modified version to be used both on Unix and Windows systems.</p> <ul> <li>Python3 compatible <em>(only minor change needed)</em>.</li> <li>Includes posix version, and defines exception to use for either.</li> </ul> <p>This way you can use the same function and exception for Unix and Windows code.</p> <pre class="lang-py prettyprint-override"><code># pipe_non_blocking.py (module) """ Example use: p = subprocess.Popen( command, stdout=subprocess.PIPE, ) pipe_non_blocking_set(p.stdout.fileno()) try: data = os.read(p.stdout.fileno(), 1) except PortableBlockingIOError as ex: if not pipe_non_blocking_is_error_blocking(ex): raise ex """ __all__ = ( "pipe_non_blocking_set", "pipe_non_blocking_is_error_blocking", "PortableBlockingIOError", ) import os if os.name == "nt": def pipe_non_blocking_set(fd): # Constant could define globally but avoid polluting the name-space # thanks to: http://stackoverflow.com/questions/34504970 import msvcrt from ctypes import windll, byref, wintypes, WinError, POINTER from ctypes.wintypes import HANDLE, DWORD, BOOL LPDWORD = POINTER(DWORD) PIPE_NOWAIT = wintypes.DWORD(0x00000001) def pipe_no_wait(pipefd): SetNamedPipeHandleState = windll.kernel32.SetNamedPipeHandleState SetNamedPipeHandleState.argtypes = [HANDLE, LPDWORD, LPDWORD, LPDWORD] SetNamedPipeHandleState.restype = BOOL h = msvcrt.get_osfhandle(pipefd) res = windll.kernel32.SetNamedPipeHandleState(h, byref(PIPE_NOWAIT), None, None) if res == 0: print(WinError()) return False return True return pipe_no_wait(fd) def pipe_non_blocking_is_error_blocking(ex): if not isinstance(ex, PortableBlockingIOError): return False from ctypes import GetLastError ERROR_NO_DATA = 232 return (GetLastError() == ERROR_NO_DATA) PortableBlockingIOError = OSError else: def pipe_non_blocking_set(fd): import fcntl fl = fcntl.fcntl(fd, fcntl.F_GETFL) fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK) return True def pipe_non_blocking_is_error_blocking(ex): if not isinstance(ex, PortableBlockingIOError): return False return True PortableBlockingIOError = BlockingIOError </code></pre> <p>To avoid reading incomplete data, I ended up writing my own readline generator (which returns the byte string for each line).</p> <p>Its a generator so you can for example...</p> <pre><code>def non_blocking_readlines(f, chunk=1024): """ Iterate over lines, yielding b'' when nothings left or when new data is not yet available. stdout_iter = iter(non_blocking_readlines(process.stdout)) line = next(stdout_iter) # will be a line or b''. """ import os from .pipe_non_blocking import ( pipe_non_blocking_set, pipe_non_blocking_is_error_blocking, PortableBlockingIOError, ) fd = f.fileno() pipe_non_blocking_set(fd) blocks = [] while True: try: data = os.read(fd, chunk) if not data: # case were reading finishes with no trailing newline yield b''.join(blocks) blocks.clear() except PortableBlockingIOError as ex: if not pipe_non_blocking_is_error_blocking(ex): raise ex yield b'' continue while True: n = data.find(b'\n') if n == -1: break yield b''.join(blocks) + data[:n + 1] data = data[n + 1:] blocks.clear() blocks.append(data) </code></pre>
1
2016-01-28T03:37:45Z
[ "python", "io", "subprocess", "nonblocking" ]
Non-blocking read on a subprocess.PIPE in python
375,427
<p>I'm using the <a href="http://docs.python.org/library/subprocess.html">subprocess module</a> to start a subprocess and connect to it's output stream (stdout). I want to be able to execute non-blocking reads on its stdout. Is there a way to make .readline non-blocking or to check if there is data on the stream before I invoke <code>.readline</code>? I'd like this to be portable or at least work under Windows and Linux.</p> <p>here is how I do it for now (It's blocking on the <code>.readline</code> if no data is avaible):</p> <pre><code>p = subprocess.Popen('myprogram.exe', stdout = subprocess.PIPE) output_str = p.stdout.readline() </code></pre>
327
2008-12-17T17:56:34Z
37,418,460
<p>This version of non-blocking read <strong>doesn't</strong> require special modules and will work out-of-the-box on majority of Linux distros.</p> <pre><code>import os import sys import time import fcntl import subprocess def async_read(fd): # set non-blocking flag while preserving old flags fl = fcntl.fcntl(fd, fcntl.F_GETFL) fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK) # read char until EOF hit while True: try: ch = os.read(fd.fileno(), 1) # EOF if not ch: break sys.stdout.write(ch) except OSError: # waiting for data be available on fd pass def shell(args, async=True): # merge stderr and stdout proc = subprocess.Popen(args, shell=False, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) if async: async_read(proc.stdout) sout, serr = proc.communicate() return (sout, serr) if __name__ == '__main__': cmd = 'ping 8.8.8.8' sout, serr = shell(cmd.split()) </code></pre>
0
2016-05-24T15:55:16Z
[ "python", "io", "subprocess", "nonblocking" ]
Prevent ftplib from Downloading a File in Progress?
375,620
<p>We have a ftp system setup to monitor/download from remote ftp servers that are not under our control. The script connects to the remote ftp, and grabs the file names of files on the server, we then check to see if its something that has already been downloaded. If it hasn't been downloaded then we download the file and add it to the list.</p> <p>We recently ran into an issue, where someone on the remote ftp side, will copy in a massive single file(>1GB) then the script will wake up see a new file and begin downloading the file that is being copied in.</p> <p>What is the best way to check this? I was thinking of grabbing the file size waiting a few seconds checking the file size again and see if it has increased, if it hasn't then we download it. But since time is of the concern, we can't wait a few seconds for every single file set and see if it's file size has increased. </p> <p>What would be the best way to go about this, currently everything is done via pythons ftplib, how can we do this aside from using the aforementioned method.</p> <p>Yet again let me reiterate this, we have 0 control over the remote ftp sites.</p> <p>Thanks.</p> <p>UPDATE1:</p> <p>I was thinking what if i tried to rename it... since we have full permissions on the ftp, if the file upload is in progress would the rename command fail?</p> <p>We don't have any real options here... do we?</p> <p>UPDATE2: Well here's something interesting some of the ftps we tested on appear to automatically allocate the space once the transfer starts.</p> <p>E.g. If i transfer a 200mb file to the ftp server. While the transfer is active if i connect to the ftp server and do a size while the upload is happening. It shows 200mb for the size. Even though the file is only like 10% complete.</p> <p>Permissions also seem to be randomly set the FTP Server that comes with IIS sets the permissions AFTER the file is finished copying. While some of the other older ftp servers set it as soon as you send the file.</p> <p>:'(</p>
4
2008-12-17T18:54:03Z
375,650
<p>You can't know when the OS copy is done. It could slow down or wait.</p> <p>For absolute certainty, you really need two files.</p> <ul> <li>The massive file.</li> <li>And a tiny trigger file.</li> </ul> <p>They can mess with the massive file all they want. But when they touch the trigger file, you're downloading both.</p> <p><hr /></p> <p>If you can't get a trigger, you have to balance the time required to poll vs. the time required to download.</p> <p>Do this.</p> <ol> <li><p>Get a listing. Check timestamps.</p></li> <li><p>Check sizes vs. previous size of file. If size isn't even close, it's being copied right now. Wait; loop on this step until size is close to previous size.</p></li> <li><p>While you're not done:</p> <p>a. Get the file.</p> <p>b. Get a listing AGAIN. Check the size of the new listing, previous listing and your file. If they agree: you're done. If they don't agree: file changed while you were downloading; you're not done.</p></li> </ol>
0
2008-12-17T19:03:45Z
[ "python", "ftp", "ftplib" ]
Prevent ftplib from Downloading a File in Progress?
375,620
<p>We have a ftp system setup to monitor/download from remote ftp servers that are not under our control. The script connects to the remote ftp, and grabs the file names of files on the server, we then check to see if its something that has already been downloaded. If it hasn't been downloaded then we download the file and add it to the list.</p> <p>We recently ran into an issue, where someone on the remote ftp side, will copy in a massive single file(>1GB) then the script will wake up see a new file and begin downloading the file that is being copied in.</p> <p>What is the best way to check this? I was thinking of grabbing the file size waiting a few seconds checking the file size again and see if it has increased, if it hasn't then we download it. But since time is of the concern, we can't wait a few seconds for every single file set and see if it's file size has increased. </p> <p>What would be the best way to go about this, currently everything is done via pythons ftplib, how can we do this aside from using the aforementioned method.</p> <p>Yet again let me reiterate this, we have 0 control over the remote ftp sites.</p> <p>Thanks.</p> <p>UPDATE1:</p> <p>I was thinking what if i tried to rename it... since we have full permissions on the ftp, if the file upload is in progress would the rename command fail?</p> <p>We don't have any real options here... do we?</p> <p>UPDATE2: Well here's something interesting some of the ftps we tested on appear to automatically allocate the space once the transfer starts.</p> <p>E.g. If i transfer a 200mb file to the ftp server. While the transfer is active if i connect to the ftp server and do a size while the upload is happening. It shows 200mb for the size. Even though the file is only like 10% complete.</p> <p>Permissions also seem to be randomly set the FTP Server that comes with IIS sets the permissions AFTER the file is finished copying. While some of the other older ftp servers set it as soon as you send the file.</p> <p>:'(</p>
4
2008-12-17T18:54:03Z
375,705
<p>As you say you have 0 control over the servers and can't make your clients post trigger files as suggested by S. Lott, you must deal with the imperfect solution and risk incomplete file transmission, perhaps by waiting for a while and compare file sizes before and after.</p> <p>You can try to rename as you suggested, but as you have 0 control you can't be sure that the ftp-server-administrator (or their successor) doesn't change platforms or ftp servers or restricts your permissions.</p> <p>Sorry.</p>
0
2008-12-17T19:19:30Z
[ "python", "ftp", "ftplib" ]
Prevent ftplib from Downloading a File in Progress?
375,620
<p>We have a ftp system setup to monitor/download from remote ftp servers that are not under our control. The script connects to the remote ftp, and grabs the file names of files on the server, we then check to see if its something that has already been downloaded. If it hasn't been downloaded then we download the file and add it to the list.</p> <p>We recently ran into an issue, where someone on the remote ftp side, will copy in a massive single file(>1GB) then the script will wake up see a new file and begin downloading the file that is being copied in.</p> <p>What is the best way to check this? I was thinking of grabbing the file size waiting a few seconds checking the file size again and see if it has increased, if it hasn't then we download it. But since time is of the concern, we can't wait a few seconds for every single file set and see if it's file size has increased. </p> <p>What would be the best way to go about this, currently everything is done via pythons ftplib, how can we do this aside from using the aforementioned method.</p> <p>Yet again let me reiterate this, we have 0 control over the remote ftp sites.</p> <p>Thanks.</p> <p>UPDATE1:</p> <p>I was thinking what if i tried to rename it... since we have full permissions on the ftp, if the file upload is in progress would the rename command fail?</p> <p>We don't have any real options here... do we?</p> <p>UPDATE2: Well here's something interesting some of the ftps we tested on appear to automatically allocate the space once the transfer starts.</p> <p>E.g. If i transfer a 200mb file to the ftp server. While the transfer is active if i connect to the ftp server and do a size while the upload is happening. It shows 200mb for the size. Even though the file is only like 10% complete.</p> <p>Permissions also seem to be randomly set the FTP Server that comes with IIS sets the permissions AFTER the file is finished copying. While some of the other older ftp servers set it as soon as you send the file.</p> <p>:'(</p>
4
2008-12-17T18:54:03Z
375,716
<p>If you are dealing with multiple files, you could get the list of all the sizes at once, wait ten seconds, and see which are the same. Whichever are still the same should be safe to download.</p>
0
2008-12-17T19:23:06Z
[ "python", "ftp", "ftplib" ]
Prevent ftplib from Downloading a File in Progress?
375,620
<p>We have a ftp system setup to monitor/download from remote ftp servers that are not under our control. The script connects to the remote ftp, and grabs the file names of files on the server, we then check to see if its something that has already been downloaded. If it hasn't been downloaded then we download the file and add it to the list.</p> <p>We recently ran into an issue, where someone on the remote ftp side, will copy in a massive single file(>1GB) then the script will wake up see a new file and begin downloading the file that is being copied in.</p> <p>What is the best way to check this? I was thinking of grabbing the file size waiting a few seconds checking the file size again and see if it has increased, if it hasn't then we download it. But since time is of the concern, we can't wait a few seconds for every single file set and see if it's file size has increased. </p> <p>What would be the best way to go about this, currently everything is done via pythons ftplib, how can we do this aside from using the aforementioned method.</p> <p>Yet again let me reiterate this, we have 0 control over the remote ftp sites.</p> <p>Thanks.</p> <p>UPDATE1:</p> <p>I was thinking what if i tried to rename it... since we have full permissions on the ftp, if the file upload is in progress would the rename command fail?</p> <p>We don't have any real options here... do we?</p> <p>UPDATE2: Well here's something interesting some of the ftps we tested on appear to automatically allocate the space once the transfer starts.</p> <p>E.g. If i transfer a 200mb file to the ftp server. While the transfer is active if i connect to the ftp server and do a size while the upload is happening. It shows 200mb for the size. Even though the file is only like 10% complete.</p> <p>Permissions also seem to be randomly set the FTP Server that comes with IIS sets the permissions AFTER the file is finished copying. While some of the other older ftp servers set it as soon as you send the file.</p> <p>:'(</p>
4
2008-12-17T18:54:03Z
375,800
<p><strong>“Damn the torpedoes! Full speed ahead!”</strong></p> <p>Just download the file. If it is a large file then after the download completes wait as long as is reasonable for your scenario and continue the download from the point it stopped. Repeat until there is no more stuff to download.</p>
5
2008-12-17T19:49:01Z
[ "python", "ftp", "ftplib" ]
How do I create a wx.Image object from in-memory data?
375,820
<p>I'm writing a GUI application in Python using wxPython and I want to display an image in a static control (<code>wx.StaticBitmap</code>).</p> <p>I can use <a href="http://www.wxpython.org/docs/api/wx-module.html#ImageFromStream" rel="nofollow"><code>wx.ImageFromStream</code></a> to load an image from a file, and this works OK:</p> <pre><code>static_bitmap = wx.StaticBitmap(parent, wx.ID_ANY) f = open("test.jpg", "rb") image = wx.ImageFromStream(f) bitmap = wx.BitmapFromImage(image) static_bitmap.SetBitmap(bitmap) </code></pre> <p>But, what I really want to be able to do is create the image from data in memory. So, if I write</p> <pre><code>f = open("test.jpg", "rb") data = f.read() </code></pre> <p>how can I create a <code>wx.Image</code> object from <code>data</code>?</p> <p>Thanks for your help!</p>
4
2008-12-17T19:54:46Z
375,836
<p>Since in Python you use Duck Typing you can write your own stream class and hand an instance of that class to ImageFromStream. I think you only need to implement the read method and make it return your data.</p>
0
2008-12-17T20:01:11Z
[ "python", "wxpython", "wxwidgets" ]
How do I create a wx.Image object from in-memory data?
375,820
<p>I'm writing a GUI application in Python using wxPython and I want to display an image in a static control (<code>wx.StaticBitmap</code>).</p> <p>I can use <a href="http://www.wxpython.org/docs/api/wx-module.html#ImageFromStream" rel="nofollow"><code>wx.ImageFromStream</code></a> to load an image from a file, and this works OK:</p> <pre><code>static_bitmap = wx.StaticBitmap(parent, wx.ID_ANY) f = open("test.jpg", "rb") image = wx.ImageFromStream(f) bitmap = wx.BitmapFromImage(image) static_bitmap.SetBitmap(bitmap) </code></pre> <p>But, what I really want to be able to do is create the image from data in memory. So, if I write</p> <pre><code>f = open("test.jpg", "rb") data = f.read() </code></pre> <p>how can I create a <code>wx.Image</code> object from <code>data</code>?</p> <p>Thanks for your help!</p>
4
2008-12-17T19:54:46Z
375,852
<p>You should be able to use <code>StringIO</code> to wrap the buffer in a memory file object.</p> <pre><code>... import StringIO buf = open("test.jpg", "rb").read() # buf = get_image_data() sbuf = StringIO.StringIO(buf) image = wx.ImageFromStream(sbuf) ... </code></pre> <p><code>buf</code> can be replaced with any data string.</p>
8
2008-12-17T20:08:11Z
[ "python", "wxpython", "wxwidgets" ]
How do you override vim options via comments in a python source code file?
376,111
<p>I would like to set some vim options in one file in the comments section.</p> <p>For example, I would like to set this option in one file</p> <pre><code>set syntax=python </code></pre> <p>The file does not have a .py extension and I am not interested in making my vim installation recognise all files with this extension as python files.</p> <p>I know this can be done because I have seen it, but my googling for this has not yet been fruitful.</p>
15
2008-12-17T21:37:46Z
376,200
<p>You're wanting a <a href="http://vim.wikia.com/wiki/Modeline_magic">modeline</a> The linked article should explain far better than I can.</p>
23
2008-12-17T22:02:51Z
[ "python", "vim" ]
How do you override vim options via comments in a python source code file?
376,111
<p>I would like to set some vim options in one file in the comments section.</p> <p>For example, I would like to set this option in one file</p> <pre><code>set syntax=python </code></pre> <p>The file does not have a .py extension and I am not interested in making my vim installation recognise all files with this extension as python files.</p> <p>I know this can be done because I have seen it, but my googling for this has not yet been fruitful.</p>
15
2008-12-17T21:37:46Z
376,225
<p>I haven't used vim much, but I think what you want is to add a line like the following to the end of your file:</p> <pre><code># vim: set syntax=python: </code></pre>
9
2008-12-17T22:13:05Z
[ "python", "vim" ]
How do you override vim options via comments in a python source code file?
376,111
<p>I would like to set some vim options in one file in the comments section.</p> <p>For example, I would like to set this option in one file</p> <pre><code>set syntax=python </code></pre> <p>The file does not have a .py extension and I am not interested in making my vim installation recognise all files with this extension as python files.</p> <p>I know this can be done because I have seen it, but my googling for this has not yet been fruitful.</p>
15
2008-12-17T21:37:46Z
34,433,933
<p>You override the Vim options by adding the modeline near the top or the bottom of the file, such as:</p> <pre><code>// vim: set syntax=python: </code></pre> <p>or:</p> <pre><code>/* vim: set syntax=python: */ </code></pre> <p>or like:</p> <pre><code># vim: set syntax=python ts=4 : </code></pre> <p>Other examples (from <a href="http://vim.wikia.com/wiki/Modeline_magic#Examples" rel="nofollow">wikia</a>):</p> <pre><code>// vim: noai:ts=4:sw=4 -or- /* vim: noai:ts=4:sw=4 */ -or- /* vim: set noai ts=4 sw=4: */ -or- /* vim: set fdm=expr fde=getline(v\:lnum)=~'{'?'&gt;1'\:'1': */ </code></pre> <p>Few highlights:</p> <ul> <li>Vim executes a modeline only when <code>modeline</code> is set to <code>modeline</code> or a possitive integer and you're not root (some OS such as Debian, Ubuntu, Gentoo, OSX, etc. disable modelines by default for security reasons), so you need to add <code>set modeline</code> into your <code>~/.vimrc</code> file (<code>:e $MYVIMRC</code>),</li> <li>the line must be in the first or last few lines,</li> <li>space between the opening comment and <code>vim:</code> is required,</li> <li>location where vim checks for the modeline is controlled by the <code>modelines</code> variable (see: <code>:help 'modelines'</code>),</li> <li>with <code>set</code>, the modeline ends at the first colon (<code>:</code>),</li> <li>text other than "vim:" can be recognised as a modeline.</li> </ul> <p>Related:</p> <ul> <li><a href="http://vim.wikia.com/wiki/Modeline_magic" rel="nofollow">Modeline magic</a> at Vim wikia</li> <li><a href="http://security.stackexchange.com/q/36001/11825">Vim modeline vulnerabilities</a> at SS or Google: <em>vim modeline vulnerability</em></li> </ul>
1
2015-12-23T10:48:11Z
[ "python", "vim" ]