我对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())但是,现在返回的值与控制台不同:
dig -x 156.17.4.20 +short
vpn.ii.uni.wroc.pl.我如何在脚本中打印上面的名字?非常感谢
发布于 2018-03-19 20:18:11
错误在于,您传递的不是单个字符串,而是多个单独的参数:
subprocess.Popen("dig -x ",Adres," +short", shell=True, stdout=subprocess.PIPE)如果您查看 constructor in the docs,这意味着您要将"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)但是,更好的解决方法是不要在这里使用shell,并将参数作为列表传递:
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'运行这个程序时,我得到了您想要的输出:
vpn.ii.uni.wroc.pl.https://stackoverflow.com/questions/49371575
复制相似问题