我对Python相当陌生,一直在尝试使用它运行.cmd文件,但它不会从正确的位置运行它。我的文件Run_setup.cmd正在设置另一个具有一系列相关文件的不同软件,因此出于我的理智,我将它们隔离在自己的文件夹中。
目前,我可以使.cmd文件从与源代码相同的位置运行。我知道我根据文档上的说明用cwd = r'%s'弄乱了文件路径,但我不知道如何。
如果cwd不为None,则函数在执行子级之前将工作目录更改为cwd。cwd可以是类似str和path的对象。特别是,如果可执行文件路径是相对路径,则该函数将查找相对于cwd的可执行文件(或args中的第一项)。
我目前基于此帖子使用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''的目的是什么?
这对我有用:
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()
Este artigo é coletado da Internet.
Se houver alguma infração, entre em [email protected] Delete.
deixe-me dizer algumas palavras