I am writting a Python script and I am running out of time. I need to do some things that I know pretty well in bash, so I just wonder how can I embed some bash lines into a Python script.
Thanks
I am writting a Python script and I am running out of time. I need to do some things that I know pretty well in bash, so I just wonder how can I embed some bash lines into a Python script.
Thanks
You can use IPython as a shell. Search the web for: "ipython bash replacement", or look here: stackoverflow.com/questions/209470/can-i-use-python-as-a-bash-replacement. You can call IPython from a script:
If you want to call system commands, use the subprocess module.
Is
going to do it for you?
EDIT: regarding readability
Yes, of course, you can have it more readable
EDIT2: regarding macros, no python does not go so far as far as i know, but between
and previous example, you basically get what you want (but you have to allow for a bit of dialectical limitations)
The ideal way to do it:
You might also add a nice
__str__
method toScriptException
(you are sure to need it to debug your scripts) -- but I leave that to the reader.If you don't use
stdout=subprocess.PIPE
etc then the script will be attached directly to the console. This is really handy if you have, for instance, a password prompt from ssh. So you might want to add flags to control whether you want to capture stdout, stderr, and stdin.As aforementioned, you could use os.system(); it's quick and dirty, bu it's easy to use and works for most cases. It's literally a mapping on to the C system() function.
http://docs.python.org/2/library/os.html#os.system
http://www.cplusplus.com/reference/cstdlib/system/
subprocess and os.system() works fine when bash commands are simple and does not have brackets, commas and quotes. Simple way to embed complex bash argument is to add bash script at the end of python script with a unique string comments and use simple os.system() commands to tail and convert to bash file.