从新编写的文件中读取的Python在modu中不起作用

2024-04-25 04:08:15 发布

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

我正在编写一个python模块,用于处理当前目录的文件。 代码如下:

import subprocess

filename="tmp_file"

#sends ls output to a temporary file
with open(filename, 'w+') as f:
    subprocess.Popen(['ls', '-p'], stdout=f)
    f.seek(0)
    result = f.read()

然而,结果似乎是空的。为什么?(如果我在Python解释器中一次执行一个命令,它将正常工作)


Tags: 模块文件to代码importoutputwithopen
1条回答
网友
1楼 · 发布于 2024-04-25 04:08:15

您需要让子流程通过wait()check_call()或其他备选方案之一完成

subprocess.Popen(['ls', '-p'], stdout=f).wait()

此外,如果您的目标是列出目录的内容,Python有内置的方法来实现这一点,而无需使用子流程

相关问题 更多 >