I want to run a command line program from within a python script and get the output.
How do I get the information that is displayed by foo so that I can use it in my script?
For example, I call foo file1
from the command line and it prints out
Size: 3KB
Name: file1.txt
Other stuff: blah
How can I get the file name doing something like filename = os.system('foo file1')
?
This is a portable solution in pure python :
In Python, You can pass a plain OS command with spaces, subquotes and newlines into the
subcommand
module so we can parse the response text like this:Save this into test.py:
Then run it like this:
Which prints:
If this isn't working for you, it could be troubles with the python version or the operating system. I'm using Python 2.7.3 on Ubuntu 12.10 for this example.
The easiest way to get the output of a tool called through your Python script is to use the subprocess module in the standard library. Have a look at subprocess.check_output.
(If your tool gets input from untrusted sources, make sure not to use the
shell=True
argument.)This is typically a subject for a bash script that you can run in python :
Edit : How to use it : open a pseuso-terminal, then copy-paste this :
In python2.4 :
Use the subprocess module:
Then you can do whatever you want with variable
text
: regular expression, splitting, etc.The 2nd and 3rd parameters of
subprocess.Popen
are optional and can be removed.