[英]run python script directly from command line
#!/usr/bin/env python
I put that at the top of a script.我把它放在脚本的顶部。 I've seen that should make the script runnable from the command line without the need for
python programname.py
.我已经看到应该使脚本可以从命令行运行,而无需
python programname.py
。 Unless I'm misunderstanding I should be able to use programname.py
as long as I have the above line at the top of the script.除非我有误解,否则只要我在脚本顶部有上述行,我就应该能够使用
programname.py
。 Is this correct?这个对吗?
It isn't working for me I just get an error indicating that I would have to use python
at the beginning of the 'call'.它对我不起作用,我只是收到一个错误,表明我必须在“呼叫”开始时使用
python
。
You can pretty much universally run without the shebang ( #!
) with 你可以在没有shebang(
#!
)的情况下普遍运行
python myscript.py
Or nearly equivalently (it places the current directory on your path and executes the module named myscript
) (preferably do this!) : 或几乎相当(它将当前目录放在您的路径上并执行名为
myscript
的模块) (最好这样做!) :
python -m myscript
from the command line, as long as you have Python installed and on your path environment variable (ie set to run with python
, which, if installed, would typically be the case). 从命令行,只要你安装了Python并在你的路径环境变量上(即设置为使用
python
运行,如果安装了,通常就是这种情况)。
#!
) are a Unix thing. #!
)是一个Unix的东西。 The shebang, as you're using it, is typically for running on a Unix platform (typically Apple or Linux). 正如您所使用的那样,shebang通常用于在Unix平台(通常是Apple或Linux)上运行。 Windows would typically require cygwin to use the shebang.
Windows通常需要cygwin才能使用shebang。
You can usually default to whatever python is available on your system path with: 您通常可以默认使用系统路径上可用的任何python:
#!/usr/bin/env python
Assuming you're on a Unix, you might try other locations for your python setup, like: 假设您使用的是Unix,可以尝试其他位置进行python设置,例如:
#!/usr/bin/python
You can see what python you're currently using by using the unix which
command, so if you want to see where your python is coming from, use this command: 您可以使用unix
which
命令查看当前正在使用的python,因此如果您想查看python的来源,请使用以下命令:
which python
or on Windows (cygwin probably can run the shebang): 或者在Windows上(cygwin可能会运行shebang):
where python
On Linux/Unix, you'll need execution perms to run the file as well, in that manner. 在Linux / Unix上,你也需要执行perms来以这种方式运行文件。 Use chmod
使用chmod
chmod +x myscript.py
(chmod also may apply to Cygwin in Windows) (chmod也可能适用于Windows中的Cygwin)
If you're not running as root, you may require sudo
, and that would be 如果你不是以root身份运行,那么你可能需要
sudo
,那就是
sudo chmod +x myscript.py
And then attempt to run (within the same directory) with 然后尝试运行(在同一目录中)
./myscript.py
make the file executable 使文件可执行
sudo chmod +x /path/to/file.py
and then from the same directory as file.py: 然后从与file.py相同的目录:
./file.py
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.