簡體   English   中英

使用Python在文件上運行Bash命令

[英]Running a Bash command on files with Python

因此,我正在創建一個腳本,該腳本需要遍歷服務器上的所有文件並運行每個文件名,后跟命令“ ll”,然后獲取該命令的輸出並將其打印到txt文件。

例:

文件夾/文件名.txt

輸出:SoMETHINGSomethingSomethingother-這被發送到output.txt文件

文件夾/子文件夾/文件名3.txt ll

輸出:SoMETHINGSomethingSomethingother-這被發送到output.txt文件

這是我到目前為止的內容:

import os

with open("output.txt", "w") as a:
    for path, subdirs, files in os.walk(r'C:\Users\user\Desktop\Test_Py'):
       for filename in files:
         f = os.path.join(filename)
         m = f + ' ll'

         a.write(str(m) + os.linesep) 

因此,我現在要弄清楚的是如何使用“ ll”命令運行打印出的文件名。 到目前為止,此代碼會將該文件夾及其子文件夾中所有文件的名稱寫入到我的output.txt文件中。

有人有什么想法嗎?

使用os.system()

import os

with open("output.txt", "w") as a:
    for path, subdirs, files in os.walk(r'C:\Users\user\Desktop\Test_Py'):
        for filename in files:
            f = os.path.join(filename)
            m = f + ' ll > output.txt'

            os.system(m)

這只會將標准輸出發送到output.txt文件。 如果您也想將錯誤消息發送到output.txt ,請改用m = f + ' ll > output.txt 2>&1'

說明: os.system(command_string)將在您的系統中執行命令command_string ,就像您在終端中鍵入該命令一樣。 在Windows和Linux中, >運算符是標准的,用於將標准輸出從命令重定向到文件中。 最后的2>&1額外參數是唯一不那么清楚的部分:它將標准錯誤重定向到要輸出標准輸出的位置。 在這里查看有關最后一部分的更多信息。

為了使用“ ll”命令運行文件,您可以使用python中可用的子進程模塊。

您修改后的代碼將是:-

import os
import subprocess
import shlex

with open("output.txt", "w") as a:
    for path, subdirs, files in os.walk(r'C:\Users\user\Desktop\Test_Py'):
       for filename in files:
         f = os.path.join(filename)
         m = f + ' ll'

         cmd_args = shlex.split(m)
         output = subprocess.check_output(cmd_args)
         a.write(output + os.linesep) 

暫無
暫無

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

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