Note that os.system()
calls are not the preferred way to run any commands and do not ensure capturing the output (see here for more on this).
The preferred and safer mechanism which will capture the output of commands is subprocess.run()
which has a capture_output
parameter and returns a CompletedProcess
object that has members including stdout
and stderr
which, if capture_output=True
contain the output stream contents.
It is worth mentioning that for portability it is usually better to use the methods from the os, shutil, path & glob libraries, etc. This is because calls such as ls
, pwd
, dir
, etc., will work on some platforms but not others.
Example:
import subprocess
result = subprocess.run(['cwd',], capture_output=True)
# Returns the current directory as a string for processing in result.stdout on Mac/Linux but raises an exception on Windows
print(result.stdout)
result = subprocess.run(['ls', '*.docx'], capture_output=True)
# Returns the *.docx files in the current directory as a string for processing in result.stdout on Mac/Linux but raises an exception on Windows
print(result.stdout)
However:
import pathlib
cwd = pathlib.Path.cwd() # Returns the current directory as a Path object on any platform.
print(cwd)
docs = cwd.glob('*.docx') # Returns an generator giving path for to any docx files in cwd on any platform
print(', '.join(p.name for p in docs)) # Print comma seperated list of filenames
Note that for long running or very verbose calls it is often better to use the subprocess.POpen constructor and communicate
or wait
.
If you want to start an external process and not wait for it to finish then use the asynco create_subprocess_exec()
call instead.