[英]How to open and print the contents of a file line by line using subprocess?
I am trying to write a python script which SSHes into a specific address and dumps a text file.我正在尝试编写一个 python 脚本,该脚本通过 SSH 连接到特定地址并转储文本文件。 I am currently having some issues.
我目前遇到一些问题。 Right now, I am doing this:
现在,我正在这样做:
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)
This is the naive approach where I am basically opening the file, saving its output to a variable and printing it.这是我基本上打开文件的天真的方法,将其 output 保存到变量并打印它。 However, this really messes up the format when I print "need".
但是,当我打印“需要”时,这确实会弄乱格式。 Is there any way to simply use subprocess and read the file line by line?
有没有办法简单地使用子进程并逐行读取文件? I have to be SSHed into the address in order to dump the file otherwise the file will not be detected, that is why I am not simply doing
我必须通过 SSH 连接到该地址才能转储文件,否则将无法检测到该文件,这就是为什么我不只是这样做
f = open(temp, "r")
file_contents = f.read()
print (file_contents)
f.close()
Any help would be appreciated:)任何帮助,将不胜感激:)
You don't need to use the subprocess module to print the entire file line by line.您不需要使用 subprocess 模块逐行打印整个文件。 You can use pure python.
您可以使用纯 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.