[英]How to open and print the contents of a file line by line using subprocess?
我正在嘗試編寫一個 python 腳本,該腳本通過 SSH 連接到特定地址並轉儲文本文件。 我目前遇到一些問題。 現在,我正在這樣做:
temp = "cat file.txt"
need = subprocess.Popen("ssh {host} {cmd}".format(host='155.0.1.1', cmd=temp),shell=True,stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
print(need)
這是我基本上打開文件的天真的方法,將其 output 保存到變量並打印它。 但是,當我打印“需要”時,這確實會弄亂格式。 有沒有辦法簡單地使用子進程並逐行讀取文件? 我必須通過 SSH 連接到該地址才能轉儲文件,否則將無法檢測到該文件,這就是為什么我不只是這樣做
f = open(temp, "r")
file_contents = f.read()
print (file_contents)
f.close()
任何幫助,將不勝感激:)
您不需要使用 subprocess 模塊逐行打印整個文件。 您可以使用純 python。
f = open(temp, "r")
file_contents = f.read()
f.close()
# turn the file contents into a list
file_lines = file_contents.split("\n")
# print all the items in the list
for file_line in file_lines:
print(file_line)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.