简体   繁体   English

从任何地方执行python脚本

[英]Execute python script from everywhere

I would like to add some python script to path. 我想在路径中添加一些python脚本。

I can add bash scripts to folders in my path and then execute them from everywhere. 我可以将bash脚本添加到路径中的文件夹,然后从任何地方执行它们。 When I do so with python script, I can only execute them when I am in the same directory. 当我使用python脚本执行此操作时,只能在同一目录中执行它们。

Per exemple, if I put test and test2.py in the same folder in my path. 例如,如果我将test和test2.py放在路径的同一文件夹中。

This work: 这项工作:

 sh test success hello world 

This doesn't: 这不是:

 python test.2.py python: can't open file 'test2.py': [Errno 2] No such file or directory [Errno 2] No such file or directory 

Assuming the python source file is in a directory that is on your path do the following: 假设python源文件位于路径上的目录中,请执行以下操作:

  1. Add this line to the top of your python file: #!/usr/bin/env python 将此行添加到python文件的顶部: #!/usr/bin/env python
  2. Set your python file to be executable: chmod +x test.2.py 将您的python文件设置为可执行文件: chmod +x test.2.py
  3. Run your python script with: test.2.py 使用以下命令运行python脚本: test.2.py

The python command doesn't search $PATH for scripts, like bash does. python命令不会像bash一样在$PATH搜索脚本。

Make test.2.py executable, and make the first line: 使test.2.py可执行,并使其第一行:

#!/usr/bin/python

Then run it by typing: 然后输入以下内容运行它:

test.2.py

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM