Reputation: 3895
I want to create a simple "virtual bash" script using Python, that takes commands in and returns the stdio output. Something like this:
>>> output = bash('ls')
>>> print output
file1 file2 file3
>>> print bash('cat file4')
cat: file4: No such file or directory
Does anyone know a module/function that allows this to happen? I could not find one.
Upvotes: 2
Views: 3109
Reputation: 229291
The subprocess
module holds the answers to all your problems. In particular, check_output
seems to do exactly what you want. Examples from the page:
>>> subprocess.check_output(["echo", "Hello World!"])
'Hello World!\n'
>>> subprocess.check_output("exit 1", shell=True)
Traceback (most recent call last):
...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1
If shell is True, the specified command will be executed through the shell. This can be useful if you are using Python primarily for the enhanced control flow it offers over most system shells and still want access to other shell features such as filename wildcards, shell pipes and environment variable expansion.
Upvotes: 6