使用python将信息从Linux文件解析到Windows

时间:2018-11-08 00:38:07

标签: python linux windows parsing

我正在尝试从Linux环境中解析某些内容,并使用python将它们转储到Windows环境中的excel文件中。

eg: foo/bar/myfile.txt在Windows env C:foo\bar\myfile.txt中有一些我想粘贴到excel文件的内容

我知道如何提取所需的信息,但找不到从python的Linux env在Windows操作系统中创建文件的解决方案。任何小信息都会有所帮助。谢谢!

1 个答案:

答案 0 :(得分:0)

import csv
import sys
import subprocess


def env_key_values(host):
    """
    The subprocess.Popen will execute the env command on the remote
    Linux server then return the results.
    """
    ssh = subprocess.Popen(["ssh", host, "env"],
                            shell=False,
                            stdout=subprocess.PIPE,
                            stderr=subprocess.PIPE)
    """
    Read each line from stdout selecting only the varname=value lines.
    Split the line on the '=' character. Use the first element as the 
    Linux environment variable name. Use the remaining elements as the value.
    yield the result.
    """
    for line in ssh.stdout:
        str_line = line[:-1].decode("utf-8")
        if "=" in str_line:
            key_values = str_line.split("=")
            values = "=".join(key_values[1:])
            yield (key_values[0], values)

if __name__ == "__main__":
    """
    Open desired file in write mode, do not enforce EOL character.
    Create a CSV writer specifying the Windows EOL.
    Use \t character for delimiter as the specified file in the question
    used a .txt extension and the user wishes to import the file into Excel.
    """
    with open("file.txt", "w", newline=None) as fout:
        csv_out = csv.writer(fout, delimiter="\t" lineterminator="\r\n")
        csv_out.writerow(["VARNAME","VALUE"])
        for row in env_key_values("ldssbox01"):
            csv_out.writerow(row)