[英]Print Subprocess.Popen
我对函数Popen有问题。 我尝试从我使用的命令中检索输出。
print(subprocess.Popen("dig -x 156.17.86.3 +short", shell=True, stdout=subprocess.PIPE).communicate()[0].decode('utf-8').strip())
这部分有效,但是当我在Popen
调用变量时(用于IP地址)
print(subprocess.Popen("dig -x ",Adres," +short", shell=True, stdout=subprocess.PIPE).communicate()[0].decode('utf-8').strip())
发生这样的事情:
raise TypeError("bufsize must be an integer")
我认为命令会出现问题,因此我使用了以下解决方案:
command=['dig','-x',str(Adres),'+short']
print(subprocess.Popen(command, shell=True, stdout=subprocess.PIPE).communicate()[0].decode('utf-8').strip())
但是现在返回值不同于console:
dig -x 156.17.4.20 +short
vpn.ii.uni.wroc.pl.
我该如何在脚本中打印上面的名字? 非常感谢
错误是您没有传递单个字符串,而是传递了多个单独的参数:
subprocess.Popen("dig -x ",Adres," +short", shell=True, stdout=subprocess.PIPE)
如果您查看docs中的Popen
构造函数,则意味着您将"dig -x"
作为args
字符串传递,将Adres
作为bufsize
传递,并将"+short"
传递为executable
。 那绝对不是你想要的。
您可以通过构建具有串联或字符串格式的字符串来解决此问题:
subprocess.Popen("dig -x " + str(Adres) + " +short", shell=True, stdout=subprocess.PIPE)
subprocess.Popen(f"dig -x {Adres} +short", shell=True, stdout=subprocess.PIPE)
但是,更好的解决方法是仅在此处不使用外壳程序,并将参数作为列表传递:
subprocess.Popen(['dig', '-x', Adres, '+short'], stdout=subprocess.PIPE)
请注意,如果执行此操作,则必须删除shell=True
,否则将不起作用。 (它实际上可能会在Windows上运行,而不是在* nix,你不应该这样做,即使在Windows上。)在你的问题的编辑的版本,你不这样做,所以它仍然是错误的。
当我们使用它时,如果您确实正在做所有事情,那么您实际上不需要创建Popen
对象并与其进行communicate
。 一个更简单的解决方案是:
print(subprocess.run(['dig', '-x', Adres, '+short'], stdout=subprocess.PIPE).stdout.decode('utf-8'))
另外,如果您在调试像您这样的复杂表达式时遇到问题,将其分解成可以单独调试的单独部分(使用额外的print
或调试器断点)确实有帮助:
proc = subprocess.run(['dig', '-x', Adres, '+short'], stdout=subprocess.PIPE)
result = proc.stdout.decode('utf-8')
print(result)
这基本上是同一件事,效率几乎相同,但更易于阅读和调试。
当我使用Adres = '156.17.4.20'
运行此Adres = '156.17.4.20'
,我得到的正是您要查找的输出:
vpn.ii.uni.wroc.pl.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.