使用Python运行批处理文件时出现问题

时间:2018-07-05 19:39:35

标签: python batch-file subprocess popen

我对Python相当陌生,一直在尝试使用它运行.cmd文件,但是它不会从正确的位置运行它。我的文件Run_setup.cmd正在设置另一个具有一系列相关文件的不同软件,因此出于我的理智,我将它们隔离在自己的文件夹中。

当前,我可以使.cmd文件从与源代码相同的位置运行。我知道我根据文档说的是用 cwd = r'%s'弄乱了它的文件路径,但我不知道怎么做。

  

如果 cwd 不是 None ,则该函数在执行子级之前将工作目录更改为 cwd 。 cwd可以是类似str和path的对象。特别是,如果可执行文件路径是相对路径,则该函数将查找相对于cwd的可执行文件(或args中的第一项)。

我目前基于this post使用 cwd = r'C:\ LargeFolder \ Files \ CorrectFolder'来获得它,它似乎适用于任何文件路径,但是我可以似乎没有办法为我工作。

from subprocess import Popen

def runCmdfile():
    # File Path to source code:    'C:\LargeFolder\Files'
    myDir = os.getcwd()

    # File Path to .cmd file:      'C:\LargeFolder\Files\CorrectFolder'
    myDir = myDir + '\CorrectFolder'

    runThis = Popen('Run_setup.cmd', cwd=r'%s' % myDir)

    stdout, stderr = runThis.communicate()

我在这里缺少什么,此外,使用 cwd = r''的目的是什么?

3 个答案:

答案 0 :(得分:0)

参数为cwd=r""部分仅需要存在于您的字符串定义中,即可使用原始字符串并使python使用反斜杠忽略特殊序列。

由于您的字符串来自os.getcwd,因此您不需要它。

def runCmdfile():
    # File Path to source code:    'C:\LargeFolder\Files'
    myDir = os.getcwd()

    # File Path to .cmd file:      'C:\LargeFolder\Files\CorrectFolder'
    myDir = os.path.join(myDir, 'CorrectFolder')

    runThis = Popen('Run_setup.cmd', cwd=myDir)

    stdout, stderr = runThis.communicate()

答案 1 :(得分:0)

您的错误是由于没有转义\。 您需要在子文件夹中添加的转义符“ \”转义,然后您应该可以使用。

Europe/Berlin

应该是

myDir = myDir + '\CorrectFolder'

答案 2 :(得分:0)

这个对我有用:

def runCmdfile():
    # File Path to source code:    'C:\LargeFolder\Files'
    myDir = os.getcwd()

    # File Path to .cmd file:      'C:\LargeFolder\Files\CorrectFolder'
    myDir = os.path.join(myDir, 'CorrectFolder')

    # Popen does not take cwd into account for the file to execute
    # so we build the FULL PATH on our own
    runThis = Popen(os.path.join(myDir, 'Run_setup.cmd'), cwd=myDir)

    stdout, stderr = runThis.communicate()
相关问题