[英]How to use Python3 Multiprocessing to run Multiple Bash commands
[英]Python3 Run Alias Bash Commands
我有以下代碼非常適合運行ls命令。 我有一個bash別名,我使用alias ll='ls -alFGh'
是否可以讓python運行bash命令,而無需python加載我的bash_alias文件,進行解析,然后實際運行完整命令?
import subprocess
command = "ls" # the shell command
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=None, shell=True)
#Launch the shell command:
output = process.communicate()
print (output[0])
嘗試使用命令=“ ll”,我得到的輸出是:
/bin/sh: ll: command not found
b''
你不能。 當您運行python進程時,它不知道shell別名。 有一些簡單的方法可以將文本從父進程傳遞到子進程(IPC除外),命令行以及通過環境變量(即導出的變量)。 Bash不支持導出別名。
在man bash
頁面上: 幾乎所有目的,別名都被shell函數所取代。
Bash 確實支持導出功能,因此建議您將別名改為一個簡單的功能。 這樣就可以將它從shell導出到python再到shell。 例如:
在外殼中:
ll() { ls -l; }
export -f ll
在python中:
import subprocess
command = "ll" # the shell command
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=None, shell=True)
output = process.communicate()
print(output[0].decode()) # Required if using Python 3
因為您使用的是print()
函數,所以我假設您使用的是.decode()
。在這種情況下,您需要.decode()
,因為會返回一個字節對象。
有了一點黑客,也可以從python創建和導出shell函數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.