简体   繁体   中英

Python's os.system(command) and dashes inside a string

I want to run some command with os.system(). I have prepared string "command" (includes some dashes, slashes) and try to do:

print(command)
os.system(command)

My output:

"C:\Program Files (x86)\SimInTech\bin\mmain.exe" "Aux Systems.prt" /saveas "Aux Systems.xprt" /exit
"C:\Program" не является внутренней или внешней
командой, исполняемой программой или пакетным файлом.

("C:\\Program" is not an inner or outter command, executable program or package file.)

If I copy+paste in a command line this (output of print(command)):

"C:\Program Files (x86)\SimInTech\bin\mmain.exe" "Aux Systems.prt" /saveas "Aux Systems.xprt" /exit

It works fine. So, what is the problem and how to avoid it?

Some details of how I prepare my "command" string:

import sys
import os
import codecs
simintech = '"C:\\Program Files (x86)\\SimInTech\\bin\\mmain.exe"'
argfile = sys.argv[1:len(sys.argv)]
file = ' '.join(argfile)
file = file.strip()
filepath, filename = os.path.split(file)
if filepath !='':
    filepath = filepath+"\\"
oldname = filename
newname = filename.replace('.prt','.xprt')
command = simintech + ' "' + filepath +oldname+'" /saveas "'+filepath+newname+'" /exit'

Explanation: I run my script with filename as an argument. Filename could contain spaces, so I collect all args and put it in one string using ' '.join(argfile) After that I separate flepath and filename (if filename was full - with absolute path). And finally I form my command with path to my program, dash, fullname of a file, option \\saveas, again fullname with path but with other file extension, dash and option \\exit.

You should not use os.system, but subprocess.call:

import subprocess
subprocess.call(["C:\Program Files (x86)\SimInTech\bin\mmain.exe", "Aux Systems.prt", "/saveas", "Aux Systems.xprt", "/exit"]

It will make sure that all spaces are escaped properly and will call the according program with the according arguments. (First of list is program, rest is arguments)

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