无法使用python读取文件
我正在尝试使用 python 3.8.5 读取文件的内容,但输出为空,我不明白我做错了什么。
这是代码:
import subprocess
import os
filename = "ls.out"
ls_command = "ls -la"
file = open(filename, "w")
subprocess.Popen(ls_command, stdout=file, shell=True)
file.close()
# So far, all is ok. The file "ls.out" is correctly created and filled with the output of "ls -la" command"
file = open(filename, "r")
for line in file:
print(line)
file.close()
这个脚本的输出是空的,它不打印任何东西。看不到内容ls.out。
这里有什么不正确的?
回答
Popen 创建一个新进程并启动它但立即返回。所以最终的结果是你已经fork编辑了你的代码并且让两个进程同时运行。您的 Python 代码执行速度比ls. 因此,您需要通过添加调用来等待该过程完成wait():
import subprocess
import os
filename = "ls.out"
ls_command = "ls -la"
file = open(filename, "w")
proc = subprocess.Popen(ls_command, stdout=file, shell=True)
proc.wait()
file.close()
file = open(filename, "r")
for line in file:
print(line)
file.close()