New on LowEndTalk? Please Register and read our Community Rules.
All new Registrations are manually reviewed and approved, so a short delay after registration may occur before your account becomes active.
All new Registrations are manually reviewed and approved, so a short delay after registration may occur before your account becomes active.
Run shell commands in Python
Microlinux
Member
I've been working with Python lately, and frequently need to execute shell commands. So, I came up with this module to do this in normalized fashion. Maybe someone else will find it useful.
I stake no claim to being a professional programmer, but it works for me.
Comments
http://amoffat.github.com/sh/
?
I'm confused. There's already a robust library in Python for executing shell commands:
http://docs.python.org/3.3/library/subprocess.html
And a whole bunch of other things for worker pools, concurrency, timeouts, etc.:
http://docs.python.org/3.3/library/concurrency.html
?
This is a wrapper for the subset of that functionality I commonly use. It provides a normalized approach and results.
I realize there may be other ways to do this. And to add, I do realize there are other native timeout methods, but I am lazy and don't want to deal with the ramifications of using them.
http://amoffat.github.com/sh/special_arguments.html?highlight=timeout
I commend your ability and patience to write your own wrapper, but I think it's probably a good idea to use a fully featured interface
80/20. This is 68 lines of code to perform a specific set of repetitive tasks in a consistent and uniform manner. Python is a big set of tinkertoys.
lol tinkertoys...so true
@Microlinux
Nice to see someone sharing his own library here.
FYI, i use https://github.com/kennethreitz/envoy in one of my project.
But not easy.
Use this:
output, error = run( 'ls -l' )
I would if that did what I needed to accomplish.
I'm beginning to wonder if anyone has actually read the code and understands what it does.
Interesting, I'll have to take a closer look.
from sh import mtr
print mtr("-r","-w", "8.8.8.8")
so ez
Yes there are other ways to accomplish similar things.
Challenge: use sh to execute multiple commands in a pool with individual timeouts. Deal with exceptions and unexpected retvals. Return command string, retval and normalized output as an ordered namedtuple generator. Use one line of non-obsfucated code.
Here is how I do this:
results = multi_command([plain text commands], timeout)
I've added a decision tree matrix to the repo that should help clear up any further confusion as to why you might, or might not, want to use this code.
I have switched to using threading.Timer() to timeout processes, external dependency gone.