我正在嘗試獲取具有功能的 shell 腳本。而不是像下面那樣嘗試執行它。
source ~/abc.sh; abc arg1 arg2 arg3 arg4a
它在 unix shell 中作業。但是當我試圖從 python 腳本內部執行相同的操作時,它會給出錯誤
def subprocess_cmd(command):
process = subprocess.Popen(command, stdout=subprocess.PIPE, shell=True)
proc_stdout = process.communicate()[0].strip()
return proc_stdout
command = "bash -c source ~/abc.sh; abc arg1 arg2 arg3 arg4a"
out = subprocess_cmd(command)
print(out)
當我在 python 代碼上方執行時,它給出了以下錯誤。
~/abc.sh: line 0: source: filename argument required
source: usage: source filename [arguments]
/bin/sh: line 1: abc: command not found
uj5u.com熱心網友回復:
來自Popen參考:
在 shell=True 的 POSIX 上,shell 默認為 /bin/sh。如果 args 是字串,則該字串指定要通過 shell 執行的命令。這意味著字串的格式必須與在 shell 提示符下鍵入時的格式完全相同。這包括,例如,參考或反斜杠轉義檔案名,其中包含空格。
因此,您傳遞的內容必須作為單個 shell 命令傳遞。
當我在我的 shell 中運行你的單個 POSIX shell 命令時:
$ bash -c source ~/abc.sh; abc arg1 arg2 arg3 arg4a
~/abc.sh: line 0: source: filename argument required
source: usage: source filename [arguments]
bash: abc: command not found
所以這里的python沒有什么特別之處。
您會收到此錯誤,因為此命令相當于:
- 原始 POSIX shell 創建一個新的 bash shell 行程
- 新的 bash shell 源
abc.sh abc現在可以在新的 bash shell 中使用命令- 新的 bash shell 終止
- 新的 bash shell 源
- 原始 POSIX shell 嘗試使用命令
abc - 原始 POSIX shell 終止
你想做的是:
- 原始 POSIX shell 創建一個新的 bash shell 行程
- 新的 bash shell 源
abc.sh abc現在可以在新的 bash shell 中使用命令- 新的 bash shell 嘗試使用命令
abc - 新的 bash shell 終止
- 新的 bash shell 源
- 原始 POSIX shell 終止
因此,您希望在同一個 shell 中使用以下 2 個命令:
source ~/abc.sh
abc arg1 arg2 arg3 arg4a
即:
bash -c 'source ~/abc.sh; abc arg1 arg2 arg3 arg4a'
(注意單引號在哪里。)
在蟒蛇中:
def subprocess_cmd(command):
process = subprocess.Popen(command, stdout=subprocess.PIPE, shell=True)
proc_stdout = process.communicate()[0].strip()
return proc_stdout
command = "bash -c 'source ~/abc.sh; abc arg1 arg2 arg3 arg4a'"
out = subprocess_cmd(command)
print(out)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/486266.html
標籤:python-3.x Unix
上一篇:需要在php中轉換一個值輸出
