子流程调用不是在等

2024-04-19 02:36:18 发布

您现在位置:Python中文网/ 问答频道 /正文

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

你知道吗输出.readlines()返回[],即使文件中写入了一些数据。这里有点不对劲。你知道吗

看起来像子流程调用()没有阻塞,文件正在读取函数后写入。我该怎么解决这个问题?你知道吗


Tags: 文件txttrueaswithstdoutopenshell
1条回答
网友
1楼 · 发布于 2024-04-19 02:36:18

with open('pf_d.txt', 'w+') as outputfile:构造称为上下文管理器。在本例中,资源是由handle/file对象outputfile表示的文件。上下文管理器确保在上下文为时关闭文件。关闭意味着刷新,然后重新打开文件将显示其所有内容。因此,解决问题的一个方法是在文件关闭后读取文件:

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

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

另一种选择是在刷新和查找后重新使用相同的文件对象:

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

文件句柄总是由文件指针表示,表示文件中的当前位置。write()将此指针转发到文件的末尾。seek(0)将其移回开头,以便随后的read()从文件开头开始。你知道吗

相关问题 更多 >