4. Using Python on a Mac

Autor

Bob Savage <bobsavage@mac.com>

Python on a Mac running macOS is in principle very similar to Python on any other Unix platform, but there are a number of additional features such as the IDE and the Package Manager that are worth pointing out.

4.1. Obtendo e instalando MacPython

macOS since version 10.8 comes with Python 2.7 pre-installed by Apple. If you wish, you are invited to install the most recent version of Python 3 from the Python website (https://www.python.org). A current “universal binary” build of Python, which runs natively on the Mac’s new Intel and legacy PPC CPU’s, is available there.

O que você obtém após a instalação é uma série de coisas:

  • A pasta Python 3.9 na sua pasta Applications. Aqui você encontra o IDLE, o ambiente de desenvolvimento que é parte padrão das distribuições oficiais do Python; e PythonLauncher, que lida com scripts de Python clicando duas vezes no Finder.

  • Um framework /Library/Frameworks/Python.framework, que inclui o executável e as bibliotecas do Python. O instalador adiciona esse local ao seu caminho do console. Para desinstalar o MacPython, você pode simplesmente remover essas três coisas. Um link simbólico para o executável Python é colocado em /usr/local/bin/.

A compilação do Python fornecida pela Apple é instalada em /System/Library/Frameworks/Python.framework e /usr/bin/python, respectivamente. Você nunca deve modificá-las ou excluí-las, pois elas são controladas pela Apple e são usadas por software da Apple ou de terceiros. Lembre-se de que, se você optar por instalar uma versão mais recente do Python a partir do python.org, terá duas instalações Python diferentes, mas funcionais, no seu computador, por isso será importante que seus caminhos e usos sejam consistentes com o que você deseja fazer.

O IDLE inclui um menu de ajuda que permite acessar a documentação do Python. Se você é completamente novo no Python, comece a ler a introdução do tutorial nesse documento.

Se você está familiarizado com o Python em outras plataformas Unix, leia a seção sobre a execução de scripts Python no shell do Unix.

4.1.1. Como executar um script Python

Your best way to get started with Python on macOS is through the IDLE integrated development environment, see section A IDE and use the Help menu when the IDE is running.

If you want to run Python scripts from the Terminal window command line or from the Finder you first need an editor to create your script. macOS comes with a number of standard Unix command line editors, vim and emacs among them. If you want a more Mac-like editor, BBEdit or TextWrangler from Bare Bones Software (see http://www.barebones.com/products/bbedit/index.html) are good choices, as is TextMate (see https://macromates.com/). Other editors include Gvim (http://macvim-dev.github.io/macvim/) and Aquamacs (http://aquamacs.org/).

Para executar seu script a partir da janela do Terminal, você deve se certificar de que /usr/local/bin esteja no seu caminho de pesquisa do shell.

Para executar seu script no Finder, você tem duas opções:

  • Arrastá-lo para o PythonLauncher

  • Selecionar PythonLauncher como aplicação padrão para abrir seu script (ou qualquer script .py) através da janela de Informações do Finder e clique duas vezes nele. PythonLauncher possui várias preferências para controlar como o script é iniciado. Arrastar com opções permite alterar esses itens para uma chamada ou usar o menu Preferências para alterar as coisas globalmente.

4.1.2. Executando scripts como uma GUI

With older versions of Python, there is one macOS quirk that you need to be aware of: programs that talk to the Aqua window manager (in other words, anything that has a GUI) need to be run in a special way. Use pythonw instead of python to start such scripts.

Com o Python 3.9, você pode usar python ou pythonw.

4.1.3. Configuração

Python on macOS honors all standard Unix environment variables such as PYTHONPATH, but setting these variables for programs started from the Finder is non-standard as the Finder does not read your .profile or .cshrc at startup. You need to create a file ~/.MacOSX/environment.plist. See Apple’s Technical Document QA1067 for details.

Para obter mais informações sobre a instalação de pacotes Python no MacPython, consulte a seção Instalando pacotes adicionais ao python.

4.2. A IDE

O MacPython é fornecido com o ambiente de desenvolvimento IDLE padrão. Uma boa introdução ao uso do IDLE pode ser encontrada em http://www.hashcollision.org/hkn/python/idle_intro/index.html.

4.3. Instalando pacotes adicionais ao python

Existem vários métodos para instalar pacotes Python adicionais:

  • Os pacotes podem ser instalados através do modo distutils padrão do Python (python setup.py install).

  • Muitos pacotes também podem ser instalados através da extensão setuptools ou do wrapper pip. Consulte https://pip.pypa.io/.

4.4. Programação de GUI no Mac

Existem várias opções para criar aplicações GUI no Mac com Python.

PyObjC é uma ligação do Python para o framework Objective-C/Cocoa da Apple, que é a base do desenvolvimento mais moderno do Mac. Informações sobre PyObjC estão disponíveis em https://pypi.org/project/pyobjc/.

O kit de ferramentas de GUI padrão do Python é tkinter, baseado no kit de ferramentas plataforma cruzada Tk (https://www.tcl.tk). Uma versão nativa do Aqua do Tk é fornecida com o OS X da Apple, e a versão mais recente pode ser baixada e instalada em https://www.activestate.com; também pode ser construído a partir do código-fonte.

wxPython is another popular cross-platform GUI toolkit that runs natively on macOS. Packages and documentation are available from https://www.wxpython.org.

PyQt is another popular cross-platform GUI toolkit that runs natively on macOS. More information can be found at https://riverbankcomputing.com/software/pyqt/intro.

4.5. Distribuindo aplicações Python no Mac

The standard tool for deploying standalone Python applications on the Mac is py2app. More information on installing and using py2app can be found at https://pypi.org/project/py2app/.

4.6. Outros recursos

A lista de discussão do MacPython é um excelente recurso de suporte para usuários e desenvolvedores de Python no Mac:

https://www.python.org/community/sigs/current/pythonmac-sig/

Outro recurso útil é o wiki do MacPython:

https://wiki.python.org/moin/MacPython