In this post, you’ll learn about how to use environment variables in Python on Windows, macOS, and Linux. Environment variables in Python enable you to write smoother workflows and more secure code.
You’ll learn why environment variables are useful to learn and how to implement them. You’ll learn how to get and set environment variables in Python. You’ll also learn how to implement Python environment variables safely in source control management tools like Github.
By the end of this tutorial, you’ll have learned:
- What environment variables in Python are and why you’ll want to use them
- How to get and set environment variables in Python using Windows, macOS, and Linux
- How to improve the environment variable workflow with the
dotenv
library - How to safely store environment variables when working with source control management tools like Github
Table of Contents
Python environment variables are variables that exist outside of your code and are part of your system’s or current user’s configurations. Why would you want to use environment variables? Environment variables provide the opportunity to make your code:
- More streamlined – by not needing to repeat constants such as API keys across multiple files. Similarly, using environment variables gives you the opportunity to configure your code so it can be tailored to a particular user running your code. For example, if your code is used by multiple people, the user’s path can be accessed from the environment.
- More secure – by not exposing secure keys or user configurations within your code. This allows you to share code that relies on API keys or other secure information without needing to expose that code. This prevents others from ready these secure pieces of information.
Environment variables represent key-value pairs of data that can be accessed by your code. As you’ll learn later, they can be accessed just like any dictionary value.
When To Use Python Environment Variables
Environment variables should be used when a variable changes with the environment (such as when a different user runs the code). This means that the best use cases are when the code would otherwise need manual updating when run in a different environment.
Similarly, environment variables should be used when secure data are implemented in a shared piece of code (or code shared to a source control management tool like Github). This allows you to embed secure information outside the code, while still being able to run your code.
When you first learn about environment variables, it may seem like a good idea to use them for everything. Following the guideline mentioned above sets a good standard for when to use them.
How to Get Environment Variables in Python
Environment variables can be accessed using the os
library. In particular, they’re stored in the environ
attribute. Because the os
package is part of the standard Python library, you don’t need to install anything extra in order to get it to run.
In a later section, you’ll learn how to use the dotenv
module to manage environment variables more easily. For now, let’s take a look at how you can get all environment variables using the os
library.
How to See All Python Environment Variables
The easiest way to get all the environment variables available is to print out the os.environ
attribute. In order to do this, you’ll need to first import the library. Let’s see what this looks like:
# Getting All Environment Variables Using os
import os
print(os.environ)
# Returns:
# environ({'TERM_PROGRAM': 'vscode', ...})
I have truncated the returned value above to make it more readable. Running this on your machine will likely display a large amount of variables.
We can check the type of this variable to see what it is:
# Checking the Type of the os.environ
import os
print(type(os.environ))
# Returns
# <class 'os._Environ'>
In the next section, you’ll learn how to get a single environment variable in Python.
How to Get a Single Environment Variable in Python
Because the returned value of the os.environ
attribute is a dictionary-like structure, we can access a particular variable by using its key. For example, if we wanted to get the environment variable for 'USER'
we could access it as we would any other dictionary’s value:
# Getting a Single Environment Variable in Python
import os
print(os.environ['USER'])
# Returns: datagy
Now, what would happen if we tried to access a variable that didn’t exist? Let’s try getting the environment variable for 'nonsense'
:
# Getting an Environment Variable that Doesn't Exist
import os
print(os.environ['nonesense'])
# Returns: KeyError: 'nonsense'
We can see that this raises a KeyError
. If we don’t want our program to crash, we can use the .get()
method to safely return None
if no value exists. Let’s see what this looks like:
# Returning None if No Environment Variable Exists
import os
print(os.getenv('nonsense'))
# Returns: None
In the next section, you’ll learn how to check if an environment variable exists in Python.
How to Check if an Environment Variable Exists in Python
Because the returned value from the os.environ
attribute is dictionary-like, you can use the in
keyword to check whether or not an environment variable exists in Python. Let’s see how we can check if the variable 'USER'
exists on the environment using an if-else
block.
# Checking if an Environment Variable Exists in Python
import os
if 'USER' in os.environ:
print('Environment variable exists!')
else:
print('Environment variable does not exist.')
# Returns:
# Environment variable exists!
Using this conditional allows you to safely run code to see if an environment variable exists. If the variable doesn’t exist, you could, for example, prompt the user for input before continuing.
In the following section, you’ll learn how to return a default value if one doesn’t exist.
How to Return a Default Value for Environment Variables If One Doesn’t Exist
If no value exists for an environment variable, you may want to pass in a default value. This can also be done by using the .getenv()
method. By passing in a second parameter, a default value can be returned if a variable doesn’t exist.
Let’s see what this looks like:
# Returning a Default Value When a Variable Doesn't Exist
import os
print(os.getenv('nonsense', 'default value'))
# Returns: default value
In the next sections, you’ll learn how to set environment variables.
How to Set Environment Variables in Python
Now that you know how to get environment variables using Python, in this section, you’ll learn how to set the values for new or existing variables. Because this process is different for Windows and macOS / Linux, the process is split across two different sections.
How to Set Environment Variables in Python Using macOS And Linux
To set an environment variable in Python using either macOS or Linus is to use the export
command in a shell session. For example, if we wanted to set the variable of API_KEY to be equal to '123acb'
, we could write the following:
# Setting an Environment Variable
export API_KEY = '123abc'
When you run this code in your terminal, the environment variable will be set globally for all programs for that session. When you close your terminal, the environment variables are lost again.
If you only wanted to set the environment variable for a particular script, you can do this as well from the shell command. Simply change the command to this:
# Setting an Environment Variable
API_KEY = '123abc' python myscript.py
How to Set Environment Variables in Python Using Windows
Windows provides very similar ways to set environment variables in Python. Similar to macOS and Linux, you can set the variables for a single session by using the command prompt. Rather than using export
, you use the word set
. Let’s take a look:
# Setting an Environment Variable
set API_KEY = '123abc'
Instead, if you’re using the PowerShell console, you need to use the following code:
# Using PowerShell to Set an Environment Variable
$Env:API_KEY = '123abc'
In the following section, you’ll learn a much easier way to set and manage environment variables, using the dotenv
library.
How to Use dotenv in Python to Work with Environment Variables in Python
Using the terminal or command prompt to manage environment variables can be a time-consuming and, frankly, annoying task. Because of this, Python provides the option to use the dotenv
library to better manage environment variables.
The benefit of using the dotenv library is that the process is the same for Windows, macOS, and Linux. The way that this process works is by including a .env
file in the project directory that you’re working in. The file will contain the environment variables that you’re hoping to use in your script.
Let’s see how we can use the dotenv library to manage our environment variables better in Python. First, we’ll need to install the dotenv library, which can be done using either pip
or conda
:
# Install dotenv
pip install python-dotenv
conda install python-dotenv
Once this is done, we need to create the file in the directory. The easiest way to do this is using the terminal:
touch .env
Once this is done, you can open the file, which is really just a text file. From there, you can add all of the environment variables that you want to use. The way that this is done is by placing different variables on new lines and creating the key-value pair by using an equal sign =
:
API_KEY=123abc
user_name=Nik
From there, in your Python script it’s as easy as importing the library and loading the file:
# Loading an Environment Variable File with dotenv
from dotenv import load_dotenv
load_dotenv()
The function will search through the current directory for the .env
file. If it doesn’t find one, then it continues to move up through the directories to try and find the file.
Similarly, you could simply pass in the full path to the file to make your code more explicit:
# Loading an Environment Variable File Explicitly with dotenv
from dotenv import load_dotenv
load_dotenv('/home/datagy/project/.env')
Using dotenv Safely with Source Control Management Tools
Because environment variables can be used to store sensitive information, it’s important to be mindful of not including them when working with SCM tools like Github. In order to work with these safely, you can add them to a .gitignore
file.
In order to make your code more understandable for others, simply add an example .env
file to your repository. This allows readers of your code to understand what environment variables must be set.
Conclusion
In this tutorial, you learned all about environment variables in Python. Environment variables provide the ability to elegantly and securely run your code. They provide the opportunity to streamline your code without repeating and changing your code. Similarly, they prevent having to share secure items such as API Keys.
You learned how to get and set environment variables in Python using the os
library. You also learned how to use the dotenv
library to make managing environment variables much easier in Python.
Additional Resources
To learn more about related topics, check out the tutorials below:
- Use Python to List Files in a Directory (Folder) with os and glob
- Python: Get and Change the Working Directory
- Python: Check if a File or Directory Exists
- Python Delete a File or Directory: A Complete Guide
- Python dotenv Official Documentation
Environment variables provide a great way to configure your Python application, eliminating the need to edit your source code when the configuration changes. Common configuration items that are often passed to application through environment variables are third-party API keys, network ports, database servers, and any custom options that your application may need to work properly.
In this article I’m going to share some of the techniques and tools available in Python to work with environment variables.
How to access environment variables from Python
Using the os.environ dictionary
In Python, the os.environ
dictionary contains all the environment variables. The simplest way to retrieve a variable from inside your application is to use the standard dictionary syntax. For example, this is how you can access an environment variable named USER
:
>>> import os
>>> user = os.environ['USER']
>>> user
'miguel'
Using this method, if you try to import an environment variable that doesn’t exist Python will raise a KeyError
exception:
>>> database_url = os.environ['DATABASE_URL']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/miguel/.pyenv/versions/3.8.6/lib/python3.8/os.py", line 675, in __getitem__
raise KeyError(key) from None
KeyError: 'DATABASE_URL'
Using os.environ.get()
Getting the KeyError
is a good idea for environment variables that your program requires, but there are situations where you may want to allow some variables to be optional. To avoid the error you can use the dictionary’s get()
method, which returns None
when the requested key does not exist in the dictionary:
>>> database_url = os.environ.get('DATABASE_URL')
Adding a default value if the variable is not defined
If you’d like to provide a default value for the missing variable that is not None
, you can add it as a second argument:
>>> database_url = os.environ.get('DATABASE_URL', 'sqlite:///')
>>> database_url
'sqlite:///'
Using the os.getenv() function
Python also provides the os.getenv()
function to access environment variables. This function works in a very similar way to the os.environ.get()
method. Here is how to access a variable with it:
>>> user = os.getenv('USER')
>>> user
'miguel'
This function does not raise an error for missing variables, it returns None
just like os.environ.get()
. And it also accepts a second argument with a custom default value:
>>> database_url = os.getenv('DATABASE_URL', 'sqlite://')
>>> database_url
'sqlite://'
Is os.getenv()
better than os.environ
? That is really up to you. I personally prefer to use the os.environ
dictionary, since it gives me the option of halting the program with a KeyError
if a required variable is missing.
How to set environment variables
In this section I’m going to give you a quick summary of how to set environment variables in a terminal or command prompt window. If you want to know all the possible ways to set environment variables, my colleague Dominik Kundel has written a very detailed blog post on this subject titled How to Set Environment Variables.
Unix and MacOS
There are two basic ways to set an environment variable from a bash or zsh terminal session. One is using the export
keyword:
A variable that is set in this way will be passed on to any programs or scripts that you start from this terminal session. Keep in mind that environment variables are not saved anywhere outside of the context of the shell session, so they will go away when you close the terminal session.
An alternative way to define an environment variable is to set it in the same line where the target application is executed:
DEBUG=true python my_cool_application.py
This second form has the benefit that the variable is only set in the environment space of the intended application.
Microsoft Windows
If you are using Windows you have a few options. If you are interested in setting environment variables via the control panel, see the article linked above.
If you are in a command prompt window, you can set an environment variable using the set
command:
Like in the Unix case, the variable is not stored or remembered beyond the current session.
If you are using the newer PowerShell console, the syntax for setting environment variables is completely different:
Finally, if you are using a Unix compatibility layer such as WSL or Cygwin, then you must go to the Unix section above and use any of the methods listed there for bash or zsh.
Using .env files
Are you confused by all the different ways to set environment variables? I personally find it inconvenient that each platform or shell requires a different procedure.
In my opinion, a better way to manage your environment variables is to store them in a .env (pronounced dot env) file. A .env file is a text file in which the variables are defined, one per line. The format of a .env file is exactly the same under all operating systems, so .env files make working with environment variables uniform across all platforms. And as if this isn’t enough, having your environment variables written in a file that is automatically imported by Python means that you don’t have to manually set them every time you start a new shell.
Here is a short .env file example with two variables:
DEBUG=true
DATABASE_URL=sqlite:///mydb.sqlite
You can create a .env file in the root directory of each of your projects, and that way you can keep all the variables that are needed by each project neatly organized!
The python-dotenv package allows a Python application to import variables defined in a .env file into the environment. You can install python-dotenv
in your virtual environment using pip
:
pip install python-dotenv
Below you can see how to import a .env file into a Python application:
>>> from dotenv import load_dotenv
>>> load_dotenv()
The load_dotenv()
function will look for a file named .env in the current directory and will add all the variable definitions in it to the os.environ
dictionary. If a .env file is not found in the current directory, then the parent directory is searched for it. The search keeps going up the directory hierarchy until a .env file is found or the top-level directory is reached.
If you want to prevent python-dotenv from searching for a .env file through your directories, you can pass an explicit path to your file as an argument to load_dotenv()
:
>>> from dotenv import load_dotenv
>>> load_dotenv('/home/miguel/my_project/.env')
There are some additional arguments that you can use when you call the load_dotenv()
function. If you want to learn about them consult the documentation.
Once the .env file is imported, you can access environment variables using any of the methods shown above.
A note about .env file security
In many cases you will be adding environment variables that contain sensitive information to your .env files, like passwords or API keys. For that reason, in general you do not want to add these files to your project’s source control repository.
The standard practice is to add an exception for files with this name, so that they are not committed to source control by mistake. For git, you can add a line with the name of the file to the .gitignore file in the root of your repository.
But if you cannot commit the .env file, how do you tell users of the project which variables need to be set? For this you can add an example .env file to your repository with a name such as .env.example, that contains the list of variables that the project requires, but without including their values. This serves as guidance for users of your project, without giving away sensitive information.
Conclusion
I hope this article was useful to help you understand how to use environment variables to configure your Python projects.
Do you have any other ways to work with environment variables? I’d love to know!
Miguel Grinberg is a Python Developer for Technical Content at Twilio. Reach out to him at mgrinberg [at] twilio [dot] com if you have a cool Python project you’d like to share on this blog!
- Introduction
- The os Module
-
Creating Environment Variables
- Method One: Creating Environment Variables Via The Operating System
- Linux and macOS
- Windows
- Method Two: Creating Environment Variables Using Python
-
Getting Environment Variables With The OS Module
- Example One: Working With A String
- Example Two: Working With A Number
- Example Three: Working With A Boolean
- Conclusion
- References
Introduction
Environment variables are used in a program to set the values of variables or constants within that program. The environment variables exist at the operating system level. This allows for the environment variables to be fluid in that they can be changed for different stages of the software development lifecycle without storing / changing the values in the source code for each stage (dev / test / production).
From a security perspective, it means that the source code does not have the values of its variables hard-coded into them. An example of this would be storing an API key as an environment variable instead of setting the value in a variable / constant in the source code. If that happened and was then sent up to a public (or even a private) Git repository, that would be a major security threat.
The os Module
For Python to interact with the operating system, the os
module is used. It can perform actions such as:
- Creating and reading environment variables.
- Getting details about the operating system, such as the type of operating system it is.
- Working with files and file paths.
There are a lot more that it can do, which is covered in the modules documentation.
So how can environment variables be created and used?
Creating Environment Variables
First up, let’s create some environment variables to work with. There are multiple ways to do this, but this article will focus on two. The first of which is to create them via the operating system with the second being via Python using os.environ
.
Three example environment variables will be created, each with a different data type.
For both methods:
- EXAMPLE_ONE is just a string of text. This is a typical use case for most data that would be assigned to an environment variable.
- EXAMPLE_TWO is a number. Or is it? More on that later.
- EXAMPLE_THREE is a boolean. Or perhaps not. Again, more on that later.
Method One: Creating Environment Variables Via The Operating System
NOTE: On Linux / macOS, if the string has spaces in it, the string will need to be wrapped in ""
, otherwise only the text up to the first space will be assigned. Windows is fine without them.
Linux and macOS
Using a terminal emulator app, run:
export EXAMPLE_ONE="This is an environment variable"
export EXAMPLE_TWO=1
export EXAMPLE_THREE=False
Enter fullscreen mode
Exit fullscreen mode
If an environment variable needs to be persistent for Linux or macOS, it will need to be added to the users .bashrc
or .zshrc
file in their home directory using the same syntax.
Windows
Using the command prompt (cmd.exe), run:
set EXAMPLE_ONE=This is an environment variable
set EXAMPLE_TWO=1
set EXAMPLE_THREE=False
Enter fullscreen mode
Exit fullscreen mode
To set persistent environment variables in Windows, use the setx
command with the syntax being:
setx EXAMPLE_ONE "This is an environment variable"
setx EXAMPLE_TWO "1"
setx EXAMPLE_THREE "False"
Enter fullscreen mode
Exit fullscreen mode
Method Two: Creating Environment Variables Using Python
For all three operating system types, the method is the same in Python by using os.environ
:
import os
os.environ["EXAMPLE_ONE"] = "This is an environment variable"
os.environ["EXAMPLE_TWO"] = "1"
os.environ["EXAMPLE_THREE"] = "False"
Enter fullscreen mode
Exit fullscreen mode
NOTE: When Python is closed, these environment variables will be removed.
Getting Environment Variables With The OS Module
There are two methods that can be used to access an environment variable using the os
module. The first method is via os.environ
. It requires the environment variable name to be passed to it in a list. For example:
import os
print(os.environ["EXAMPLE_ONE"])
Enter fullscreen mode
Exit fullscreen mode
Output:
This is an environment variable
Enter fullscreen mode
Exit fullscreen mode
There is one downside to this method, which is open to interpretation. If the environment variable is not present, it will raise a KeyError
and cause a hard stop. An example of this is shown below:
Traceback (most recent call last):
File "/Users/neil/Documents/writing/blog-posts/code.py", line 11, in <module>
print(os.environ["EXAMPLE_ONE"])
~~~~~~~~~~^^^^^^^^^^^^^^^
File "<frozen os>", line 679, in __getitem__
KeyError: 'EXAMPLE_ONE'
Enter fullscreen mode
Exit fullscreen mode
Now, this might be what is required to happen, which is fine. But let’s say that it isn’t and the code needs to continue. To get around this, os.getenv
is a useful solution. What this will do is instead of erroring out, it will set the value to None
for any missing environment variables instead.
For the examples going forward, the os.getenv
method will be used.
Example One: Working With A String
The first example will get the value or the EXAMPLE_ONE
environment variable and show its value.
import os
example_one = os.getenv("EXAMPLE_ONE")
print(f"Example One Value: {example_one}")
print(type(example_one))
Enter fullscreen mode
Exit fullscreen mode
Output:
Example One Value: This is an environment variable
<class 'str'>
Enter fullscreen mode
Exit fullscreen mode
From the output, the value of example_one
is shown and it has a data type of str
(string).
Example Two: Working With A Number
This is where things get problematic. Remember how Example Two was described earlier («EXAMPLE_TWO is a number. Or is it?»). Well, although it looks like a number, it is actually a string data type. This is because environment variables are treated as strings, no matter what the value is.
For example, let’s access the EXAMPLE_TWO
environment variable and see what data type it has:
import os
example_two = os.getenv("EXAMPLE_TWO")
print(f"Example Two Value: {example_two}")
print(type(example_two))
Enter fullscreen mode
Exit fullscreen mode
Output:
Example Two Value: 1
<class 'str'>
Enter fullscreen mode
Exit fullscreen mode
As can be seen, the data type class is str
(string). So how can the value be used as a number, in this case an integer? It is done by enforcing the data type to the example_two
variable using the int
class. For example:
import os
example_two = int(os.getenv("EXAMPLE_TWO"))
print(f"Example Two Value: {example_two}")
print(type(example_two_int))
Enter fullscreen mode
Exit fullscreen mode
Output:
Example Two Value: 1
<class 'int'>
Enter fullscreen mode
Exit fullscreen mode
The output looks the same but the data type for example_two
is now an integer (int). This will now allow it to be used for any mathematical operations.
There is one further issue. What if the environment variable is not an integer number but rather a string, float, boolean or just doesn’t exist?
If it doesn’t exist, the value would be set to None
. If it did exist and is not an integer, it would be set to that value. But, as the data type is enforced as an integer, a ValueError
would be raised for both cases.
A solution for this would be to use the try
block to check it.
The following example will check the value of EXAMPLE_TWO
and if it can’t be set to an integer data type due to the value not being an integer, it will set example_two
to 0
:
First, change EXAMPLE_TWO
to a non-number-based value:
Operating system method:
export EXAMPLE_TWO="I am not a number"
Enter fullscreen mode
Exit fullscreen mode
Or via Python:
import os
os.environ["EXAMPLE_TWO"] = "I am not a number"
Enter fullscreen mode
Exit fullscreen mode
Next, use the try
block to check and set the value of example_two
:
import os
try:
example_two_int = int(os.getenv("EXAMPLE_TWO"))
except ValueError:
example_two_int = 0
print(f"Example Two Value: {example_two_int}")
print(type(example_two_int))
Enter fullscreen mode
Exit fullscreen mode
Output:
Example Two Value: 0
<class 'int'>
Enter fullscreen mode
Exit fullscreen mode
As EXAMPLE_TWO
was not a numeric value, a ValueError
was raised and as a result, the value of example_two
was set to 0
.
Example Three: Working With A Boolean
Just as in example two, an environment variable with what looks like a boolean value will have a string data type. This will mean that it cannot be used for boolean operations.
One of the additional issues with boolean values is how they can be presented. For example, in Python a boolean value is set to either True
or False
. In other languages, such as JavaScript, they are set to either true
or false
. There are others, such as yes / no, y / n, 0 / 1 or on / off.
So, how can we set a boolean data type when there are a lot of possible ways that an environment variable can be set with a boolean value? This is actually easy to do with Python. Start by putting as many of the possible ways to present a True
value in a list and compare the value that is assigned to the environment variable. If the value matches one of the entries in the list, the value of the variable will be set to True
. If not, it will be False
.
For example, set a False
boolean value:
import os
example_three = os.getenv("EXAMPLE_THREE") # --- Currently set to "False"
example_three = example_three.lower() in ["true", "1", "1.0", "y", "yes", "on"]
print(f"Example Three Value: {example_three}")
print(type(example_three))
Enter fullscreen mode
Exit fullscreen mode
Output:
Example Three Value: False
<class 'bool'>
Enter fullscreen mode
Exit fullscreen mode
In the above example, the value of example_three
was converted to all lowercase to make it easier to check against and then compared to each entry in the list. As it didn’t match, the new value of example_three
is False
but with a data type class of bool
, which is what is needed.
Conclusion
I hope that this article was useful. There will be a follow up article to this that will cover using .env files for creating environment variables.
Thank you for reading and have a nice day!
References
Python os module documentation.
- 1. Настройка локальной среды
- 2. Получение Python
- 1. Платформа Windows
- 2. Платформа Linux
- 3. Mac OS
- 3. Настройка PATH
- 1. Настройка PATH в Unix / Linux
- 2. Настройка PATH в Windows
- 3. Переменные среды Python
- 4. Запуск Python
- 1. Интерактивный интерпретатор
- 2. Скрипт из командной строки
- 3. Интегрированная среда разработки
Python 3 доступен для Windows, Mac OS и большинства вариантов операционной системы Linux.
Настройка локальной среды
Откройте окно терминала и введите «python», чтобы узнать, установлен ли он и какая версия установлена.
Получение Python
Платформа Windows
Бинарники последней версии Python 3 (Python 3.6.4) доступны на этой странице
загрузки
Доступны следующие варианты установки.
- Windows x86-64 embeddable zip file
- Windows x86-64 executable installer
- Windows x86-64 web-based installer
- Windows x86 embeddable zip file
- Windows x86 executable installer
- Windows x86 web-based installer
Примечание. Для установки Python 3.6.4 минимальными требованиями к ОС являются Windows 7 с пакетом обновления 1 (SP1). Для версий от 3.0 до 3.4.x Windows XP является приемлемым.
Платформа Linux
Различные варианты использования Linux используют разные менеджеры пакетов для установки новых пакетов.
На Ubuntu Linux Python 3 устанавливается с помощью следующей команды из терминала.
sudo apt-get install python3-minimalУстановка из исходников
Загрузите исходный tar-файл Gzipped с URL-адреса загрузки Python
https://www.python.org/ftp/python/3.6.4/Python-3.6.4.tgz
Extract the tarball tar xvfz Python-3.5.1.tgz Configure and Install: cd Python-3.5.1 ./configure --prefix = /opt/python3.5.1 make sudo make installMac OS
Загрузите установщики Mac OS с этого URL-адреса
https://www.python.org/downloads/mac-osx/
Дважды щелкните этот файл пакета и следуйте инструкциям мастера для установки.
Самый современный и текущий исходный код, двоичные файлы, документация, новости и т.д. Доступны на официальном сайте Python —
Python Official Website
−https://www.python.org/
Вы можете загрузить документацию Python со следующего сайта. Документация доступна в форматах HTML, PDF и PostScript.
Python Documentation Website
−www.python.org/doc/
Настройка PATH
Программы и другие исполняемые файлы могут быть во многих каталогах. Следовательно, операционные системы предоставляют путь поиска, в котором перечислены каталоги, которые он ищет для исполняемых файлов.
Важными особенностями являются:
- Путь хранится в переменной среды, которая является именованной строкой, поддерживаемой операционной системой. Эта переменная содержит информацию, доступную для командной оболочки и других программ.
- Переменная пути называется PATH в Unix или Path в Windows (Unix чувствительна к регистру, Windows — нет).
- В Mac OS установщик обрабатывает детали пути. Чтобы вызвать интерпретатор Python из любого конкретного каталога, вы должны добавить каталог Python на свой путь.
Настройка PATH в Unix / Linux
Чтобы добавить каталог Python в путь для определенного сеанса в Unix —
В csh shell
— введите setenv PATH «$ PATH:/usr/local/bin/python3» и нажмите Enter.
В оболочке bash (Linux)
— введите PYTHONPATH=/usr/local/bin/python3.4 и нажмите Enter.
В оболочке sh или ksh
— введите PATH = «$PATH:/usr/local/bin/python3» и нажмите Enter.
Примечание.
/usr/local/bin/python3
— это путь к каталогу Python.
Настройка PATH в Windows
Чтобы добавить каталог Python в путь для определенного сеанса в Windows —
-
В командной строке введите путь
%path%;C:\Python
и нажмите Enter.
Примечание.
C:\Python
— это путь к каталогу Python.
Переменные среды Python
S.No. | Переменная и описание |
---|---|
1 | PYTHONPATH Он играет роль, подобную PATH. Эта переменная сообщает интерпретатору Python, где можно найти файлы модулей, импортированные в программу. Он должен включать каталог исходной библиотеки Python и каталоги, содержащие исходный код Python. PYTHONPATH иногда задается установщиком Python. |
2 | PYTHONSTARTUP Он содержит путь к файлу инициализации, содержащему исходный код Python. Он выполняется каждый раз, когда вы запускаете интерпретатор. Он называется как .pythonrc.py в Unix и содержит команды, которые загружают утилиты или изменяют PYTHONPATH. |
3 | PYTHONCASEOK Он используется в Windows, чтобы проинструктировать Python о поиске первого нечувствительного к регистру совпадения в инструкции импорта. Установите эту переменную на любое значение, чтобы ее активировать. |
4 | PYTHONHOME Это альтернативный путь поиска модуля. Он обычно встроен в каталоги PYTHONSTARTUP или PYTHONPATH, чтобы упростить библиотеку модулей коммутации. |
Запуск Python
Существует три разных способа запуска Python —
Интерактивный интерпретатор
Вы можете запустить Python из Unix, DOS или любой другой системы, которая предоставляет вам интерпретатор командной строки или окно оболочки.
Введите
python
в командной строке.
Начните кодирование сразу в интерактивном интерпретаторе.
$python # Unix/Linux or python% # Unix/Linux or C:>python # Windows/DOSВот список всех доступных параметров командной строки —
S.No. | Вариант и описание |
---|---|
1 | -d предоставлять отладочную информацию |
2 | -O генерировать оптимизированный байт-код (приводящий к .pyo-файлам) |
3 | -S не запускайте сайт импорта, чтобы искать пути Python при запуске |
4 | -v подробный вывод (подробная трассировка по операциям импорта) |
5 | -X отключить встроенные исключения на основе классов (просто используйте строки); устаревший, начиная с версии 1.6 |
6 | -c cmd запустить скрипт Python, отправленный в виде строки cmd |
7 | file запустить скрипт Python из заданного файла |
Скрипт из командной строки
Сценарий Python можно запустить в командной строке, вызвав интерпретатор в вашем приложении, как показано в следующем примере.
$python script.py # Unix/Linux or python% script.py # Unix/Linux or C:>python script.py # Windows/DOSПримечание. Убедитесь, что права файлов разрешают выполнение.
Интегрированная среда разработки
Вы можете запустить Python из среды графического интерфейса пользователя (GUI), если у вас есть приложение GUI в вашей системе, которое поддерживает Python.
Для разработки Python приложений рекомендую PyCharm от компании JetBrains, как наиболее развитую и удобную IDE.
На простом примере рассмотрим, как настроить рабочее окружение для работы с новыми данными, а также как вернуться к рабочему процессу с помощью одного слова.
Нам часто приходится сталкиваться с обработкой различных типов данных. Вся обработка осуществляется с помощью языка Python, который позволяет в короткие сроки решать поставленные задачи. Для работы с новым проектом необходимо создавать новое окружение, чтобы избежать проблем с различными версиями пакетов в Python. Рассмотрим пример создания виртуального окружения и его быстрого запуска.
(далее будет информация для начинающих специалистов, если вы уже профессионал — переходите сразу к следующему пункту)
Если у Вас не установлен Python, то скачиваем программу установки и устанавливаем в нужную директорию, не забываем поставить галочку (Add Python X.X to PATH).
Не всегда последняя версия дистрибутива – оптимальное решение, т.к. множество пакетов работает под определенные версии Python. Наиболее распространена версия 3.6.
Чтобы проверить, что Python установился правильно, в командной строке вводим команду — python —version:
Если в результате получаем ошибку о том, что «python не является внутренней или внешней командой…» — необходимо проверить наличие пути в переменных окружения. Проверить это можно в «переменных среды текущего пользователя»:
В данном случае Python установлен в директорию «D:\Work\Python». Если в переменной Path прописаны эти пути, но все равно выскакивает ошибка, то перезагрузите компьютер.
С установкой разобрались, приступим к созданию окружения. Для этого создадим папку для нового проекта и запустим командную строку в новой директории. Для запуска используем команду cmd в строке пути:
В командной строке вводим команду: python -m venv new_proj_env
Где venv – инструмент для создания виртуального окружения, new_proj_env – произвольное имя, которое задали для данного окружения. В результате выполнения в папке с проектом появится новая директория с именем new_proj_env.
Для работы в рамках виртуального окружения, его необходимо активировать с помощью следующей команды: new_proj_env\Scripts\activate
После активации название окружения должно появиться в скобках слева от пути к проекту:
Далее устанавливаем необходимые пакеты, для примера установим pandas и jupyter:
- pip install pandas jupyter – здесь не нужно разделять имена пакетов запятыми,
- pandas – пакет для работы с табличными данными,
- jupyter – пакет для интерактивной работы с данными в браузере с помощью блокнота (jupyter notebook).
Важно отметить, если Вы не установите jupyter для нового окружения, то интерпретатор Python будет подтягивать пакеты из глобального окружения.
Для того, чтобы начать работу, осталось запустить блокнот, командой jupyter notebook:
В результате должен запуститься браузер (по умолчанию), если этого не произошло, то необходимо скопировать адрес, выделенный красным, и вставить в строку поиска браузера. Создадим новый блокнот, импортируем необходимые библиотеки и загрузим данные:
Таким образом, чтобы на следующий день продолжить работу, необходимо:
- Перейти в папку с проектом;
- Активировать виртуальное окружение;
- Запустить jupyter notebook.
Вместо этого, создадим переменную окружения, которая будет выполнять все три пункта разом. Для этого снова зайдем в переменные окружения и создадим новую переменную:
Здесь мы задаем имя переменной, и через оператор «&» обозначаем команды:
- d: — переходим на диск D, т.к. в данном примере папка с проектом лежит на локальном диске D;
- cd D:\Work\New_Projec – переходим к расположению папки с проектом;
- new_proj_env\Scripts\activate – активируем виртуальное окружение;
- jupyter notebook – запускаем блокнот.
Таким образом, чтобы на следующий день продолжить работу, потребуется ввести лишь имя переменной, заключенной в знак «%»:
Ввод осуществляется с любого расположения командной строки.
В результате мы создали виртуальное окружение, а также создали переменную для быстрого доступа к рабочему проекту. Надеюсь, вы нашли для себя что-то новое.