具有多个参数、变量和当前工作目录的命令行

Command line with multiple arguments, variables and current working directory

我正在尝试使用 Popen 调用命令行。

命令行运行在shell

cd C:\Program Files (x86)\Inventor
Inventor -exe -- no-gui -f C:\Users\Vince\Documents\Inventor\Inventor.iam

但是当我在我的程序中使用 Popen 尝试这个时

from subprocess import *
from os.path import expanduser

home = expanduser("~")
path = home + "\Documents\Inventor\Inventor.iam"
cmd = "Inventor -exe -- no-gui -f " + path
Popen(cmd, cwd="C:\Program Files (x86)\Inventor")

它returns我FileNotFoundError: [WinError 2]

所以我搞不懂文件路径有什么问题

在参数中添加 (shell =True)

但谨慎使用 warning for using shell = True argument

您可以尝试添加可执行文件的完整路径:

#!/usr/bin/env python
import os.path
import subprocess

exedir = os.path.join(os.environ['PROGRAMFILES'], "Inventor")
exepath = os.path.join(exedir, "Inventor.exe")
filepath = os.path.join(os.path.expanduser('~'), r'Documents\Inventor\Inventor.iam')
subprocess.check_call([exepath, '-exe', '--', 'no-gui', '-f', filepath],
                      cwd=exedir)

请参阅 Popen with conflicting executable/path,以了解在使用和不使用 shell=True 时如何搜索可执行文件。

要避免对特殊 Windows 文件夹的路径进行硬编码,请参阅 Python, get windows special folders for currently logged-in user