簡體   English   中英

在python中發送命令行命令並打印stdout和stderr的最簡單,最可靠的方法是什么?

[英]What is the simplest and most reliable way to send a command-line command in python, and print the stdout and stderr?

要詳細說明我在做什么:

我想為我的Raspberry Pi創建一個基於Web的CLI。 我想拿一個websocket並將其連接到該Raspberry Pi腳本,以便我在網頁中鍵入的文本將直接輸入到raspberry pi的CLI中,並且響應將在網頁上返回給我。

我的第一個目標是創建python腳本,該腳本可以正確地將用戶輸入的命令發送到CLI,並返回CLI中的所有響應。

如果只需要返回值,則可以使用os.system ,但不會獲得stdout和stderr的輸出。 因此,您可能必須使用子流程模塊,該模塊要求您首先將輸入文本分為命令和參數。

聽起來您正在尋找標准庫中的python 子進程模塊。 這將允許您從python腳本與CLI進行交互。

subprocess模塊將為您執行此操作,但有一些怪癖。 您可以將文件對象傳遞給各種調用以綁定到stderrstdout ,但是它們必須是真實的文件對象。 StringIO不會削減它。

下面使用check_output()因為它為我們獲取了stdout並節省了打開文件的時間。 我敢肯定,這樣做有更好的方法。

from tempfile import TemporaryFile
from subprocess import check_output, CalledProcessError


def shell(command):
    stdout = None

    with TemporaryFile('rw') as fh:
        try:
            stdout = check_output(command, shell=True, stderr=fh)

        except CalledProcessError:
            pass

        # Rewind the file handle to read from the beginning
        fh.seek(0)
        stderr = fh.read()

    return stdout, stderr


print shell("echo hello")[0]
    # hello
print shell("not_a_shell_command")[1]
    # /bin/sh: 1: not_a_shell_command: not found

正如其他海報中提到的那樣,您應該真正清理輸入內容以防止安全漏洞(並丟棄shell=true )。 不過,老實說,您的項目聽起來像是您有意為自己構建一個遠程執行漏洞利用程序,所以可能沒關系。

暫無
暫無

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

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