How to execute Python inline from a bash shell

前端 未结 4 518
自闭症患者
自闭症患者 2020-12-24 11:22

Is there a Python argument to execute code from the shell without starting up an interactive interpreter or reading from a file? Something similar to:

perl          


        
相关标签:
4条回答
  • 2020-12-24 11:58

    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
    
    0 讨论(0)
  • 2020-12-24 12:06

    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"
    
    0 讨论(0)
  • 2020-12-24 12:08

    This works:

    python -c 'print("Hi")'
    Hi
    

    From the manual, 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).
    
    0 讨论(0)
  • 2020-12-24 12:17

    Another way is to use the e module

    eg.

    $ python -me 1 + 1
    2
    
    0 讨论(0)
提交回复
热议问题