理解python -c||python -m interpreter run scripts

  • 缘起

    refer2中使用到:

    python -c 'import site; print(site.getsitepackages())'
    python3 -c 'import sysconfig; print(sysconfig.get_paths()["purelib"])'
    

    -c -m are both command-line[refer1] options.

    When invoking Python ,you may specify any of these options:

    python [-bBdEhiIOqsSuvVWx?] [-c command | -m module-name | script | - ] [args]
    
  • Using the Python Interpreter

    The Python interpreter is usually installed as /usr/local/bin/python3.9 on those machines where it is avaiable; putting /usr/local/bin in your Unix shell’s search path makes it possible to start it by typing the command:

    python3.9
    

    to the shell.

  • Redirecting the output
    python hello.py > output.txt # rather than to the stdout,known as stram redirection. It will create or replace output.txt
    python hello.py >> output.txt # add the output to the file 
    
  • Using python module -m module
    python -m <module-name>
    python -m hello
    # not
    python -m hello.py
    

    The -m option searches sys.path for the module name and runs its content as _main_

    对于功能单一的代码,就可以用这样的方式,而不用写复杂的argparses

  • Execute the Python statements -c command

    It executes the Python statements given as command.

    Here command may contain multiple statements separated by newlines.

    And leading whitespace is significant.

    If the option is given, the first element of sys.argv will be “-c” and the current directory will be added to the start of sys.path(allowing modules in that directory to be imported as top level modules).

  • import runs the code as its final stop

    It just do the “run” work once, after the first import, successive import executions do nothing.

  • importlib module
  • exec(open('hello.py').read())
  • Stop running

    Control-D Unix;

    Control-Z Windows;

  • 总结

    python -m or python -c both run python scripts using the interpreter.

    关于python -mpython -c的用法,在网上搜索很难发现什么资料,后来才突然意识到,想要学习它们,最好的资料是它们自己的帮助文档:

    python -h
    
  • References

  1. Command line and environment
  2. How do I find the location of my Python site-packages directory?
  3. How to Run Your Python Scripts
  4. Using the Python Interpreter
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值