이것은 shell globbing 때문에 발생합니다.
기본적으로 *
(ls -al *
)은 사용 가능한 모든 파일과 일치하도록 사용자 쉘에 의해 확장됩니다. shell=True
플래그없이 하위 프로세스를 실행하면 python이 *
을 자체적으로 구문 분석 할 수 없으므로 오류 메시지 ls: cannot access *: No such file or directory
이 표시됩니다.
shell=True
과 함께 명령을 실행하면 python은 실제로 컨트롤을 셸로 전달하므로 올바른 출력이 표시됩니다.
신뢰할 수없는 소스의 비 초기화 된 입력을 통합하는 셸 명령을 실행하면 프로그램이 셸 주입에 취약 해져 임의의 명령을 실행할 수있는 심각한 보안 결함이 발생하므로 신중하게 사용해야합니다 (see warning here).
EDIT 1
쉘 대체 (globbing)와 Popen
이 args
이 subprocess module에서 여기
문제를 일으키는 소비 방식 모두,
class subprocess.Popen
args
은 프로그램 인수 시퀀스이거나 단일 문자열이어야합니다.
If shell is
True , it is recommended to pass
args as a
문자열이 아닌 시퀀스.
는 쉘 대체 (globbing)와
Popen
가
args
는 다음의 출력을 비교, 여기에 문제가 소비되는 방식을 이해합니다.2 예 그 참고 만
ls
이 실행될 때
shell=True
전달 된 입력은 추천
subprocess.Popen(['ls']) #works
subprocess.Popen('ls') #works
subprocess.Popen(['ls', '-al']) #works
subprocess.Popen(['ls -al']) #doesn't work raises OSError since not a single command
subprocess.Popen('ls -al') #doesn't work raises OSError since not a single command
subprocess.Popen(['ls -al'], shell=True) #works since in shell mode
subprocess.Popen('ls -al', shell=True) #works since in shell mode & string is single command
subprocess.Popen(['ls', '-al'], shell=True) #output corresponds to ls only, list passed instead of string, against recommendation
subprocess.Popen(['ls', '-al', '*']) #doesn't work because of shell globbing for *
subprocess.Popen(['ls -al *']) #doesn't work raises OSError since not a single commandfor *
subprocess.Popen('ls -al *') #doesn't work raises OSError since not a single commandvalid arg
subprocess.Popen(['ls', '-al', '*'], shell=True) #output corresponds to ls only, list passed instead of string, against recommendation
subprocess.Popen(['ls -al *'], shell=True) #works
subprocess.Popen('ls -al *', shell=True) #works
번역을위한 thyx – ullix
Popen의 기본값은 shell = False입니다. 따라서 First와 Second는 이런 종류입니다. args에 제공된 인수를 사용합니다. shell = True를 추가하면 args의 첫 번째 인수 만 평가되고 다른 인수는 무시됩니다. 따라서 쉘 명령은 "ls"이며 "ls -al"또는 "ls -al *"가 아닙니다. – ullix
''subprocess.Popen ([ 'ls'])''을 실행하면'subprocess.Popen ([ 'ls', '-al'])'을 실행할 때와 다른 출력을 볼 수 있습니다. 무엇이 작동하지 않는가'subprocess.Popen ([ 'ls', '-al', '*'])''이며 이것은'*'와 관련된 셸 globbing 때문입니다. –