本文介绍了直接从命令行运行python脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

   

 只要你有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 use programname.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 (#!) with

python 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 be

sudo chmod +x myscript.py

And then attempt to run (within the same directory) with

./myscript.py

这篇关于直接从命令行运行python脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 15:45