【问题标题】:Can I tell Python to execute command line in cmd?我可以告诉 Python 在 cmd 中执行命令行吗?
【发布时间】:2017-03-22 18:56:21
【问题描述】:

作为一个非常业余的程序员,我正在从事一个个人项目,为此,我需要让 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>\*.*"')

尽管没有将错误发布到 shell,但仍然无法使其工作。

【问题讨论】:

  • 一般可以用subprocess.callimport subprocess; subprocess.call(['C:\blah\blah\newName.fileType']),How do I execute a program from python?
  • 您可能希望chdir 的效果持续/存在于您的python 进程/脚本 - os.chdir(path)?
  • 你会“接受”下面的首选答案吗?如果你愿意,你可以接受你自己的。要接受,请单击您喜欢的答案旁边的勾号。请考虑为您认为有帮助的任何其他人点赞;这不是强制性的,但这样做很好。最后我看到 Prune 的答案没有得到回复 - 如果可以的话,请考虑对每个人做出回应。
  • 投反对票,见上文。如果您可以点击勾选标记,很高兴取消投票。

标签: python python-2.7 command-line cmd windows-7


【解决方案1】:

最简单的方法是:

import os
os.system('your command')

【讨论】:

  • 我试过这个,我的 cmd 闪烁打开和关闭,没有任何动静。我怎样才能检查问题是什么?
  • @Hallquist 如果你试图执行os.system('chdir your/dir'),那么它不会有任何效果。它打开 cmd 在其中更改目录并关闭。如果您想更改当前 python 脚本的工作目录,那么您可能需要使用os.chdir('your/dir')(如@greybeard 建议的那样)
  • 我尝试并更新了我的帖子。感谢您抽出宝贵时间提供帮助!
【解决方案2】:

是的。您需要 os.system() 方法,在this page 的底部附近。您将要运行的命令作为字符串传递。

此外,该软件包中内置了许多 UNIX 系统命令;您可能会找到您想要的特定呼叫。

【讨论】:

    【解决方案3】:

    你的引号?

    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 
    

    【讨论】:

    • 所以,我已经让它打印出我想要的样子,但无法让它做任何事情。它只是闪烁,没有任何反应。似乎我无法正确更改目录并且它停留在 user\pthyon 上。如何让它在同一个 cmd 窗口中连续运行 2 个或多个命令?
    • import os os.chdir('C:\Program Files (x86)') os.system("cd") os.system("PAUSE")
    【解决方案4】:

    因此,我的主要问题是在更改目录以更改磁盘时没有添加 /D,以及使用“&&”。

    import os
    changeDir = ('cd /D C:\\Program Files (x86)\\externalProgram')
    externalCommand = '<Command> \"<destination>\\newName.fileType\" \"<source>\\*.*\"'
    os.system(changeDir + ' && ' externalCommand)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-24
      • 2019-03-20
      • 1970-01-01
      • 2017-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-14
      相关资源
      最近更新 更多