簡體   English   中英

通過 python 在 CMD 中運行命令並提取數據

[英]Run command in CMD via python and extract the data

我正在嘗試使用以下代碼運行命令並從 cmd 中提取數據。

包含命令和數據的文件是 txt 文件。 (讓我知道是否應該更改它或使用 excel 如果更好)。

命令看起來像這樣:ping“主機名”,這將導致 cmd 中的一些數據。文件中有這些數據的列表。 所以它會 ping “hostname1” 然后第二行 ping “hostname2”..etc

問題:我希望它單獨運行每一行並從 cmd 中提取結果並將它們存儲在 txt 文件或 excel 文件中 - 理想情況下,我希望所有結果都在同一個文件中。 這可能嗎? 如何?

這是到目前為止的代碼:

root_dir = pathlib.Path(r"path to file here")
cmds_file = root_dir.joinpath('actual file here with commands and data') 
#fail = []
cmds = cmds_file.read_text().splitlines()

try:

for cmd in cmds:
    args = cmd.split() 
    print(f"\nRunning: {args[0]}")
    output = subprocess.check_output(args)


    print(output.decode("utf-8"))
    out_file = root_dir.joinpath(f"Name of file where I want results printed in")
    out_file.write_text(output.decode("utf-8"))
except:
pass

您可以使用一個名為 subprocess 的模塊import subprocess

然后你可以像這樣定義一個變量run = subprocess.run(command_to_execute, capture_output=True)

之后,您可以執行print(run.stdout)以打印命令 output。 如果要將其寫入文件,則可以在運行上述代碼后執行此操作

    with open("PATH TO YOUR FILE", "w") as file:
        file.write(run.stdout)

這應該寫入一個包含命令的 output 的文件之后使用file.close()關閉文件並重新打開它,但在“a”模式下

    with open("PATH TO YOUR FILE", "a") as file:
        file.write(\n + run.stdout)

這應該將 append 數據添加到您的文件中。 請記住關閉文件只是為了獲得最佳實踐,我有一些關於打開文件后不關閉文件的糟糕記憶:D

我的計划很簡單:

  1. 打開輸入,output文件
  2. 逐行讀取輸入文件
  3. 執行命令,將output指向output文件
#!/usr/bin/env python3
import pathlib
import shlex
import subprocess

cmds_file = pathlib.Path(__file__).with_name("cmds.txt")
output_file = pathlib.Path(__file__).with_name("out.txt")
with open(cmds_file, encoding="utf-8") as commands, open(output_file, "w", encoding="utf-8") as output:
    for command in commands:
        command = shlex.split(command)
        output.write(f"\n# {shlex.join(command)}\n")
        output.flush()
        subprocess.run(command, stdout=output, encoding="utf-8")

筆記

  • 使用shlex.split()模擬 bash shell 的命令拆分
  • output.write(...)行是可選的。 你可以刪除它
  • 使用subprocess.run(...)stdout=output會將命令的 output 重定向到文件。 你不必做任何事情。

暫無
暫無

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

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