如何使用 shell 中的子进程检查模块是否已安装?

How to check if a Module is installed or not using a subprocess in shell?

我想运行一个子进程来检查是否安装了类似于thispython-docx,其中行

verify_installation = subprocess.run(["pdftotext -v"], shell=True)
        if verify_installation.returncode == 127:

检查是否安装了 pdftotext,如果没有安装 (returncode ==127),则抛出异常。

我想有一个类似的实现来检查是否安装了 python-docx,但是,在 Colab 中调试时,即使在安装 python-docx 之后,也会返回相同的返回码。

(returncode ==127) 的解释是什么以及如何仅在未安装库时引发异常。

另外 subprocess.run(["pdftotext -v"], shell=True) 究竟实现了什么。

我可以为此推荐不同的方法,将 PIPEs 传递给生成进程的 stderr 和 stdout,并在子 return.

之后检查这些管道
import subprocess
outs=None
errs=None

try:
    proc=subprocess.Popen(["pdftotext -v"], shell=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE)
    outs, errs = proc.communicate(timeout=15)  #timing out the execution, just if you want, you dont have to!
except TimeoutExpired:
    proc.kill()
    outs, errs = proc.communicate()

#parse the stderr and stdoutput of proc:
f_check_if_has_errors(errs, outs)

同时考虑以下 use/look subprocess.check_call 方法:

try:
  proc = subprocess.check_call(["pdftotext -v"], shell=True)
  proc.communicate()
except subprocess.CalledProcessError:
  # There was an error - command exited with non-zero code

我找到了一个解决方案,它没有像我提到的那样使用子进程,但我包含了答案以确保遇到类似问题的人“检查是否安装了模块,如果没有捕获错误"可以试试

try:
    import docx
except ImportError as e:
    raise Exception( 
        #do something
    )

万一导入模块产生问题,我仍在寻找无需导入模块即可运行 shell 子进程的解决方案。