[英]Avoid typing “python” in a terminal to open a .py script?
Whilst running python scripts from my linux terminal, I find myself typing in python myfile.py
way too much. 从我的linux终端运行python脚本时,我发现自己在
python myfile.py
输入的方式太多了。 Is there a way on linux (or windows) to execute a python script by just entering in the name of the script, as is possible with bash/sh? 在Linux(或Windows)上,是否可以通过仅输入脚本名称来执行python脚本,就像使用bash / sh一样? like
./script.py
? 喜欢
./script.py
吗?
At the top of the script, put 在脚本顶部,将
#!/usr/bin/python
or whatever the path to Python is on your computer (the result of which python
on Linux). 或您计算机上的Python路径(在Linux上
which python
的结果)。 This tells the system to run your script using python
. 这告诉系统使用
python
运行脚本。 You'll also need to do chmod +x script.py
for it to work. 您还需要执行
chmod +x script.py
使其正常工作。
Or if you're really lazy, use alias p=python
or something. 或者,如果您真的很懒,请使用
alias p=python
或其他名称。
您将需要chmod 0755 script.py
并且作为脚本的第一行有类似
#!/usr/bin/python
The first line of your Python script should be: Python脚本的第一行应为:
#!/usr/bin/env python
or 要么
#!/usr/bin/env python3
Depending on your version, and if Python 3
is your default or not. 取决于您的版本,以及是否默认使用
Python 3
。
Then, set executable bits at the shell (maybe with sudo
if needed): 然后,在外壳上设置可执行位(如果需要,可以使用
sudo
):
chmod +x my_script_name.py
Note that with the above done, you could rename your Python script 请注意,完成上述操作后,您可以重命名Python脚本
mv my_script_name.py my_script_name
and then execute your Python script just by: 然后只需执行以下操作即可执行Python脚本:
my_script_name
at the shell line. 在壳线处。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.