简体   繁体   English

subprocess.call没有等待

[英]subprocess.call is not waiting

with open('pf_d.txt', 'w+') as outputfile:
        rc = subprocess.call([pf, 'disable'], shell=True, stdout=outputfile, stderr=outputfile)
        print outputfile.readlines()

output.readlines() is returning [] even though the file is written with some data. 即使文件已写入某些数据,output.readlines()仍返回[]。 Something is wrong here. 这里不对劲。

looks like subprocess.call() is not blocking and the file is being written after the read function. 看起来subprocess.call()没有阻塞,并且在read函数之后正在写入文件。 How do i solve this? 我该如何解决?

The with open('pf_d.txt', 'w+') as outputfile: construct is called context manager. with open('pf_d.txt', 'w+') as outputfile:构造称为上下文管理器。 In this case, the resource is a file represented by the handle/file object outputfile . 在这种情况下,资源是由handle / file对象outputfile表示的文件。 The context manager makes sure that the file is closed when the context is left . 上下文管理器确保在离开上下文时关闭文件。 Closing implicates flushing, and re-opening the file after that will show you all its contents. 关闭意味着刷新,然后重新打开文件将向您显示其所有内容。 So, one option to solve your issue is to read your file after it has been closed: 因此,解决问题的一种方法是在关闭文件读取文件:

with open('pf_d.txt', 'w+') as outputfile:
    rc = subprocess.call(...)

with open('pf_d.txt', 'r') as outputfile:
    print outputfile.readlines()

Another option is to re-use the same file object, after flushing and seeking: 另一种选择是在刷新并查找后重新使用相同的文件对象:

with open('pf_d.txt', 'w+') as outputfile:
    rc = subprocess.call(...)
    outputfile.flush()
    outputfile.seek(0)
    print outputfile.readlines()

A file handle is always represented by a file pointer, indicating the current position in the file. 文件句柄始终由文件指针表示,指示文件中的当前位置。 write() forwards this pointer to the end of the file. write()将此指针转发到文件末尾。 seek(0) moves it back to the beginning, so that a subsequent read() startes from the beginning of the file. seek(0)将其移回开头,以便随后的read()从文件的开头开始。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM