如何像 Windows 一样使用 Python?

msy*_*msy 1 python

例如,我用 vim 编写了一个 Python 程序,但我如何运行它?当我双击它时,它只显示一个编辑器程序。

tho*_*ter 12

您也可以在 Python 脚本的开头添加一个 shebang 并标记脚本可执行文件,这将使其在正常执行时正确运行。

将此行添加到脚本的顶部:

#!/usr/bin/env python
Run Code Online (Sandbox Code Playgroud)

请注意,由于 Python 2.x 和 3 之间的差异,通常默认为 Python 2.7,因此如果您想要 Python 3,请使用它:

#!/usr/bin/env python3
Run Code Online (Sandbox Code Playgroud)

然后使其可执行。这告诉 shell/GUI 这是一个可以执行的程序。

chmod a+x <name of script>
Run Code Online (Sandbox Code Playgroud)

然后,您可以在不将“python”放在前面的情况下运行它 - 只需<name of script>在提示符下键入或双击或在 GUI 中进行任何操作。

不管你是否这样做是一个品味问题,你可能更喜欢python <name of script>用这种方法或通过这种方法来调用它们。


小智 6

类型

python name-of-python-script-here.py
Run Code Online (Sandbox Code Playgroud)

在终端。确保终端的目录与您在 vim 中创建的文件的位置相同。

  • 它不必是同一个目录,可以指定完整路径(例如`/path/to/script.py`。另外,在开头使用shebang行`#!/usr/bin/env python`脚本应该告诉程序使用 python 来运行它。 (2认同)