簡體   English   中英

如何在python中通過stdin發送多個字符串

[英]How to send multiple string by stdin in python

我通過父代碼將字符串Router_Status [Router] ='ON'發送到新進程

proc[Router] = subprocess.Popen([sys.executable, os.getcwd() + '/'
                                + Router + '.py', Router,
                                json.dumps(graph),
                                json.dumps(As_numbers_dict)],
                                shell=False, stderr=True,
                                stdin=subprocess.PIPE,
                                stdout=subprocess.PIPE)

proc[Router].stdin.write(bytes(Router_Status[Router],
                               encoding='utf-8') + b'\n')

而子進程是

Router_Status[Router]=sys.stdin.readline().strip()
path = os.path.expanduser('~' + '/BGP_Routers/' + Router)
with open(path + '/Router_Status.txt', 'w') as f:
        f.write(Router_Status[Router])

但它不起作用! 然后我通過proc [Router] .stdin.write(bytes(Router_Status [Router],encoding ='utf-8')將第二個字符串Router_Status [Router] ='OFF'傳遞給進程

proc[Router].stdin.flush()

它仍然沒有做任何事情!

好的,所以我不完全熟悉你傳遞給subprocess.Popen()的參數,所以我無法檢查它們是否正確。 但是,我知道有關子進程模塊的一兩件事,有些事情要考慮查看你的代碼:

  • 使用shell=False不需要明確定義,因為它是標准設置(但是,如果你想因為一個原因而明確它,那當然沒關系)。
  • 參數stderr=False不正確。 它必須是None或類似subprocess.PIPE

然后,由於您使用的是Python3.x,因此文檔聲明:

警告 - 使用communic()而不是.stdin.write,.stdout.read或.stderr.read來避免由於任何其他OS管道緩沖區填滿和阻止子進程而導致的死鎖。

所以你最好使用proc[Router].communicate(input="your standard input, meaning your stdin")

它還指出:

Popen.stdin - 如果stdin參數是PIPE,則此屬性是open()返回的可寫流對象。 如果指定了encoding或errors參數或者universal_newlines參數為True,則流是文本流,否則它是字節流。 如果stdin參數不是PIPE,則此屬性為None。

在你的情況下,平均值stdin應該是一個字節流。

總之,我猜你應該做的事情如下:

proc[Router] = subprocess.Popen([sys.executable, os.getcwd() + '/'
                                + Router + '.py', Router,
                                json.dumps(graph),
                                json.dumps(As_numbers_dict)],
                                stderr=subprocess.PIPE,
                                stdin=subprocess.PIPE,
                                stdout=subprocess.PIPE)

proc[Router].stdin.communicate(str(Router_Status[Router]).encode())

我仍然想知道,為什么你包括:

path = os.path.expanduser('~' + '/BGP_Routers/' + Router)
with open(path + '/Router_Status.txt', 'w') as f:
        f.write(Router_Status[Router])

因為它與subprocess.Popen()語句基本無關。 它只是將用戶輸入寫入文本文件,該文件只捕獲最新的輸入btw。 如果您想保存所有用戶輸入,請將'w'更改為'a' (這將使文件處於append-mode而不是write-mode)。

暫無
暫無

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

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