[英]How to read all .txt files in a folder and append its contents into one .txt file, using Python?
[英]How to Pipe shell command into a file and read its contents using python?
我需要執行一個命令,將其輸出保存到文件中,然后讀取文件的內容。 這是我到目前為止:
file_out = open('if','w')
ls = sp.Popen(["ls","-1","/sys/class/net"],stdout=file_out)
file_out.close()
lines = [line.rstrip('\n') for line in open('if')]
print(lines)
確實使用所需內容創建了該文件。 但是當我執行腳本時它只輸出一個[]
原因是子進程ls
不會立即終止。 並且輸出尚未寫入文件。 您可以在讀取文件之前添加ls.wait()
以確保先前的子ls.wait()
已經終止
如果你不想與子retcode = sp.call(["ls","-1","/sys/class/net"],stdout=file_out)
通信,但只是為了執行它,你可以使用retcode = sp.call(["ls","-1","/sys/class/net"],stdout=file_out)
。 這樣,子進程被確保終止並具有返回碼。
如果你只需要輸出文件,你可以使用管道,而不需要在文件中保存輸出。 代碼如下:
ls = sp.Popen(["ls","-1","/sys/class/net"],stdout=sp.PIPE)
lines = [line.rstrip('\n') for line in ls.stdout]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.