有没有办法在windows上用python运行命令?

2024-04-20 09:54:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试在windows中使用python并运行到 WindowsError: [Error 2] The system cannot find the file specified错误,目前我的电脑上没有script.exe,手动运行它会抛出错误'script.exe' is not recognized as an internal or external command,operable program or batch file.,我希望通过python运行时也会抛出同样的错误,如何修复这个错误?非常感谢您的意见

你知道吗代码:-你知道吗

cmd = "script.exe"
print "Executing " + cmd
fetchPipe = subprocess.Popen(cmd.split(' '), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(output, error) = fetchPipe.communicate()

Tags: orthecmdwindows错误scripterrorexe
2条回答
def find_abs_path(executable_fname):
    if os.path.exists(executable_fname): # in case it is in our cwd
        return os.path.abspath(os.path.join(".",executable_fname))
    for dirname in os.environ["PATH"].split(";"): # split dependant on your os
        if executable_fname in os.listdir(dirname):
           return os.path.join(dirname,executable_fname)

应该搜索路径并找到可执行文件的绝对路径

这是推荐的方法。。。你知道吗

但是你可以通过一个env

subprocess.Popen(cmd_args,env=os.environ,...)

这应该为运行的子shell提供相同的路径变量。。。因此,它可能会找到可执行文件。。。你知道吗

您必须在以下解决方案中进行选择:

  1. 传递relative path并将当前工作目录设置为包含脚本.exe在尝试打开文件之前使用os.chdir('folderPath')

或者

  1. 使用cmd = os.getcwd() + "\\script.exe"absolute path传递到script.exe文件

通过使用第二种方法,您将拥有:

cmd = os.getcwd() + "\\script.exe"
print "Executing " + cmd
fetchPipe = subprocess.Popen(cmd.split(' '), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(output, error) = fetchPipe.communicate()

相关问题 更多 >