Linux中python subprocess.Popen错误

1 投票
1 回答
1439 浏览
提问于 2025-04-17 22:06

我现在正在用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的内容,然后在命令行中运行,那么这个可执行程序就可以正常运行。有什么想法吗?谢谢。

1 个回答

2

好吧,正如错误信息所说:

OSError: [Errno 2] 没有这样的文件或目录

你给出的路径中没有叫做 '../../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()

撰写回答