簡體   English   中英

如何使用 python 存儲 ubuntu 命令行的 output

[英]how to store the output of ubuntu command line with python

我需要從 Python 腳本運行以下命令行(在 Linux Ubuntu 中)並將結果存儲到變量中

我正在使用以下代碼

dir = 'labels.txt'
for dir in subdirs:
    args = "tail -1 %s"%(dir)
    output = subprocess.check_output(args, shell = True)

我有以下錯誤消息: No such file or directory 我無法弄清楚我做錯了什么。 謝謝你的幫助弗雷德

假設您的意思是subprocess.check_output ,您提供的是相對目錄。 當您使用subprocess.check_output(args, shell=True)運行命令時,它會在您的主目錄 - /home/<username>/中執行。 在那里,它試圖訪問可能不存在的文件dir

如果你嘗試在 shell 中運行相同的命令,你會得到這個 output tail: cannot open '<filename>' for reading: No such file or directory

為了解決這個問題,我建議您在程序中使用絕對路徑。 一個例子如下

import os
import subprocess


directory_to_iterate_through = "/absolute/path/to/directory"

for file in os.listdir(directory_to_iterate_through):
    filepath = os.path.join(directory_to_iterate_through, file)
    args = "tail -1 %s" % (filepath)
    output = subprocess.check_output(args, shell=True)

您可以使用 package command_runner來處理 Unix 和 Windows 平台上的超時、編碼等,並提供退出代碼,以便您知道命令何時失敗。

使用python -m pip install command_runner

與它一起使用

from command_runner import command_runner

all_output = []
file= 'labels.txt'

command = "tail -1 {}".format(file)
exit_code, output = command_runner(command, shell=True, timeout=30)
if exit_code == 0:
   all_output.append(output)

print(all_output)

如果您碰巧需要遍歷給定目錄中的文件,您可以使用ofunctions.file_utils

使用python -m pip install ofunctions.file_utils

像這樣使用它:

from ofunctions.file_utils import get_files_recursive

files = get_files_recursive('/my/folder', ext_include_list='.txt')
for file in files:
    exit_code, output = command_runner('tail -1 {}'.format(file), timeout=30)
    if exit_code == 0:
        print(output)

免責聲明:我是 command_runner package 的作者。

暫無
暫無

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

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