gpt4 book ai didi

Python, subprocess, call(), check_call 和 returncode 来查找命令是否存在

转载 作者:IT老高 更新时间:2023-10-28 21:09:33 25 4
gpt4 key购买 nike

我已经弄清楚如何使用 call() 让我的 python 脚本运行命令:

import subprocess

mycommandline = ['lumberjack', '-sleep all night', '-work all day']
subprocess.call(mycommandline)

这可行,但有一个问题,如果用户的命令路径中没有伐木 worker 怎么办?如果将伐木 worker 放在与 python 脚本相同的目录中,它会起作用,但是脚本如何知道它应该寻找伐木 worker ?我想如果有一个 command-not-found 错误,那么 lumberjack 就不会在命令路径中,脚本可以尝试找出它的目录是什么并在那里寻找 lumberjack,最后警告用户将 lumberjack 复制到其中之一如果在任何一个地方都没有找到那两个地方。如何找出错误消息是什么?我读到 check_call() 可以返回错误消息和有关 returncode 属性的内容。我找不到有关如何使用 check_call() 和 returncode、消息是什么或如何判断消息是否为 command-not-found 的示例。

我的做法是否正确?

最佳答案

一个简单的片段:

try:
subprocess.check_call(['executable'])
except subprocess.CalledProcessError:
pass # handle errors in the called executable
except OSError:
pass # executable not found

关于Python, subprocess, call(), check_call 和 returncode 来查找命令是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14106720/

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