All these functions support keyword parameters to customize how exactly the subprocess is executed. You can for example use shell=True to execute the program through the shell, if you need things like file name expansions of *, but that comes with limitations.
sth is right. You can also use os.popen(), but where available (Python 2.4+) subprocess is generally preferable.
However, unlike some languages that encourage it, it's generally considered bad form to spawn a subprocess where you can do the same job inside the language. It's slower, less reliable and platform-dependent. Your example would be better off as:
foo= open('/tmp/baz').read()
eta:
baz is a directory and I'm trying to get the contents of all the files in that directory
? cat on a directory gets me an error.
If you want a list of files:
import os
foo= os.listdir('/tmp/baz')
If you want the contents of all files in a directory, something like:
contents= []
for leaf in os.listdir('/tmp/baz'):
path= os.path.join('/tmp/baz', leaf)
if os.path.isfile(path):
contents.append(open(path, 'rb').read())
foo= ''.join(contents)
or, if you can be sure there are no directories in there, you could fit it in a one-liner:
path= '/tmp/baz'
foo= ''.join(open(os.path.join(path, child), 'rb').read() for child in os.listdir(path))
I quit using python a while back because I was annoyed with the difficulty of of doing the equivalent of perl `cmd ...`. I'm glad to find Python has made this reasonable.
This will return a subprocess.CompletedProcess object. The output to stdout will be in cpe.stdout, the output to stderr will be in cpe.stderr, which will both be bytes objects. You can decode the output to get a str object by using cpe.stdout.decode() or get a by passing text=True to subprocess.run:
The backtick (`) operator was removed in Python 3. It is confusingly similar to a single quote, and hard to type on some keyboards. Instead of the backtick, use the equivalent built-in function repr().