让我们考虑 Linux 平台,我需要执行一个名为 smart.exe 的程序,该程序使用 input.dat 文件。这两个文件都放在同一目录中,每个文件具有相同的文件权限 777。
现在,如果我在终端窗口中运行以下命令,smart.exe 将完全执行,没有任何错误。
$./smart.exe input.dat
另一方面,如果我使用位于同一目录中的以下名为 my_script.py 的 python 脚本,则会收到错误。
my_script.py 具有以下代码:
#!/usr/bin/python
import os, subprocess
exit_code = subprocess.call("./smart.exe input.dat", shell = False)
错误如下:
File "my_script.py", line 4, in <module>
exit_code = subprocess.call("./smart.exe input.dat", shell = False)
File "/usr/lib64/python2.6/subprocess.py", line 478, in call
p = Popen(*popenargs, **kwargs)
File "/usr/lib64/python2.6/subprocess.py", line 642, in __init__
errread, errwrite)
File "/usr/lib64/python2.6/subprocess.py", line 1234, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
有人可以告诉我为什么会发生这种情况吗?请注意,smart.exe 需要大约 10 秒才能完全完成。这或许是问题的线索。
还请告知是否有其他方法可以从 my_script.py 运行 smart.exe。非常感谢您的解决方案!
最佳答案
您应该决定是否需要 shell 支持。
如果您希望使用 shell(此处不需要),则应使用 exit_code = subprocess.call("./smart.exe input.dat", shell=True)
。然后 shell 解释您的命令行。
如果您不想要它(因为您不需要它并且希望避免不必要的复杂性),则应该执行 exit_code = subprocess.call(["./smart.exe", "input.dat"], shell=False)
。
(在 Linux 下命名二进制文件 .exe
是没有意义的。)
关于python - 为什么 subprocess.call () 在 Linux 中显示错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35521820/