import subprocess
with open('disk.txt','w') as fr:
subprocess.Popen(['df','-h'],stdout=fr)
with open('disk.txt','r') as fp:
header=fp.readline()
for line in fp:
val=line.split()[-2][:-1]
print(val)
答案 0 :(得分:1)
subprocess.Popen()
启动一个进程并返回一个可用于检查其状态的对象;它不等待该进程完成,因此没有理由期望在代码运行其读取之前完成写入。
一种选择是使用subprocess.call()
而不是subprocess.Popen()
,因此您的代码会在继续之前等待该过程完成:
with open('disk.txt','w') as fr:
subprocess.call(['df','-h'], stdout=fr)
另一种方法是明确延迟:
with open('disk.txt','w') as fr:
p = subprocess.Popen(['df','-h'], stdout=fr)
p.wait()
当然,你可以通过直接在输出上迭代而不是写入文件来避免整个问题:
p = subprocess.Popen(['df', '-h'], stdout=subprocess.PIPE)
header = p.stdout.readline()
for line in p.stdout:
val = line.rsplit(None, 2)[-2].rstrip('%')
print val