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.systemC system()함수에 위임합니다:

os.system(command)

서브셸에서 명령(문자열)을 실행합니다. 이는 표준 C 함수를 호출하여 구현됩니다.system()

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

Linux에서는 다음과 같이 정의됩니다.

int system(const char *command);

라이브러리 system()함수는 다음과 같이 using fork(2)에 지정된 쉘 명령을 실행하는 하위 프로세스를 생성하는 데 사용됩니다.commandexecl(3)

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

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

RHEL에서는 sh이지만 bashUbuntu에서는 dash.

$_에서는 정의되지 않았 dash으며 bash 기능이므로 불일치가 있습니다.

sudo dpkg-reconfigure dashUbuntu/Debian에서는 대화 상자에서 "아니요"를 사용하고 선택하여 bash-as-sh를 설정할 수 있습니다 .

관련 정보