如何查找python中是否存在软件

2024-06-01 10:57:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个python代码,它使用os.system()调用gpg命令来解密一些文件,作为更大的文件管理管道的一部分。不过,在我的MacOS10.11.6上,我有一个gpg2版本,可以用来解密文件。你知道吗

因此,我想在脚本中添加一些检查gpg或gpg2是否存在于机器上。你知道吗

我尝试测试gpg调用,并发现可能的操作错误:

try:
    os.system("gpg --version")
except OSError:
    print("gpg not found")

但是即使gpg不存在并且os.system()调用的输出是:

sh: gpg: command not found
32512

你知道我该怎么做吗?你知道吗

(附言:我不知道32512是什么……)


Tags: 文件代码命令版本脚本机器管道os
2条回答

就像os.system()文档告诉你的那样,我想现在10多年了,用subprocess代替。你知道吗

>>> import subprocess
>>> subprocess.check_output(['gpg', ' version'])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/Cellar/python3/3.5.1/Frameworks/Python.framework/Versions/3.5/lib/python3.5/subprocess.py", line 629, in check_output
    **kwargs).stdout
  File "/usr/local/Cellar/python3/3.5.1/Frameworks/Python.framework/Versions/3.5/lib/python3.5/subprocess.py", line 696, in run
    with Popen(*popenargs, **kwargs) as process:
  File "/usr/local/Cellar/python3/3.5.1/Frameworks/Python.framework/Versions/3.5/lib/python3.5/subprocess.py", line 950, in __init__
    restore_signals, start_new_session)
  File "/usr/local/Cellar/python3/3.5.1/Frameworks/Python.framework/Versions/3.5/lib/python3.5/subprocess.py", line 1544, in _execute_child
    raise child_exception_type(errno_num, err_msg)
FileNotFoundError: [Errno 2] No such file or directory: 'gpg'

在Python的最新版本中,您可能更喜欢subprocess.run(),而不是有些笨拙的遗留API函数。你知道吗

来自python docs关于os.system()

Execute the command (a string) in a subshell. This is implemented by calling the Standard C function system(), and has the same limitations. Changes to sys.stdin, etc. are not reflected in the environment of the executed command.

所以这不是要使用的命令。你应该使用欧斯波本现在它被subprocess module取代了。你知道吗

This answer是您正在寻找的一个有效示例。你知道吗

相关问题 更多 >