![](/img/trans.png)
[英]How to suppress KeyboardInterrupt output when running a python script on bash?
[英]Python Running Bash Script and Getting Output
我需要運行 bash 腳本並獲取 output。 該腳本有一個帶有變量的循環。
當我僅粘貼 bash 腳本時,它可以在終端屏幕上工作,但是當我使用 Python 使用子進程時它會出錯。 這是代碼:
import subprocess
text1 = """
declare -a StringArray=("a1" "a2" "a3" "a4" "a5" )
for val in ${StringArray[@]}; do
echo $val
done
"""
text_output = (subprocess.check_output(text1, shell=True).strip()).decode()
這是錯誤:
/bin/sh: 2: Syntax error: "(" unexpected
Traceback (most recent call last):
.
.
.
' returned non-zero exit status 2.
解決辦法是什么?
Python3.7, OS: Debian-like Linux, Kernel: 4.19.
錯誤消息指出: /bin/sh...
Python 沒有像您預期的那樣使用bash
。 它使用另一個 shell。 (在我的系統上sh
是dash
。)似乎其他 shell 不支持StringArray=("a1" "a2" "a3" "a4" "a5" )
語法。
您可以嘗試像這樣顯式 select bash
:
subprocess.check_output(text1, shell=True, executable='/bin/bash')
(至少, /bin/bash
在我的系統上工作。)
在這種情況下,您可以使用subprocess.Popen 。
以下是可以幫助您實現上述目標的代碼。 如果您有任何問題,請告訴我。
>>> import subprocess
>>> cmd = 'declare -a StringArray=("a1" "a2" "a3" "a4" "a5" );for val in ${StringArray[@]}; do echo $val; done'
>>> x=subprocess.Popen(cmd,shell=True)
>>> a1
a2
a3
a4
a5
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.