直接从命令行运行python脚本 [英] run python script directly from command line
问题描述
#!/ usr / bin / env python
我把它放在脚本的顶部。我已经看到应该使脚本可以从命令行运行,而不需要 python programname.py
。除非我有误解,否则我应该能够使用 programname.py
,只要我在脚本的顶部有上面的那一行。它是否正确?
对我来说不行,我只是得到一个错误,指出我将不得不使用 python
Python脚本的普遍运行
你可以在没有shebang(#!
)几乎普遍运行
python myscript.py
或几乎等同(它将当前目录放在您的路径上并执行
只要你有Python,就可以从命令行中的$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $安装和您的路径环境变量(即设置为运行与python
,如果安装,通常情况下)。
Shebangs(
#!
)是一个Unix的东西。
使用它,通常用于运行在Unix平台上(通常是Apple或Linux)。 Windows通常会要求cygwin使用shebang。
您通常可以默认使用系统路径上可用的任何python:
#!/ usr / bin / env python
假设你在一个Unix上,你可以尝试Python的其他位置,如:
#!/ usr / bin / python
通过
混合
您可以通过使用unix 命令来查看当前正在使用的python,因此,如果要查看python来自哪里,请使用以下命令:
哪个python
或在Windows上(cygwin可能可以运行shebang):
其中python
在Linux / Unix上,您也需要执行perms来运行该文件。使用chmod
chmod + x myscript.py
(chmod也可能适用于Windows中的Cygwin)
如果您没有以root用户身份运行,则可能需要
sudo
,那将是sudo chmod + x myscript.py
然后尝试运行(在同一目录中)与
./ myscript.py
#!/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
. Unless I'm misunderstanding I should be able to useprogramname.py
as long as I have the above line at the top of the script. 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'.解决方案Universal running of Python scripts
You can pretty much universally run without the shebang (
#!
) withpython myscript.py
Or nearly equivalently (it places the current directory on your path and executes the module named
myscript
) (preferably do this!):python -m myscript
from the command line, as long as you have Python installed and on your path environment variable (i.e. set to run with
python
, which, if installed, would typically be the case).Shebangs (
#!
) are a Unix thing.The shebang, as you're using it, is typically for running on a Unix platform (typically Apple or Linux). Windows would typically require cygwin to use the shebang.
You can usually default to whatever python is available on your system path with:
#!/usr/bin/env python
Assuming you're on a Unix, you might try other locations for your python setup, like:
#!/usr/bin/python
Muddling through
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:which python
or on Windows (cygwin probably can run the shebang):
where python
On Linux/Unix, you'll need execution perms to run the file as well, in that manner. Use chmod
chmod +x myscript.py
(chmod also may apply to Cygwin in Windows)
If you're not running as root, you may require
sudo
, and that would besudo chmod +x myscript.py
And then attempt to run (within the same directory) with
./myscript.py
这篇关于直接从命令行运行python脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!