Python os.system 中的 Bash $_

Python os.system 中的 Bash $_

我剛剛遇到以下情況

grep -h ^ID= /etc/*-release
python -c 'from os import system; system("echo hello; echo $_")'

對於 RHEL,這給出了我的期望($_擴展到hello):

$ grep -h ^ID= /etc/*-release
ID="rhel"

$ python -c 'from os import system; system("echo hello; echo $_")'
hello
hello

但對於 Ubuntu (WSL) 則不然:

$ grep -h ^ID= /etc/*-release
ID=ubuntu

$ python -c 'from os import system; system("echo hello; echo $_")'
hello
/usr/bin/python

這是為什麼?

答案1

os.system委託給 Csystem()函數:

os.system(command)

在子 shell 中執行命令(字串)。這是透過呼叫標準C函數來實現的system()

--https://docs.python.org/3/library/os.html#os.system

在 Linux 上定義為:

int system(const char *command);

system()函式庫函數用於建立一個子進程,該子進程執行 使用fork(2)中指定的shell命令,如下所示:commandexecl(3)

execl("/bin/sh", "sh", "-c", command, (char *) NULL);

--https://man7.org/linux/man-pages/man3/system.3.html

在 RHEL 上shbash,但在 Ubuntu 上是dash

$_中未定義dash,它是 bash 功能,因此存在差異。

在 Ubuntu/Debian 上,您可以使用設定 bash-as-shsudo dpkg-reconfigure dash並在對話方塊中選擇「否」。

相關內容