subprocess.check\u输出函数的行为有问题

2024-06-11 16:25:40 发布

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

我的代码是:

import subprocess

answer = subprocess.check_output("python ../pydig/pydig @1.1.1.1 +tls=noauth goowdqdqdqdgle.de A",  encoding='utf8')
print (answer)

Pydig是一个查找域名的库。我遇到的问题是,当我执行此程序时,它会告诉我一个名为subprocess.CalledProcessError的子进程:

subprocess.CalledProcessError: Command 'python ../pydig/pydig @1.1.1.1 +tls=noauth goowdqdqdqdgle.de A' returned non-zero exit status 3.

但是当我通过命令提示符执行命令pydig @1.1.1.1 +tls=noauth goowdqdqdqdgle.de A时,它会给我一个有效的输出

这怎么可能

谢谢你的帮助

问候


Tags: 代码answerimportoutputchecktlsdeutf8
1条回答
网友
1楼 · 发布于 2024-06-11 16:25:40

问题是,如果命令失败,^{}将不会产生命令的输出

If the return code was non-zero it raises a CalledProcessError. The CalledProcessError object will have the return code in the returncode attribute and any output in the output attribute.

由于网站不存在,该命令返回一个错误,您得到的只是一个python异常。如果仍要获取输出,请使用带有输出/错误重定向的subprocess.Popensubprocess.run(python 3.5+)

也总是使用参数列表,而不是字符串

Popen为例

handle = subprocess.Popen(["python","../pydig/pydig","@1.1.1.1","+tls=noauth","goowdqdqdqdgle.de","A"], stdout=subprocess.PIPE,stderr=subprocess.PIPE  encoding='utf8')
out,err = handle.communicate()
return_code = handle.wait()
print(return_code,out.decode(),err.decode())

请注意,由于要运行的命令是python代码,您可以将第一个"python"参数替换为sys.executable(因此它使用与脚本相同的解释器运行),或者查找是否无法导入模块和调用函数(避免产生子进程/保留异常链)

相关问题 更多 >