Bash $_ in Python os.system

Bash $_ in Python os.system

Ich bin gerade auf Folgendes gestoßen

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

für RHEL ergibt dies, was ich erwarte ( $_erweitert sich zu hello):

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

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

aber für Ubuntu (WSL) nicht:

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

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

Warum das?

Antwort1

os.systemdelegiert an die C- system()Funktion:

os.system(command)

Führen Sie den Befehl (einen String) in einer Subshell aus. Dies wird durch den Aufruf der Standard-C-Funktionsystem()

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

was unter Linux wie folgt definiert ist:

int system(const char *command);

Die system()Bibliotheksfunktion verwendet , fork(2)um einen untergeordneten Prozess zu erstellen, der den in command using angegebenen Shell-Befehl execl(3)wie folgt ausführt:

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

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

Unter RHEL shist es bash, unter Ubuntu jedoch dash.

$_ist in nicht definiert dash, es ist eine Bash-Funktionalität, daher die Diskrepanz.

Unter Ubuntu/Debian können Sie Bash als Sh festlegen sudo dpkg-reconfigure dash, indem Sie im Dialogfeld „Nein“ auswählen.

verwandte Informationen