Dav*_*ker 18 python command-line subprocess call file-exists
我已经想出如何使用call()来获取我的python脚本来运行命令:
import subprocess
mycommandline = ['lumberjack', '-sleep all night', '-work all day']
subprocess.call(mycommandline)
Run Code Online (Sandbox Code Playgroud)
这有效,但是有一个问题,如果用户的命令路径中没有伐木工人怎么办?如果将伐木工人放在与python脚本相同的目录中,它会起作用,但是脚本如何知道它应该寻找伐木工人?我想如果有一个命令未找到错误,则樵夫不会命令路径,该脚本可以揣摩它的目录是什么,寻找伐木工人有最后警告用户复制成樵夫的一个如果两个地方都没有找到那两个地方.我如何找出错误信息是什么?我读到check_call()可以返回错误消息和一些关于returncode属性的信息.我找不到关于如何使用check_call()和returncode的示例,消息将是什么或如何判断消息是否为command-not-found.
我是否正确地走这条路?
The*_*eke 24
一个简单的片段:
try:
subprocess.check_call(['executable'])
except subprocess.CalledProcessError:
pass # handle errors in the called executable
except OSError:
pass # executable not found
Run Code Online (Sandbox Code Playgroud)
subprocessOSError当找不到命令时,将引发异常.
找到subprocess命令并为您运行命令后,将从命令返回结果代码.标准是代码0表示成功,任何故障都是一些非零错误代码(这会有所不同;请检查您正在运行的特定命令的文档).
因此,如果你抓住了,OSError你可以处理不存在的命令,如果检查结果代码,你可以找出命令是否成功.
最棒的subprocess是你可以让它收集来自stdout和的所有文本stderr,然后你可以丢弃它或者将它丢弃或者记录或者按照你喜欢的方式显示它.我经常使用一个丢弃命令的所有输出的包装器,除非命令失败,在这种情况下stderr输出文本.
我同意你不应该要求用户复制可执行文件.程序应该在PATH变量中列出的目录中; 如果程序丢失则应安装,或者如果它安装在不在PATH用户的目录中,则应更新PATH包含该目录.
请注意,您可以选择subprocess使用各种硬编码路径多次尝试执行可执行文件:
import os
import subprocess as sp
def _run_cmd(s_cmd, tup_args):
lst_cmd = [s_cmd]
lst_cmd.extend(tup_args)
result = sp.call(lst_cmd)
return result
def run_lumberjack(*tup_args):
try:
# try to run from /usr/local/bin
return _run_cmd("/usr/local/bin/lumberjack", tup_args)
except OSError:
pass
try:
# try to run from /opt/forest/bin
return _run_cmd("/opt/forest/bin/lumberjack", tup_args)
except OSError:
pass
try:
# try to run from "bin" directory in user's home directory
home = os.getenv("HOME", ".")
s_cmd = home + "/bin/lumberjack"
return _run_cmd(s_cmd, tup_args)
except OSError:
pass
# Python 3.x syntax for raising an exception
# for Python 2.x, use: raise OSError, "could not find lumberjack in the standard places"
raise OSError("could not find lumberjack in the standard places")
run_lumberjack("-j")
Run Code Online (Sandbox Code Playgroud)
编辑:在考虑了一下之后,我决定完全改写上面的内容.传递一个位置列表要清晰得多,并且循环尝试替代位置,直到一个工作.但是如果不需要,我不想为用户的主目录构建字符串,所以我只是将可调用的内容放入备选列表中.如果您对此有任何疑问,请询问.
import os
import subprocess as sp
def try_alternatives(cmd, locations, args):
"""
Try to run a command that might be in any one of multiple locations.
Takes a single string argument for the command to run, a sequence
of locations, and a sequence of arguments to the command. Tries
to run the command in each location, in order, until the command
is found (does not raise OSError on the attempt).
"""
# build a list to pass to subprocess
lst_cmd = [None] # dummy arg to reserve position 0 in the list
lst_cmd.extend(args) # arguments come after position 0
for path in locations:
# It's legal to put a callable in the list of locations.
# When this happens, we should call it and use its return
# value for the path. It should always return a string.
if callable(path):
path = path()
# put full pathname of cmd into position 0 of list
lst_cmd[0] = os.path.join(path, cmd)
try:
return sp.call(lst_cmd)
except OSError:
pass
raise OSError('command "{}" not found in locations list'.format(cmd))
def _home_bin():
home = os.getenv("HOME", ".")
return os.path.join(home, "bin")
def run_lumberjack(*args):
locations = [
"/usr/local/bin",
"/opt/forest/bin",
_home_bin, # specify callable that returns user's home directory
]
return try_alternatives("lumberjack", locations, args)
run_lumberjack("-j")
Run Code Online (Sandbox Code Playgroud)
哇,太快了!我将 Theodros Zelleke 的简单示例和 steveha 对函数的使用与关于 OSError 的 abarnert 评论和 Lattyware 关于移动文件的评论结合起来:
import os, sys, subprocess
def nameandpath():
try:
subprocess.call([os.getcwd() + '/lumberjack'])
# change the word lumberjack on the line above to get an error
except OSError:
print('\nCould not find lumberjack, please reinstall.\n')
# if you're using python 2.x, change the () to spaces on the line above
try:
subprocess.call(['lumberjack'])
# change the word lumberjack on the line above to get an error
except OSError:
nameandpath()
Run Code Online (Sandbox Code Playgroud)
我在 Mac OS-X (6.8/Snow Leopard)、Debian (Squeeze) 和 Windows (7) 上进行了测试。它似乎在所有三个操作系统上都按照我想要的方式工作。我尝试使用 check_call 和 CalledProcessError 但无论我做什么,我似乎每次都会收到错误,并且无法让脚本来处理错误。为了测试脚本,我将名称从“lumberjack”更改为“deadparrot”,因为我的脚本目录中有 lumberjack。
您认为这个脚本的编写方式有什么问题吗?