How to execute shell command in Python program?

DL Neil PythonList at DancesWithMice.info
Sat Jul 20 17:59:54 EDT 2019


On 21/07/19 5:07 AM, Peter J. Holzer wrote:
> On 2019-07-20 15:39:58 +0100, Chris Narkiewicz via Python-list wrote:
>> Madhavan Bomidi wrote:
>>> import subprocess
>>> subprocess.call(['./opac'],shell=True)
> 
> There may be an os.chdir() missing here.
> 
>> subprocess.call(['./opac', "my-input.inp"], shell=True)
> 
> We don't know whether the OP's program accepts command line arguments.
> But I agree that it probably does and then this is the best way.
...

> In this case you should set shell=False. Either invoke the command
> directly with an argument vector (almost always preferrable), or invoke
> the shell with a shell command. Don't mix them.


+1 for simplicity


subprocess.call() is now described as "older" (since v3.5). The manual 
says: <<<Code needing to capture stdout or stderr should use run() 
instead>>>

Note that if the existing Fortran s/w puts its output to stdout (which I 
think ALL of 'mine' do), then you will need to "capture" that output 
from the subprocess (not necessary if the Fortran writes to a 
report-file on disk).

If you are using v3.7+, use:

	subprocess.run( [ ...etc... ], capture_output=True )

Older versions 3.5+:

	subprocess.run( [ ...etc... ], stdout=subprocess.PIPE )


run() returns a subprocess.CompletedProcess class.

To check that opac executed correctly, inspect the
CompletedProcess.returncode.

To access any "captured" output from opac, use CompletedProcess.stdout 
(similarly stderr, if execution was unsuccessful).

Be aware that the returned data may be string or bytes, and may have 
different line-separators from the one you/your Operating System 
normally uses!

Please study the first sections of subprocess — Subprocess management 
for details, (https://docs.python.org/3/library/subprocess.html), 
experiment, and come back to us with any questions...
-- 
Regards =dn



More information about the Python-list mailing list