我想在终端中运行Python脚本,但我不知道该怎么做。我已经在目录“/User/luca/Documents/python”中有一个名为gameover.py的保存文件。
您需要在系统上安装Python。然后可以在正确的目录中在终端中运行以下命令:
python gameover.py
你可以使用以下方式执行你的文件:
python /Users/luca/Documents/python/gameover.py
您也可以通过移动到要运行的文件的路径并输入以下命令来运行该文件:
python gameover.py
这取决于您的系统上安装的Python版本。请参见以下说明。
如果您有Python 2.*版本,则必须运行此命令
python gameover.py
但如果您使用的是Python 3.*版本,则需要运行此命令
python3 gameover.py
因为MAC上Python版本为3.*,如果你运行"python gameover.py"会得到命令未找到的错误。
首先,您需要安装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
来运行文件。
假设你的脚本名为my_script.py
,并且你已将其放在下载文件夹中。
有许多安装Python的方法,但Homebrew是最简单的。
Open Terminal.app (press ⌘+Space and type "Terminal" and press the Enter key)
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)"
Install Python using Homebrew
brew install python
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
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"
首先,您需要移动到要执行的文件所在位置,在终端中:
cd ~/Documents/python
python gameover.py
sudo python gameover.py
对于 Python3:
sudo python3 gameover.py
打开您保存Python程序的目录
cd desktop/home/file.....
输入命令
python3 filename.py
适用于OS Monterrey
/usr/local/bin/python3
或者在您的Mac上打开搜索栏,输入python,一个窗口将会打开,并显示目录的地址,将目录复制并粘贴到终端中即可。
祝您使用愉快!