[英]Can I tell Python to execute command line in cmd?
我正在作为一个非常业余的程序员从事个人项目,为此,我需要让 python 告诉 cmd 通过命令行运行外部程序。
例如,我需要在 Python 上chdir ("C:\blah\blah")
,然后运行externalprogram -w "<destination>\newName.fileType>" "<source>\*.*"
。
我非常迷茫如何做到这一点,任何帮助将不胜感激。
到目前为止,我的代码看起来像这样
import os
os.chdir('C:\Program Files (x86)\<externalProgram>')
os.system('<externalCommand> "<destination>\file.fileType" "<source>\*.*"')
尽管没有将错误发布到外壳,但仍然无法使其工作。
最简单的方法是:
import os
os.system('your command')
是的。 你需要这个页面底部附近的os.system()方法。 您将要作为字符串运行的命令传递。
此外,该软件包中内置了许多 UNIX 系统命令; 您可能会找到您想要的特定呼叫。
你的引号?
os.system('<command> "<destination>\file.fileType" "<source>\*.*") #still in quote
以 ' 开头 以 " 结尾
os.system('<command> "<destination>\file.fileType" "<source>\*.*" ') #closed properly
如果您不希望 python 中的引号在引号中被识别,请在前面加上反斜杠
print (" \" ") # prints out "
说在命令中添加参数
destination = "folder\file.fileType"
source = "source\*.*"
os.system('<command> \" ' + destination + ' \" '+ source+' \" ') #closed
因此,我的主要问题是在更改目录以更改磁盘时没有添加 /D,以及使用“&&”。
import os
changeDir = ('cd /D C:\\Program Files (x86)\\externalProgram')
externalCommand = '<Command> \"<destination>\\newName.fileType\" \"<source>\\*.*\"'
os.system(changeDir + ' && ' externalCommand)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.