无法通过标准输出的“全局”重定向到日志文件获取子进程的返回码:Fe:
>>> rc = subprocess.call(['ping', '-c1', 'google.com'])
PING google.com (173.194.69.102) 56(84) bytes of data.
64 bytes from bk-in-f102.1e100.net (173.194.69.102): icmp_seq=1 ttl=46 time=86.1 ms
--- google.com ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 86.141/86.141/86.141/0.000 ms
>>> rc
0
rc为0,我可以使用它,但如果这样做:
>>> sys.stdout=open('/var/log/test','a')
>>> rc = subprocess.call(['ping', '-c1', 'google.com'])
PING google.com (173.194.69.102) 56(84) bytes of data.
64 bytes from bk-in-f102.1e100.net (173.194.69.102): icmp_seq=1 ttl=46 time=86.9 ms
--- google.com ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 86.947/86.947/86.947/0.000 ms
>>> rc
>>> sys.stdout.flash()
1st - rc 进入文件,不再考虑脚本。所以我无法使用它。
第二 - 仅在 sys.stdout.flash() 之后
3rd - 只有当我这样做时,ping 结果才会进入文件
rc = subprocess.call(['ping', '-c1', 'google.com'],stdout=sys.stdout)
主要问题是如何防止返回代码重定向到标准输出文件?