gpt4 book ai didi

python subprocess.Popen 错误在 linux

转载 作者:太空宇宙 更新时间:2023-11-04 09:40:15 25 4
gpt4 key购买 nike

我现在用Python运行一个自己开发的命令行可执行程序:

import subprocess
cmd = '../../run_demo'
print cmd
subprocess.Popen(cmd)

此脚本在 Windows 中运行良好。但是在linux上运行,报错如下:

Traceback:
File "script.py", line 6, in <module>
subprocess.Popen(cmd)
File "/user/lib/python2.5/subprocess.py", line 623, in _init_
erread, errwrite)
File "/user/lib/python2.6/subprocess.py", line 1141, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory

由于脚本print cmd中打印了可执行命令,如果我复制cmd的内容,然后在命令行中运行,那么可执行程序就可以运行。有任何想法吗?谢谢。

最佳答案

好吧,正如错误所说:

OSError: [Errno 2] No such file or directory

您提供的路径中没有诸如 '../../run_demo' 之类的文件。我敢打赌,您正在尝试调用相对于脚本路径的脚本,而它是相对于您运行它的路径。

首先,打印你在 ../.. 处得到的内容:

import os
print os.listdir('../../')

你会看到里面是否有run_demo

然后,打印当前脚本的路径:

pwd = os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir))

现在尝试使用从 pwdrun_demo 路径的相对路径,例如:

rundemo_exec = os.path.join(pwd,'..','..','run_demo')

最后,一旦你验证了所有这些,你想正确地调用 Popen:

subprocess.Popen([rundemo_exec])

subprocess.Popen(rundemo_exec, shell=True)

取决于你是否想将它嵌入到 shell 中。

注意:无论脚本是否确实在您提供的路径中,您说您正在 linux 和 windows 之间制作一个“可移植”应用程序,所以您肯定需要使用 os.path.join ()

关于python subprocess.Popen 错误在 linux,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22377853/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com