简体   繁体   English

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

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

I want to run a subprocess to check if python-docx is installed similar to this , where the lines我想运行一个子进程来检查是否安装了类似于python-docx ,其中行

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

checks if pdftotext is installed or not and if it is not installed ( returncode ==127 ), then it raises an exception.检查是否安装了pdftotext以及是否未安装( returncode ==127 ),然后引发异常。

I want to have a similar implementation to check if python-docx is installed, however, while debugging in Colab, even after installing python-docx , the same returncode is returned.我想要一个类似的实现来检查是否安装了python-docx ,但是,在 Colab 中调试时,即使在安装了python-docx之后,也会返回相同的返回码。

What is the interpretation of ( returncode ==127 ) and how do I raise an exception only when the library is not installed. returncode ==127 )的解释是什么,仅在未安装库时如何引发异常。

Also what exactly does subprocess.run(["pdftotext -v"], shell=True) achieve.还有subprocess.run(["pdftotext -v"], shell=True)到底实现了什么。

I can recommend for different approach for this, pass PIPE s to the stderr and stdout for the spawned process and check those pipes after child return.我可以为此推荐不同的方法,将PIPE传递给生成进程的标准错误和标准输出,并在子进程返回后检查这些管道。

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)

Also consider to use/look subprocess.check_call method below:还可以考虑使用/查看下面的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

I found a solution, it doesn't use subprocess as I mentioned, but I am including the answer to make sure someone who faces a similar problem "To check if a module is installed and if not to catch the error" can try it.我找到了一个解决方案,它没有像我提到的那样使用子进程,但我提供了答案,以确保遇到类似问题的人“检查是否安装了模块,如果没有发现错误”可以尝试一下。

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

In case importing the module creates problems, I'm still looking for a solution that runs shell subprocesses without having to import the module.如果导入模块产生问题,我仍在寻找一种无需导入模块即可运行 shell 子流程的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM