Python subprocess Popen
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:~/开发者_如何学JAVApython# 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...
I see you have an empty string in your args:
... ,"-Oqv","","-Ln", ...
^^
Is that possibly causing a problem for snmpget?
You've got two arguments in one, too:
"192.168.1.1 1.3.6.1.2.1.2.2.1.10.7"
That should be split in two:
"192.168.1.1", "1.3.6.1.2.1.2.2.1.10.7"
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:
snmpget -v 1 -c public -Oqv -Ln '192.168.1.1 1.3.6.1.2.1.2.2.1.10.7'
If you wanted the test you're running from the command line to be analogous, you'd need to do the following:
snmpget -v 1 -c public -Oqv '' -Ln "192.168.1.1 1.3.6.1.2.1.2.2.1.10.7"
...noting the empty quotes after the -Oqv
, and that 192.168.1.1
is in the same argument as 1.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:
- Record exit status.
- Record the contents of stderr, and print them a non-zero exit.
By the way, a bit more whitespace isn't necessarily a bad thing when it comes to readability. Consider the following:
p = subprocess.Popen([
'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,
stderr=subprocess.PIPE)
out, err = p.communicate()
if p.returncode != 0:
raise Exception('snmpget exited with status %r: %r' % (p.returncode. err)
Try to add a shell=True parameter to Popen call.
精彩评论