簡體   English   中英

使用python將信息從Linux文件解析到Windows

[英]Parse information from Linux file to Windows using python

我正在嘗試從我的 Linux 環境中解析一些內容,並使用 python 將它們轉儲到我的 Windows 環境中的 excel 文件中。

eg: foo/bar/myfile.txt有一些我想粘貼到我的 windows 環境中的 excel 文件的內容C:foo\\bar\\myfile.txt

我知道如何提取我需要的信息,但我找不到在我的 Windows 操作系統中從 python 中的 linux env 創建文件的解決方案。 任何小信息都有幫助。 謝謝!

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM