![](/img/trans.png)
[英]How to check the status of a shell script using subprocess module in Python?
[英]How to check if a Module is installed or not using a subprocess in shell?
我想运行一个子进程来检查是否安装了类似于此的python-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)
到底实现了什么。
我可以为此推荐不同的方法,将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)
还可以考虑使用/查看下面的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 子流程的解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.