如何在终端上运行Python脚本?

111

我想在终端中运行Python脚本,但我不知道该怎么做。我已经在目录“/User/luca/Documents/python”中有一个名为gameover.py的保存文件。

9个回答

123

您需要在系统上安装Python。然后可以在正确的目录中在终端中运行以下命令:

python gameover.py

1
当我这样做时,我得到了这个:/Library/Frameworks/Python.framework/Versions/2.5/Resources/Python.app/Contents/MacOS/Python: 无法打开文件'gameover.py': [Errno 2] 没有那个文件或目录。 - SnakeEyes
4
首先,您应该更改目录(Shell 命令):cd /User/luca/Documents/python。 - Nikita Kozlov

28

你可以使用以下方式执行你的文件:

python /Users/luca/Documents/python/gameover.py

您也可以通过移动到要运行的文件的路径并输入以下命令来运行该文件:

python gameover.py

23

这取决于您的系统上安装的Python版本。请参见以下说明。

如果您有Python 2.*版本,则必须运行此命令

python gameover.py

但如果您使用的是Python 3.*版本,则需要运行此命令

python3 gameover.py

因为MAC上Python版本为3.*,如果你运行"python gameover.py"会得到命令未找到的错误。


5

首先,您需要安装Python。Mac预装了Python 2.7版本,如果您需要安装Python 3,请参考此教程:http://docs.python-guide.org/en/latest/starting/install3/osx/

在安装完成后,您可以将以下代码复制并粘贴以运行程序:

python /Users/luca/Documents/python/gameover.py

或者您可以使用cd命令进入文件所在的目录。当您进入该目录后,您可以使用python YourFile.py来运行文件。


5

假设你的脚本名为my_script.py,并且你已将其放在下载文件夹中。

有许多安装Python的方法,但Homebrew是最简单的。

  1. Open Terminal.app (press ⌘+Space and type "Terminal" and press the Enter key)

  2. Install Homebrew (by pasting the following text into Terminal.app and pressing the Enter key)

    /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
    
  3. Install Python using Homebrew

    brew install python
    
  4. cd into the directory that contains your Python script (as an example I'm using the Downloads (Downloads) folder in your home (~) folder):

    cd ~/Downloads
    
  5. Run the script using the python3 executable

    python3 my_script.py
    
您可以跳过第三步,而是给python3提供一个绝对路径
python3 ~/Downloads/my_script.py

不需要打出整个路径(~/Downloads/my_script.py),你可以在Finder.app中找到.py文件,然后将其拖放到Terminal.app窗口中,这样它就会为你打出绝对路径。

如果文件名中有空格或其他特殊符号,你需要用引号将文件名括起来:

python3 "~/Downloads/some directory with spaces/and a filename with a | character.py"

4

首先,您需要移动到要执行的文件所在位置,在终端中:

cd ~/Documents/python

现在,您应该能够执行您的文件:
python gameover.py

4
如果你在使用Ubuntu系统,有时候需要以sudo身份运行:
对于Python2:
sudo python gameover.py

对于 Python3:

sudo python3 gameover.py

1
请解释一下为什么需要以sudo身份运行Python代码?在我看来,如果你不小心或者不知道自己在做什么的话,这可能是危险的。 - Valentyn

2

打开您保存Python程序的目录

cd desktop/home/file.....

输入命令

python3 filename.py

1

适用于OS Monterrey

/usr/local/bin/python3 

或者在您的Mac上打开搜索栏,输入python,一个窗口将会打开,并显示目录的地址,将目录复制并粘贴到终端中即可。
祝您使用愉快!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接