Python 子进程 Popen
为什么它不工作? :|
import subprocess
p = subprocess.Popen([r"snmpget","-v","1","-c","public","-Oqv","","-Ln","192.168.1.1 1.3.6.1.2.1.2.2.1.10.7"],stdout=subprocess.PIPE).communicate()[0]
print p
运行脚本:
root@OpenWrt:~/python# python w.py
root@OpenWrt:~/python#
其打印空行:| Bu在同一台机器上,从shell:
root@OpenWrt:~/python# snmpget -v 1 -c public -Oqv -Ln 192.168.1.1 1.3.6.1.2.1.2.2.1.10.7
3623120418
我知道有“-Oqv”,“”,但如果没有它,我会从 snmpget 收到错误...
Why its not working? :|
import subprocess
p = subprocess.Popen([r"snmpget","-v","1","-c","public","-Oqv","","-Ln","192.168.1.1 1.3.6.1.2.1.2.2.1.10.7"],stdout=subprocess.PIPE).communicate()[0]
print p
Run script:
root@OpenWrt:~/python# python w.py
root@OpenWrt:~/python#
its printing empty line :|
Bu on the same machine, from shell:
root@OpenWrt:~/python# snmpget -v 1 -c public -Oqv -Ln 192.168.1.1 1.3.6.1.2.1.2.2.1.10.7
3623120418
I know tere is "-Oqv","", but without it i got error from snmpget...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
尝试在 Popen 调用中添加 shell=True 参数。
Try to add a shell=True parameter to Popen call.
我发现您的参数中有一个空字符串:
这是否可能导致 snmpget 出现问题?
您也将两个参数合二为一:
应该将其一分为二:
在命令行上键入命令时,shell 会为您执行此拆分操作。当以这种方式调用
subprocess.Popen()
时,您必须自己拆分所有参数。如果你运行以下命令,你会得到同样的错误:I see you have an empty string in your args:
Is that possibly causing a problem for snmpget?
You've got two arguments in one, too:
That should be split in two:
When typing a command on the command line, the shell does this splitting for you. When calling
subprocess.Popen()
in this way, you'll have to do all the argument splitting yourself. You'd get the same error if you ran:如果您希望从命令行运行的测试是类似的,则需要执行以下操作:
...注意
-Oqv
后面的空引号,以及192.168.1.1
与1.3.6
... 具有相同的参数,这几乎肯定不是您想要的。正如 Greg 所建议的,您几乎肯定应该将最后一个参数拆分为两个单独的数组元素,并取出空字符串。
同时,您可以采取一些简单的措施来改进错误处理:
顺便说一句,就可读性而言,多一点空白不一定是坏事。考虑以下几点:
If you wanted the test you're running from the command line to be analogous, you'd need to do the following:
...noting the empty quotes after the
-Oqv
, and that192.168.1.1
is in the same argument as1.3.6
..., which is almost certainly not what you want.As Greg suggests, you should almost certainly split that last argument into two separate array elements, and take out the empty string.
In the mean time, there are simple things you can do to improve error-handling:
By the way, a bit more whitespace isn't necessarily a bad thing when it comes to readability. Consider the following: