从 Python 代码执行终端 cmd 会在 IDE 和终端本身中返回不同的结果



我想在Python代码中执行which jupyter命令,以便接收我的jupyter二进制文件的位置。

我的名为ReportGenerator.py的 Python 脚本如下所示:

from subprocess import call
if __name__ == "__main__":
    call(["which", "jupyter"])

输出为:

但是,如果我导航到终端中的同一文件夹并执行代码 Python 脚本,那么:

Kamils-MacBook-Pro-2:project F1sherKK$ python3 ReportGenerator.py /Users/F1sherKK/.pyenv/versions/3.6.1/bin/jupyter

它有效...所以我确保我的 PyCharm IDE 使用与我的终端相同的 python 3.6.1。我目前没有使用任何虚拟环境。

有人可以解释为什么会发生这种情况吗?

subprocess.call()执行给定的命令并返回命令的返回代码(0 => 好的,其他任何内容都是错误(。

交互式 Python shell

(无论是否嵌入在 IDE 中(显示命令的 stdout 和 stderr 流以及返回代码,但这只是交互式 Python shell 的工件 - 正如您注意到的那样,如果您运行与脚本相同的代码,这不会将任何内容打印到 stdout。

在这里,您要改用subprocess.check_output(),这将以字符串形式返回命令的输出。然后你需要明确地将此字符串打印到 python 的进程 stdout 中:

import subprocess
if __name__ == "__main__":
    found = subprocess.check_output(["which", "jupyter"])
    print(found)

我不知道为什么会发生这种情况,但这是我用于从控制台和 cron 运行的代码:

def which(name):
'''
Replace unix 'which' command.
Tested on windows10 and linux mint. Should work on all platforms.
:param name: Requested command name
:type name: str
:return: Full path to command
:rtype: str
'''
for path in os.getenv("PATH").split(os.path.pathsep):
    full_path = path + os.sep + name
    if os.path.exists(full_path) and os.access(full_path, os.X_OK):
        return full_path
raise ValueError('Cant fint command %s')%name

编辑:在 Windows 上,该函数将返回不可执行文件的值。要为 Windows 编写自己的解决方案,请参阅:descusion

最新更新