使用subprocess.Popen调用dig命令传入变量触发TypeError问题求助
解决subprocess.Popen循环传参时的TypeError问题
嗨,我来帮你搞定这个问题!你遇到的TypeError完全是因为给subprocess.Popen()传参的方式不对,咱们一步步理清楚:
错误原因
你单独执行命令时,把整个命令写成一个完整字符串传给Popen,这没问题;但到循环里时,你把命令拆成了多个零散参数:
subprocess.Popen("dig -x ",Adres," +short", shell=True, stdout=subprocess.PIPE)
而subprocess.Popen()的第二个参数是bufsize(要求必须是整数),第三个参数是executable,这就导致它把你的IP地址Adres当成了bufsize参数,自然触发了TypeError: bufsize must be an integer的错误。
两种解决方案
方案1:拼接成完整命令字符串(保留shell=True)
如果你还是想用shell=True,需要把命令和变量拼成一个完整的字符串,推荐用f-string来实现,简洁又清晰:
for adres in IP: # 用f-string把变量嵌入命令字符串 cmd = f"dig -x {adres} +short" output = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0].decode('utf-8').strip() print(output)
⚠️ 注意:如果adres来自不可信输入(比如用户手动输入),shell=True可能存在命令注入的安全风险,这种情况下更推荐方案2。
方案2:用列表传参(更安全,不依赖shell)
这是subprocess官方推荐的用法,把命令和每个参数拆成列表的元素,不需要shell解析,既安全又不会出现参数传递错误:
for adres in IP: # 命令和参数都放在列表里,Popen会正确解析每个部分 output = subprocess.Popen(["dig", "-x", adres, "+short"], stdout=subprocess.PIPE).communicate()[0].decode('utf-8').strip() print(output)
额外小技巧:用更简洁的subprocess函数
其实subprocess提供了更方便的check_output()函数,可以帮你省去手动调用communicate()的步骤,甚至自动完成字节流到字符串的解码:
import subprocess for adres in IP: # text=True 自动把字节流转成字符串,省去decode步骤 output = subprocess.check_output(["dig", "-x", adres, "+short"], text=True).strip() print(output)
这样代码更简洁,可读性也更高~
内容的提问来源于stack exchange,提问作者Gracjan
相关产品推荐
相关产品推荐

