子进程调用中的意外缩进
Unexpected indent in subprocess call
我的印象是 exit(0)
向 Python 解释器发出信号 return 0 到系统。例如,
from subprocess import check_call
check_call('python3 -c "exit(0)"', shell=True) # returns 0
但是
check_call(['/usr/bin/python3', '-c "exit(0)"'])
returns 1:
>>> check_call(['/usr/bin/python3', '-c "exit(0)"'])
File "<string>", line 1
"exit(0)"
^
IndentationError: unexpected indent
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3.5/subprocess.py", line 581, in check_call
raise CalledProcessError(retcode, cmd)
subprocess.CalledProcessError: Command '['/usr/bin/python3', '-c "exit(0)"']' returned non-zero exit status 1
我不知道哪里有空间偷偷溜进来,这是怎么回事?
看来,如果 -c
标志后面没有另一个参数,则当前参数的其余部分将被解释为 Python 代码:
>> python3 -c 'print("yes")'
yes
>> python3 '-cprint("yes")'
yes
>> python3 '-c print("yes")'
File "<string>", line 1
print("yes")
^
IndentationError: unexpected indent
所以下面两个应该都有效,虽然第一个变体感觉最idiomatic/safe:
check_call(['/usr/bin/python3', '-c', 'exit(0)'])
check_call(['/usr/bin/python3', '-cexit(0)'])
我的印象是 exit(0)
向 Python 解释器发出信号 return 0 到系统。例如,
from subprocess import check_call
check_call('python3 -c "exit(0)"', shell=True) # returns 0
但是
check_call(['/usr/bin/python3', '-c "exit(0)"'])
returns 1:
>>> check_call(['/usr/bin/python3', '-c "exit(0)"'])
File "<string>", line 1
"exit(0)"
^
IndentationError: unexpected indent
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3.5/subprocess.py", line 581, in check_call
raise CalledProcessError(retcode, cmd)
subprocess.CalledProcessError: Command '['/usr/bin/python3', '-c "exit(0)"']' returned non-zero exit status 1
我不知道哪里有空间偷偷溜进来,这是怎么回事?
看来,如果 -c
标志后面没有另一个参数,则当前参数的其余部分将被解释为 Python 代码:
>> python3 -c 'print("yes")'
yes
>> python3 '-cprint("yes")'
yes
>> python3 '-c print("yes")'
File "<string>", line 1
print("yes")
^
IndentationError: unexpected indent
所以下面两个应该都有效,虽然第一个变体感觉最idiomatic/safe:
check_call(['/usr/bin/python3', '-c', 'exit(0)'])
check_call(['/usr/bin/python3', '-cexit(0)'])