有没有 Python 参数可以在不启动交互式解释器或读取文件的情况下从 shell 执行代码? 类似于:
perl -e 'print "Hi"'
This works:
python -c 'print("Hi")' Hi
From the manual, man python:
man python
-c command Specify the command to execute (see next section). This termi- nates the option list (following options are passed as arguments to the command).
Another way is to use the e module
e
eg.
$ python -me 1 + 1 2
Another way is to you use bash redirection:
python <<< 'print "Hi"'
And this works also with perl, ruby, and what not.
p.s.
To save quote ' and " for python code, we can build the block with EOF
c=`cat <<EOF print(122) EOF` python -c "$c"
A 'heredoc' can be used to directly feed a script into the python interpreter:
python <<HEREDOC import sys for p in sys.path: print(p) HEREDOC /usr/lib64/python36.zip /usr/lib64/python3.6 /usr/lib64/python3.6/lib-dynload /home/username/.local/lib/python3.6/site-packages /usr/local/lib/python3.6/site-packages /usr/lib64/python3.6/site-packages /usr/lib/python3.6/site-packages