问题 运行 批处理文件 Python

Problems running batch files with Python

我是 Python 的新手,一直在尝试 运行 一个 .cmd 文件,但它不会 运行 它来自正确的位置。我的文件 Run_setup.cmd 正在设置另一个带有一堆相关文件的不同软件,因此为了我的理智,我将它们隔离在它们自己的文件夹中。

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

If cwd is not None, the function changes the working directory to cwd before executing the child. cwd can be a str and path-like object. In particular, the function looks for executable (or for the first item in args) relative to cwd if the executable path is a relative path.

我目前使用 cwd=r' C:\LargeFolder\Files\CorrectFolder' 基于 this post,它似乎适用于任何文件路径,但我似乎无法让它为我工作。

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' ' 的目的是什么?

参数为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()

您的错误是由于没有转义您的 \. 您需要在要添加到子文件夹的位置转义“\”,然后就可以开始了。

myDir = myDir + '\CorrectFolder'

应该是

myDir = myDir + '\CorrectFolder'

这个对我有用:

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()