sys.stdout.write或print覆盖subprocess.call输出
写了个小程序,但是在输出到文本时出现了问题,请大家帮忙解答下,先谢了哈!
程序:
1 import subprocess
2
3
4 import sys
5 sys.stdout = open("record.txt","w")
6
7 fp = open("record.txt","w")
8 def func1():
9 uname = "uname"
10 uname_arg = "-a"
11 tmp_str = "the system information is : " + "/n"
12 sys.stdout.write( tmp_str ) ######此处改为print函数输出,问题也一样
13 subprocess.call([uname, uname_arg],stdout=fp)
14
15 def func2():
16 diskspace = "df"
17 diskspace_arg = "-h"
18 tmp_str = "the disk information is : " + "/n"
19 sys.stdout.write( tmp_str )
20 subprocess.call([diskspace,diskspace_arg],stdout=fp)
21 def main():
22 func1()
23 func2()
24
25 if __name__ == "__main__":
26 main()
~
~
输出为:
the system information is : /nthe disk information is : /nv 28 19:23:11 UTC 2011 i686 G NU/Linux
2 Filesystem Size Used Avail Use% Mounted on
3 /dev/sda5 19G 6.3G 12G 35% /
4 none 997M 212K 996M 1% /dev
5 none 1002M 24K 1002M 1% /dev/shm
6 none 1002M 76K 1002M 1% /var/run
7 none 1002M 0 1002M 0% /var/lock
8 /dev/sda1 118M 44M 68M 40% /boot
9 /dev/sda7 98G 1.5G 92G 2% /home
请大家注意以上输出中标明的红色部分, 出现 sys.stdout.write或print覆盖subprocess.call输出 ,我把它的位置换到其它地方,仍然不能解决,为何先执行后者,再执行前者呢?
求解答
[解决办法]
#!/usr/bin/env pythonimport subprocessimport syslog = open('dfuname.txt', 'w')def fun1(): args = ['uname', '-a'] log.write("The system information is:\n") log.flush() subprocess.call(args, stdout=log)def fun2(): args = ['df', '-h'] log.write("The disk information is:\n") log.flush() subprocess.call(args, stdout=log)def main(): fun1() fun2()if __name__ == '__main__': main()