简体   繁体   中英

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

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.

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.

What is the interpretation of ( returncode ==127 ) and how do I raise an exception only when the library is not installed.

Also what exactly does subprocess.run(["pdftotext -v"], shell=True) achieve.

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.

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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