It used to be common to use os.system, but it seems to be modern to use subprocess. Reference: http://stackoverflow.com/questions/4813238/difference-between-subprocess-popen-and-os-system
import subprocess
cmd = 'myprogram myargs'
returncode = subprocess.call(cmd)
Call is sufficient for simple calls, but it seems better to use Popen for more general purposes. According to the following references, Popen has the advantage of not blocking command execution (= advancing to the next line without waiting for the command to finish), and call is an implementation of Popen with a command block. It seems. Reference: http://stackoverflow.com/questions/7681715/whats-the-difference-between-subprocess-popen-and-call-how-can-i-use-them
import subprocess
cmd = 'myprogram myargs'
returncode = subprocess.Popen(cmd)
However, this does not allow you to call Windows built-in commands such as dir and echo. When I try to call it, I get the error "The specified file cannot be found". Reference: http://stackoverflow.com/questions/19819417/how-to-use-subprocess-in-windows
The solution is to add shell = True.
import subprocess
cmd = 'dir .'
returncode = subprocess.Popen(cmd, shell=True)
As mentioned in the reference material above, if you add shell = True on Windows, the command prompt cmd.exe is actually called and the command is executed on it. If this option is not added or shell = False is specified, the call will not occur unless the actual file name including the extension is specified.
Most people probably don't need it, but as mentioned above, since it is the command prompt that is called with shell = True, various shell commands that can be executed on Powershell cannot be called from the subprocess.
Recommended Posts