【问题标题】:How to open and print the contents of a file line by line using subprocess?如何使用子进程逐行打开和打印文件的内容?
【发布时间】:2020-07-17 20:09:43
【问题描述】:

我正在尝试编写一个 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)

这是我基本上打开文件,将其输出保存到变量并打印它的天真的方法。但是,当我打印“需要”时,这确实会弄乱格式。有没有办法简单地使用子进程并逐行读取文件?我必须通过 SSH 连接到该地址才能转储文件,否则将无法检测到该文件,这就是为什么我不只是这样做

            f = open(temp, "r")
            file_contents = f.read()
            print (file_contents)
            f.close()

任何帮助将不胜感激:)

【问题讨论】:

  • 打印need时格式“乱七八糟”是怎么回事?
  • 由于某种原因,行没有被分开。
  • 这很奇怪。也许远程主机正在使用一些晦涩的行尾协议。将print(need) 更改为print(repr(need)) 可能是值得的,这样您就可以看到正在发送的内容。

标签: python file parsing subprocess


【解决方案1】:

您不需要使用 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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-01
    • 2022-07-06
    • 2023-04-07
    • 1970-01-01
    • 2021-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多