简体   繁体   中英

Execute cmd-like command in Python

I want to make a Python code that will open a program like cmd would, then export a .txt file from the file menu. The code looks like this for cmd:

c:\ESG\Statsvis.exe \\192.168.100.222\c\ESG\S1-424\2012\06\29\S1-42420120629.dsf /output=C:\Users\jessica.macleod\Desktop\outfile.txt /param=RMS Amplitude

In cmd, the above line does exactly what I want. What would be the equivalent for Python?

See subprocess.Popen , like this:

subprocess.Popen(["/bin/ls", "-l"]

Or, depending on what you want to get as result (stdout, return code), use subprocess.call , subprocess.call_check , or other snippets in this module.

Another way would be os.system() .

import os
os.system("c:\\ESG\\Statsvis.exe \\192.16...0629.dsf /output=C:\\...\\outfile.txt ...")

If you want to have exact shell/cmd behavior, then set the shell argument to True in a suprocess.Popen() call. However, from the documentation:

Warning

Invoking the system shell with shell=True can be a security hazard if combined with untrusted input. See the warning under Frequently Used Arguments for details.

If you need the output of the command use subprocess:

import subprocess
out = subprocess.check_output("dir c:\ /AD", shell = True)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM