如何在macOS上安装Python3并设置本地编程环境
介绍
Python是一种多功能编程语言,可用于许多不同的编程项目。1991年首次出版,其名称灵感来自英国喜剧组织Monty Python,开发团队希望使Python成为一种有趣的语言。易于设置,并以相对简单的方式编写并立即反馈错误,Python是初学者和经验丰富的开发人员的绝佳选择。Python 3是该语言的最新版本,被认为是Python的未来。
本教程将指导您在本地macOS机器上安装Python 3并通过命令行设置编程环境。
准备
您将需要一台连接到互联网的具有管理访问权限的macOS计算机。
第1步 - 打开终端
我们将完成大部分安装并在命令行上进行设置,这是一种与计算机交互的非图形方式。也就是说,您不是点击按钮,而是键入文本并通过文本从计算机接收反馈。命令行(也称为shell)可以帮助您修改和自动化您每天在计算机上执行的许多任务,并且是软件开发人员必不可少的工具。
macOS终端是一个可用于访问命令行界面的应用程序。与任何其他应用程序一样,您可以通过进入Finder,导航到Applications文件夹,然后进入Utilities文件夹找到它。从这里,像任何其他应用程序一样双击终端以打开它。或者,您可以通过按住command
和spacebar
键来使用Spotlight,通过在显示的框中键入它来查找终端。
还有许多终端命令需要学习,可以让你做更强大的事情。
第2步 - 安装Xcode
Xcode是一个集成开发环境(IDE),由macOS的软件开发工具组成。您可能已经安装了Xcode。要检查,请在“终端”窗口中键入:
xcode-select -p
如果您收到以下输出,则安装Xcode:
/Library/Developer/CommandLineTools
如果收到错误,则在Web浏览器中从App Store安装Xcode并接受默认选项。
安装Xcode后,返回终端窗口。接下来,您需要安装Xcode的单独命令行工具应用程序,您可以通过键入以下内容来执行此操作:
xcode-select --install
此时,Xcode及其Command Line Tools应用程序已完全安装,我们已准备好安装软件包管理器Homebrew。
第3步 - 安装和设置Homebrew
虽然OS X终端具有许多Linux终端和其他Unix系统的功能,但它没有附带一个好的包管理器。一个包管理器是一种软件工具,工作自动化的安装过程,其中包括最初的软件安装,升级和软件的配置和删除软件需要的集合。它们将安装保存在中央位置,并且可以以常用格式维护系统上的所有软件包。Homebrew为OS X提供免费的开源软件包管理系统,简化了OS X上软件的安装。
要安装Homebrew,请在终端窗口中键入:
/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
Homebrew是用Ruby制作的,所以它将修改你的计算机的Ruby路径。该curl
命令从指定的URL中提取脚本。此脚本将解释它将执行的操作,然后暂停该过程以提示您确认。这为您提供了有关脚本将对您的系统执行的操作的大量反馈,并为您提供验证过程的机会。
如果您需要输入密码,请注意您的按键不会显示在终端窗口中,但会记录下来,只需在输入密码后按return
键即可。否则,只要提示您确认安装,请按y
字母表达“是”。
让我们来看看与curl
命令相关的标志:
- -
f
或--fail
标志告诉终端窗口不提供服务器错误的HTML文档输出。 - 该
-s
或--silent
标志静音curl
,使其不显示进度表,并与-S
或--show-error
标志合并,如果它失败的话,它将确保curl
显示错误消息,。 - 该
-L
或--location
标志将告诉curl
来重做请求到一个新的地方,如果服务器报告所请求的页面已移动到不同的位置。
安装过程完成后,我们将Homebrew目录放在PATH
环境变量的顶部。这将确保将通过Mac OS X可能自动选择的工具调用Homebrew安装,这些工具可能与我们正在创建的开发环境背道而驰。
您应该使用nano
命令创建或打开命令行文本编辑器nano的~/.bash_profile
文件:
nano ~/.bash_profile
在终端窗口中打开文件后,输入以下内容:
export PATH=/usr/local/bin:$PATH
要保存更改,请按住control
键和字母o
,然后在提示时按return
键。现在,您可以通过按住control
键和字母x
来退出nano 。
要激活这些更改,请在“终端”窗口中键入:
source ~/.bash_profile
完成此操作后,您对PATH
环境变量所做的更改将生效。
我们可以通过键入以下命令确保已成功安装Homebrew:
brew doctor
如果此时不需要更新,则终端输出将显示为:
Your system is ready to brew.
否则,您可能会收到类似brew update
的警告以运行另一个命令来确保您的Homebrew安装是最新的。
一旦Homebrew准备就绪,您就可以安装Python 3。
第4步 - 安装Python 3
您可以使用Homebrew搜索您可以使用brew search
命令安装的所有内容,但是为了向我们提供更短的列表,让我们只搜索可用的Python相关软件包或模块:
brew search python
终端将输出您可以安装的列表,如下所示:
app-engine-python micropython python3 boost-python python wxpython gst-python python-markdown zpython homebrew/apache/mod_python homebrew/versions/gst-python010 homebrew/python/python-dbus Caskroom/cask/kk7ds-python-runtime homebrew/python/vpython Caskroom/cask/mysql-connector-python
Python 3将成为列表中的项目之一。让我们继续安装它:
brew install python3
终端窗口将为您提供有关Python 3安装过程的反馈,可能需要几分钟才能完成安装。
与Python 3一起,Homebrew将安装pip,setuptools和wheel。
作为与Python一起使用的工具,我们将使用pip来安装和管理我们可能希望在我们的开发项目中使用的编程包。您可以键入以下命令安装Python包:
pip3 install package_name
在这里,package_name
可以引用任何Python包或库,例如用于Web开发的Django或用于科学计算的NumPy。因此,如果您想安装NumPy,可以使用pip3 install numpy
命令执行此操作。
setuptools有助于打包Python项目,wheel是Python 的内置包格式,可以通过减少编译所需的次数来加速软件生产。
要检查您安装的Python 3的版本,可以键入:
python3 --version
这将输出当前安装的特定版本的Python,默认情况下,它将是可用的最新Python 3版本。
要更新您的Python 3版本,您可以先更新Homebrew然后更新Python:
brew update
brew upgrade python3
确保您的Python版本是最新的是一种很好的做法。
第5步 - 创建虚拟环境
现在我们已经安装了Xcode,Homebrew和Python,我们可以继续创建我们的编程环境。
虚拟环境使您可以在计算机上为Python项目创建一个隔离空间,确保每个项目都有自己的一组依赖项,这些依赖项不会破坏任何其他项目。
设置编程环境使我们能够更好地控制Python项目以及如何处理不同版本的包。在使用第三方软件包时,这一点尤为重要。
您可以根据需要设置尽可能多的Python编程环境。每个环境基本上都是计算机中的一个目录或文件夹,其中包含一些脚本以使其充当环境。
选择您希望将Python编程环境放在哪个目录中,或者使用mkdir
创建新目录:
mkdir Environments
cd Environments
进入您希望环境生存的目录后,可以通过运行以下命令来创建环境:
python3.6 -m venv my_env
本质上,此命令创建一个包含几个项目的新目录(在本例中称为my_env):
pyvenv.cfg
文件指向您用于运行该命令的Python安装。lib
子目录包含Python版本的副本,并且其中包含一个site-packages
子目录,该子目录以空白开头,但最终将保存您安装的相关第三方模块。include
子目录编译软件包。bin
子目录包含Python二进制文件的副本以及用于设置环境的activate shell脚本。
这些文件一起用于确保您的项目与本地计算机的更广泛的上下文隔离,以便系统文件和项目文件不会混合。这是版本控制的良好实践,并确保您的每个项目都可以访问所需的特定软件包。
要使用此环境,您需要激活它,您可以通过键入以下调用activate脚本的命令来执行此操作:
source my_env/bin/activate
您的提示现在将以您的环境名称作为前缀,在这种情况下,它被称为my_env:
(my_env) Sammys-MBP:~ sammy$
这个前缀让我们知道环境my_env当前是活动的,这意味着当我们在这里创建程序时,它们将只使用这个特定环境的设置和包。
注意:在虚拟环境中,您可以使用命令python
代替python3
,如果您喜欢的话也可以使用pip
代替pip3
。如果在环境之外的机器上使用Python 3,则需要独占使用python3
和pip3
命令,因为python
和pip
将调用早期版本的Python。
执行这些步骤后,您的虚拟环境即可使用。
第6步 - 创建一个简单的程序
现在我们已经设置了虚拟环境,让我们创建一个简单的“Hello,World!”程序。这将确保我们的环境正常运行,并让我们有机会更熟悉Python,如果我们还没有。
为此,我们将打开命令行文本编辑器(如nano)并创建一个新文件:
nano hello.py
一旦文本文件在终端打开,我们将输入我们的程序:
print("Hello, World!")
通过键入control
和x
键退出nano ,并在提示保存文件时按y
。
一旦退出nano并返回shell,让我们运行程序:
python hello.py
您刚刚创建的hello.py程序应该导致Terminal生成以下输出:
Hello, World!
要离开环境,只需键入命令deactivate
即可返回原始目录。
结论
恭喜!此时,您在本地Mac OS X机器上设置了Python 3编程环境,可以开始编码项目!
要在另一台计算机上设置Python 3,请前往腾讯云+社区了解更多。
使用本地计算机为软件开发做好准备后,您可以通过Python 数据类型等文章继续学习有关Python编码的更多信息。
参考文献:《How To Install Python 3 and Set Up a Local Programming Environment on macOS》
How To Install Python 3 and Set Up a Local Programming Environment on macOS
Published on September 1, 2016 · Updated on July 12, 2022
Developer and author at DigitalOcean.
Introduction
Python is a versatile programming language that can be used for many different programming projects. First published in 1991 with a name inspired by the British comedy group Monty Python, the development team wanted to make Python a language that was fun to use. Easy to set up, and written in a relatively straightforward style with immediate feedback on errors, Python is a great choice for beginners and experienced developers alike. Python 3 is the most current version of the language and is considered to be the future of Python.
This tutorial will guide you through installing Python 3 on your local macOS machine and setting up a programming environment via the command line.
Prerequisites
You will need a macOS computer with administrative access that is connected to the internet.
Step 1 — Opening Terminal
We’ll be completing most of our installation and set up on the command line, which is a non-graphical way to interact with your computer. That is, instead of clicking on buttons, you’ll be typing in text and receiving feedback from your computer through text as well. The command line, also known as a shell, can help you modify and automate many of the tasks you do on a computer every day, and is an essential tool for software developers.
The macOS Terminal is an application you can use to access the command line interface. Like any other application, you can find it by going into Finder, navigating to the Applications folder, and then into the Utilities folder. From here, double-click the Terminal like any other application to open it up. Alternatively, you can use Spotlight by holding down the command
and spacebar
keys to find Terminal by typing it out in the box that appears.
There are many more Terminal commands to learn that can enable you to do more powerful things. The article “[An Introduction to the Linux Terminal] (An Introduction to the Linux Terminal | DigitalOcean)” can get you better oriented with the Linux Terminal, which is similar to the macOS Terminal.
Step 2 — Installing Xcode
Xcode is an integrated development environment (IDE) that is comprised of software development tools for macOS. You may have Xcode installed already. To check, in your Terminal window, type:
xcode-select -p
Copy
If you receive the following output, then Xcode is installed:
Output
/Library/Developer/CommandLineTools
If you received an error, then in your web browser install [Xcode from the App Store] (Xcode on the Mac App Store) and accept the default options.
Once Xcode is installed, return to your Terminal window. Next, you’ll need to install Xcode’s separate Command Line Tools app, which you can do by typing:
xcode-select --install
Copy
At this point, Xcode and its Command Line Tools app are fully installed, and we are ready to install the package manager Homebrew.
Step 3 — Installing and Setting Up Homebrew
While the OS X Terminal has a lot of the functionality of Linux Terminals and other Unix systems, it does not ship with a good package manager. A package manager is a collection of software tools that work to automate installation processes that include initial software installation, upgrading and configuring of software, and removing software as needed. They keep installations in a central location and can maintain all software packages on the system in formats that are commonly used. Homebrew provides OS X with a free and open source software package managing system that simplifies the installation of software on OS X.
To install Homebrew, type this into your Terminal window:
/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
Copy
Homebrew is made with Ruby, so it will be modifying your computer’s Ruby path. The curl
command pulls a script from the specified URL. This script will explain what it will do and then pauses the process to prompt you to confirm. This provides you with a lot of feedback on what the script is going to be doing to your system and gives you the opportunity to verify the process.
If you need to enter your password note that your keystrokes will not display in the Terminal window but they will be recorded, simply press the return
key once you’ve entered your password. Otherwise press the letter y
for “yes” whenever you are prompted to confirm the installation.
Let’s walk through the flags that are associated with the curl
command:
- The -
f
or--fail
flag tells the Terminal window to give no HTML document output on server errors. - The
-s
or--silent
flag mutescurl
so that it does not show the progress meter, and combined with the-S
or--show-error
flag it will ensure thatcurl
shows an error message if it fails. - The
-L
or--location
flag will tellcurl
to redo the request to a new place if the server reports that the requested page has moved to a different location.
Once the installation process is complete, we’ll put the Homebrew directory at the top of the PATH
environment variable. This will ensure that Homebrew installations will be called over the tools that Mac OS X may select automatically that could run counter to the development environment we’re creating.
You should create or open the ~/.bash_profile
file with the command-line text editor nano using the nano
command:
nano ~/.bash_profile
Copy
Once the file opens up in the Terminal window, write the following:
export PATH=/usr/local/bin:$PATH
To save your changes, hold down the control
key and the letter o
, and when prompted press the return
key. Now you can exit nano by holding the control
key and the letter x
.
For these changes to activate, in the Terminal window, type:
source ~/.bash_profile
Copy
Once you have done this, the changes you have made to the PATH
environment variable will be effective.
We can make sure that Homebrew was successfully installed by typing:
brew doctor
Copy
If no updates are required at this time, the Terminal output will read:
Output
Your system is ready to brew.
Otherwise, you may get a warning to run another command such as brew update
to ensure that your installation of Homebrew is up to date.
Once Homebrew is ready, you can install Python 3.
Step 4 — Installing Python 3
You can use Homebrew to search for everything you can install with the brew search
command, but to provide us with a shorter list, let’s instead search for just the available Python-related packages or modules:
brew search python
Copy
The Terminal will output a list of what you can install, like this:
Output
app-engine-python micropython python3 boost-python python wxpython gst-python python-markdown zpython homebrew/apache/mod_python homebrew/versions/gst-python010 homebrew/python/python-dbus Caskroom/cask/kk7ds-python-runtime homebrew/python/vpython Caskroom/cask/mysql-connector-python
Python 3 will be among the items on the list. Let’s go ahead and install it:
brew install python3
Copy
The Terminal window will give you feedback regarding the installation process of Python 3, it may take a few minutes before installation is complete.
Along with Python 3, Homebrew will install pip, setuptools and wheel.
A tool for use with Python, we will use pip to install and manage programming packages we may want to use in our development projects. You can install Python packages by typing:
pip3 install package_name
Copy
Here, package_name
can refer to any Python package or library, such as Django for web development or NumPy for scientific computing. So if you would like to install NumPy, you can do so with the command pip3 install numpy
.
setuptools facilitates packaging Python projects, and wheel is a built-package format for Python that can speed up your software production by reducing the number of times you need to compile.
To check the version of Python 3 that you installed, you can type:
python3 --version
Copy
This will output the specific version of Python that is currently installed, which will by default be the most up-to-date stable version of Python 3 that is available.
To update your version of Python 3, you can first update Homebrew and then update Python:
brew update brew upgrade python3
Copy
It is good practice to ensure that your version of Python is up-to-date.
Step 5 — Creating a Virtual Environment
Now that we have Xcode, Homebrew, and Python installed, we can go on to create our programming environment.
Virtual environments enable you to have an isolated space on your computer for Python projects, ensuring that each of your projects can have its own set of dependencies that won’t disrupt any of your other projects.
Setting up a programming environment provides us with greater control over our Python projects and over how different versions of packages are handled. This is especially important when working with third-party packages.
You can set up as many Python programming environments as you would like. Each environment is basically a directory or folder in your computer that has a few scripts in it to make it act as an environment.
Choose which directory you would like to put your Python programming environments in, or create a new directory with mkdir
, as in:
mkdir Environments
cd Environments
Copy
Once you are in the directory where you would like the environments to live, you can create an environment by running the following command:
python3.7 -m venv my_env
Copy
Essentially, this command creates a new directory (in this case called my_env) that contains a few items:
- The
pyvenv.cfg
file points to the Python installation that you used to run the command. - The
lib
subdirectory contains a copy of the Python version and has asite-packages
subdirectory inside it that starts out empty but will eventually hold the relevant third-party modules that you install. - The
include
subdirectory compiles packages. - The
bin
subdirectory has a copy of the Python binary along with the activate shell script that is used to set up the environment.
Together, these files work to make sure that your projects are isolated from the broader context of your local machine, so that system files and project files don’t mix. This is good practice for version control and to ensure that each of your projects has access to the particular packages that it needs.
To use this environment, you need to activate it, which you can do by typing the following command that calls the activate script:
source my_env/bin/activate
Copy
Your prompt will now be prefixed with the name of your environment, in this case it is called my_env:
Copy
This prefix lets us know that the environment my_env is currently active, meaning that when we create programs here they will use only this particular environment’s settings and packages.
Note: Within the virtual environment, you can use the command python
instead of python3
, and pip
instead of pip3
if you would prefer. If you use Python 3 on your machine outside of an environment, you’ll need to use the python3
and pip3
commands exclusively, as python
and pip
will call an earlier version of Python.
After following these steps, your virtual environment is ready to use.
Step 6 — Creating a Sample Program
Now that we have our virtual environment set up, let’s create a traditional “Hello, World!” program. This will make sure that our environment is working and gives us the opportunity to become more familiar with Python if we aren’t already.
To do this, we’ll open up a command-line text editor such as nano and create a new file:
nano hello.py
Copy
Once the text file opens up in Terminal we’ll type out our program:
print("Hello, World!")
Copy
Exit nano by typing the control
and x
keys, and when prompted to save the file press y
.
Once you exit out of nano and return to your shell, let’s run the program:
python3 hello.py
Copy
The hello.py program that you just created should cause Terminal to produce the following output:
Output
Hello, World!
To leave the environment, simply type the command deactivate
and you’ll return to your original directory.
Conclusion
Congratulations! At this point you have a Python 3 programming environment set up on your local Mac OS X machine and can begin a coding project!
To set up Python 3 on another computer, follow the local programming environment guides for Ubuntu 16.04, Debian 8, CentOS 7, or Windows 10. You can also read about installing Python and setting up a programming environment on an Ubuntu 16.04 server, which is especially useful when working on development teams.
With your local machine ready for software development, you can continue to learn more about coding in Python by following “Understanding Data Types in Python 3” and “How To Use Variables in Python 3”.