Терминальный сеанс python что это
Перейти к содержимому

Терминальный сеанс python что это

  • автор:

Терминальный сеанс python что это

Когда вы решите, что знаете путь к команде, проверьте его: введите этот путь в терминальном окне. Откройте окно командной строки и введите только что найденный полный путь:

C:\> C:\Python35\python

Python 3.5.0 (v3.5.0:374f501f4567, Sep 13 2015, 22:15:05) [MSC v.1900 32 bit

Type «help», «copyright», «credits» or «license» for more information.

Если команда успешно работает, то вы знаете, как запустить Python в вашей системе.

Запуск Python в терминальном сеансе

Введите в терминальном сеансе следующую строку и убедитесь в том, что на экране появился вывод Hello Python world!:

>>> print(«Hello Python world!»)

Hello Python interpreter!

Каждый раз, когда вы захотите выполнить фрагмент кода Python, откройте окно командной строки и запустите терминальный сеанс Python. Чтобы закрыть терминальный сеанс, нажмите Ctrl+Z или введите команду exit().

Установка текстового редактора

Geany — простой и удобный текстовый редактор; он легко устанавливается, позволяет запускать практически любые программы прямо из редактора (вместо терминала) и использует цветовое выделение синтаксиса, а код выполняется в терминальном окне. В приложении Б приведена информация о других текстовых редакторах, но я рекомендую использовать Geany, если только у вас нет веских причин для работы в другом редакторе.

Программу установки Geany для Windows можно загрузить по адресу http://geany.org/. Щелкните в строке Releases меню Download и найдите пакет geany-1.25_setup.exe (или что-нибудь в этом роде). Запустите программу и подтвердите все значения по умолчанию.

Чтобы запустить свою первую программу, откройте Geany: нажмите клавишу Windows и найдите Geany в вашей системе. Создайте ярлык, перетащив значок на панель задач или рабочий стол. Создайте папку для своих проектов и присвойте ей имя python_work. (В именах файлов и папок лучше использовать буквы нижнего регистра и символы подчеркивания, потому что это соответствует соглашениям об именах Python.) Вернитесь к Geany и сохраните пустой файл Python (File—>Save As) с именем hello_world.py в папке python_work. Расширение .py сообщает Geany, что файл содержит программу Python. Оно также подсказывает Geany, как следует запускать программу и как правильно выделить элементы синтаксиса.

После того как файл будет сохранен, введите следующую строку:

print(«Hello Python world!»)

Если команда python успешно сработала в вашей системе, то дополнительная настройка Geany не нужна; пропустите следующий раздел и переходите к разделу «Запуск программы Hello World» на с. 28. Если для запуска интерпретатора Python пришлось вводить полный путь вида C:\Python35\python, выполните инструкции по настройке Geany для вашей системы, приведенные в следующем разделе.

Чтобы настроить Geany для работы с Python, откройте окно Build—>Set Build Commands. В окне приведены команды Compile и Execute, рядом с каждой из которых располагается команда. Команды Compile и Execute начинаются с команды python, записанной символами нижнего регистра, но Geany не знает, где в вашей системе находится исполняемый файл python. К команде нужно добавить путь, который вы ввели в окне командной строки.

Добавьте в начало команд Compile и Execute диск и путь к папке, в которой находится файл. Команда Compile должна выглядеть примерно так:

C:\Python35\python -m py_compile «%f»

Возможно, в вашей системе путь будет выглядеть немного иначе; проследите за правильностью регистра символов и расстановки пробелов.

Рис. 1.3. Настройка Geany для использования Python 3 в Windows

Команда Execute должна выглядеть примерно так:

И снова внимательно проверьте пробелы и регистр символов. На рис. 1.3 показано, как эти команды должны выглядеть в меню конфигурации Geany.

Завершив настройку команд, нажмите кнопку OK.

Запуск программы Hello World

Все должно быть готово для успешного выполнения программы. Запустите программу hello_world.py: выберите команду меню Build—>Execute, щелкните на кнопке Execute (с шестеренками) или нажмите клавишу F5. На экране появляется терминальное окно со следующим выводом:

Hello Python world!

(program exited with code: 0)

Press return to continue

Если вы не увидели это сообщение, проверьте каждый символ во введенной строке. Может, вы случайно набрали print с прописной буквы? Пропустили одну или обе кавычки или круглые скобки? В языках программирования используется предельно конкретный синтаксис, и при малейшем его нарушении произойдет ошибка. Если программа так и не заработала, возможно, следующий раздел поможет вам в этом.

The Terminal: First Steps and Useful Commands

The terminal can be intimidating to work with when you’re used to working with graphical user interfaces (GUIs). However, it’s an important tool that you need to get used to in your journey as a Python developer. And once you level up your skill of using the terminal, it becomes an extremely powerful tool in your repertoire. With just a few commands in the terminal, you can do tasks that are impossible or at least very tedious to do in a GUI.

In this tutorial, you’ll learn how to:

  • Find the terminal on your operating system
  • Open the terminal for the first time
  • Navigate your file system with basic commans
  • Create files and folders with the terminal
  • Manage packages with pip commands
  • Keep track of your files with Git in the terminal

If you’re new to working with the terminal, or you’re looking to expand your understanding of its capabilities, then this tutorial is a great starting point. In it, you’ll get an introduction to some of the basic commands and learn how to use pip and Git to manage your projects in the terminal.

Understanding how to integrate the terminal, pip , and Git into your workflows is essential for you as a Python developer. However, it’s important to note that you’ll only scratch the surface of what the terminal can do, and there’s much more to learn as you continue to explore the terminal as an essential development tool.

Free Download: Click here to get a free cheat sheet of useful commands to get you started working with the terminal.

Install and Open the Terminal

Back in the day, the term terminal referred to some clunky hardware that you used to enter data into a computer. Nowadays, people are usually talking about a terminal emulator when they say terminal, and they mean some kind of terminal software that you can find on most modern computers.

Note: There are two other terms that you might hear now and then in combination with the terminal:

  1. A shell is the program that you interact with when running commands in a terminal.
  2. A command-line interface (CLI) is a program designed to run in a shell inside the terminal.

In other words, the shell provides the commands that you use in a command-line interface, and the terminal is the application that you run to access the shell.

If you’re using a Linux or macOS machine, then the terminal is already built in. You can start using it right away.

On Windows, you also have access to command-line applications like the Command Prompt. However, for this tutorial and terminal work in general, you should use the Windows terminal application instead.

Read on to learn how to install and open the terminal on Windows and how to find the terminal on Linux and macOS.

Windows

The Windows terminal is a modern and feature-rich application that gives you access to the command line, multiple shells, and advanced customization options. If you have Windows 11 or above, chances are that the Windows terminal is already present on your machine. Otherwise, you can download the application from the Microsoft Store or from the official GitHub repository.

Before continuing with this tutorial, you need to get the terminal working on your Windows computer. You can follow the Your Python Coding Environment on Windows: Setup Guide to learn how to install the Windows terminal.

After you install the Windows terminal, you can find it in the Start menu under Terminal. When you start the application, you should see a window that looks like this:

Windows Terminal with Windows PowerShell tab

It can be handy to create a desktop shortcut for the terminal or pin the application to your task bar for easier access.

Linux

You can find the terminal application in the application menu of your Linux distribution. Alternatively, you can press Ctrl + Alt + T on your keyboard or use the application launcher and search for the word Terminal.

After opening the terminal, you should see a window similar to the screenshot below:

Screenshot of the Linux terminal

How you open the terminal may also depend on which Linux distribution you’re using. Each one has a different way of doing it. If you have trouble opening the terminal on Linux, then the Real Python community will help you out in the comments below.

macOS

A common way to open the terminal application on macOS is by opening the Spotlight Search and searching for Terminal. You can also find the terminal app in the application folder inside Finder.

When you open the terminal, you see a window that looks similar to the image below:

Screenshot of the macOS terminal

After you launch the terminal application, you’ll see a window that waits for commands. That’s similar to when you’re interacting with a Python script that expects user input.

If you want to interact with the terminal, then you need to know which terminal commands you can enter to proceed. In the next section, you’ll learn about basic terminal commands that’ll help you get started.

Learn Basic Terminal Commands

To work with the terminal effectively, it’s important to understand some basic terminal commands and know how to use them. Terminal commands are the instructions that you type into the terminal to execute a specific task.

Depending on your operating system, you’ll run the terminal commands in a specific shell. For Linux, it’s most likely Bash, for newer macOS versions it’s Zsh, and for Windows it’s PowerShell. These shells differ in their features, but they share most of the basic commands.

Note: You can think of commands as little programs that are built into your shell or can be added by external applications. In PowerShell, commands are also known as cmdlets.

In this section, you’ll explore the most commonly used terminal commands. To see a preview of the commands, select your operating system from the platform switcher below:

  • Windows
  • Linux + macOS

These are the Windows commands that you’ll cover:

Command Description
pwd Print the path of the current directory
mkdir FOLDERPATH Create a new directory
ni FILEPATH Create a new file
clear Clear the terminal window
ls List the contents of a folder
ls -al List all the contents of a folder with info
cat TARGET Show the content of TARGET
cd FOLDERPATH Change into a directory
cd .. Change into the parent directory
echo TEXT Print TEXT to the terminal
echo TEXT > TARGET Print TEXT to a file named TARGET
echo TEXT >> TARGET Append TEXT to TARGET
cp SOURCE TARGET Copy SOURCE to TARGET
rni SOURCE TARGET Rename SOURCE to TARGET
python PYTHONFILE Run PYTHONFILE

The terms in uppercase letters are references to the arguments that the commands allow.

These are the Linux and macOS commands that you’ll cover:

Command Description
pwd Print the path of the current directory
mkdir FOLDERPATH Create a new directory
touch FILEPATH Create a new file
clear Clear the terminal window
ls List the contents of a folder
ls -al List all the contents of a folder with info
cat TARGET Show the content of TARGET
cd FOLDERPATH Change into a directory
cd .. Change into the parent directory
echo TEXT Print TEXT to the terminal
echo TEXT > TARGET Print TEXT to a file named TARGET
echo TEXT >> TARGET Append TEXT to TARGET
cp SOURCE TARGET Copy SOURCE to TARGET
mv SOURCE TARGET Rename or move SOURCE to TARGET
python PYTHONFILE Run PYTHONFILE

The terms in uppercase letters are references to the arguments that the commands allow.

You’ll learn how to navigate the file system and create, edit, and delete files and directories. By the end of this section, you’ll have a solid foundation for working with the terminal and be able to perform many everyday tasks with confidence. You can take this confidence and use it to tackle other tasks in the terminal, such as using pip , interacting with Git, and building command-line interfaces with Python.

Navigate Your File System

The file system is the hierarchical structure of directories and files on a computer. It’s usually what you see when you open a GUI file system application like Windows Explorer or the macOS Finder. It also happens to be an excellent place to start your terminal journey, but again, you’re just dipping a toe into all the terminal’s capabilities here.

The folder that you have currently open in a file system is the current working directory (cwd). As you’ll notice, you use the working directory as a reference point for many file system operations. Understanding the file system and the current working directory as a state is important for effectively navigating and managing files and directories in the terminal.

After you’ve opened the terminal app, you usually start in the user folder of your operating system. You see a command prompt that’s waiting for your input. As you’ll learn, you can use a wide variety of commands as input. But some common commands are the ones to navigate the file system.

To get things started, find out what your current working directory is:

The pwd command stands for print working directory, which is the command that you use to determine your current location within the file system. Here pwd shows that the current working directory is /Users/realpython .

The working directory is the current directory that you’re operating in. It’s where commands will be executed by default.

Dig Deeper Into the Current Working Directory Show/Hide

There are two terms that are worth exploring in the context of the current working directory:

  1. Environment Variables
  2. PATH

Environment variables are variables that store stateful information about the environment in which the terminal is running. They can be used to store information such as the current working directory, the location of installed software, or the user’s home directory. The terminal can access and use this information to determine how to operate and where to look for files.

PATH is an environment variable that stores a list of directories. To see what paths are in your PATH, call the following command:

  • Windows
  • Linux + macOS

When you enter a command in the terminal, the system will look for a program that matches the command in the directories listed in the PATH. The list visible after running the previous command is the list of locations that your system will look for when evaluating which program to run.

To see which files and folders the /Users/realpython directory contains, you can use ls , which is short for list:

When you type ls and press Enter , you see a list of all the items in the current working directory. In this case, the example shows the folders that you commonly find in the user directory on a macOS machine.

You can also use the -a flag with the ls command, which stands for all. The -a flag shows you all the items in the current working directory, including the hidden items.

Another flag that you can use is -l , which stands for long. When you use this flag along with ls , the command shows you detailed information about the items in the current working directory.

You can also combine these flags to show detailed information about all the items, including the hidden ones, by using ls -al :

The output will show the file type, permissions, owner, size, and timestamp of all the items in the current working directory, including the hidden files and folders. Here, for example, the hidden items are .DS_Store and .Trash .

Note: You can recognize hidden items in the terminal by a dot ( . ) at the start of their name, but there are a couple of dot items that you shouldn’t confuse for hidden files. The single dot ( . ) in the list above represents the current directory, and the two dots ( .. ) link to the parent directory. You’ll work with both of them later in this tutorial.

Hidden files and folders aren’t displayed by default. That’s okay for casual users. But for you as a developer, hidden items can be of interest. They often store configuration data or settings for various applications or the system itself.

The output above may be a bit overwhelming at first. Have a look at this line to understand the output better:

This line gives you valuable information about an item. There’s a directory named Desktop. The last modified date is November 7 at 16:00, and it has a size of 704 bytes.

Apart from that, you can see information about the owner and group permissions. If you want to learn more about the file system permission notation, then you can check out the notation of traditional Unix permissions.

Each folder in the output of ls represents a subfolder that’s inside your current working directory. To change the current working directory into the Desktop/ subfolder, you use the change directory command, cd :

When you enter cd followed by a directory name, it’ll change the current working directory to the specified directory. After you run the command cd Desktop , the current working directory changes to /Users/realpython/Desktop .

Note that you don’t specify a slash / or drive indicator like C:\ at the beginning of Desktop . Calling a path like this indicates that you want to navigate into a path that’s relative to the directory that you’re in right now.

You used a relative path in the command above to navigate into a subfolder. Relative paths make it convenient to reference items in your file system because you don’t have to specify the complete path from the root directory. That being said, you can also change into any directory of your file system by using a complete or absolute path:

  • Windows
  • Linux + macOS

In this case, the cd command changes the current working directory to the directory C:\Users\realpython\Desktop , independently of its previous location.

In this case, the cd command changes the current working directory to the directory /Users/realpython/Desktop , independently of its previous location.

If you use cd with a path that doesn’t exist, then the terminal will print an error. You’ll soon learn how to create new directories. Before you do, make one last move in your file system.

To move one directory up, you usually don’t use the name of the parent folder but two dots:

The two dots ( .. ) represent the parent directory of the current directory. Using cd .. moves you up one directory in the file system hierarchy.

In a GUI file system application like Windows Explorer or the macOS Finder, you’d click little folder icons with your mouse cursor. In the terminal application, you use commands to perform tasks—for example, cd to move between folders and ls to get an overview of the items in a directory.

Create Files and Folders

In this section, you’ll learn how to create and manage files and folders directly from the terminal with some new commands. Additionally, you’ll continue to list the contents of a directory with ls and move between folders with cd , just like you learned before.

With the knowledge from this section, you’ll be able to create and organize your projects from within the terminal.

Start by making sure that your current working directory is the Desktop. Then, use mkdir to create a new folder named rp_terminal :

  • Windows
  • Linux + macOS

You use the mkdir command to create a new directory. The command stands for make directory. Here, you name the new directory rp_terminal .

Next, move into rp_terminal/ and create a new file named hello_terminal.py . Select your operating system below and use your platform-specific command accordingly:

  • Windows
  • Linux + macOS

When you run the ni command, you create an empty file with the given name. In this case, the file is a Python script named hello_terminal.py .

If a file with the provided name already exists, then using ni updates the file’s timestamp to the current date and time, but doesn’t change its contents. The ni command stands for new item.

When you run the touch command, you create an empty file with the given name. In this case, the file is a Python script named hello_terminal.py .

If a file with the provided name already exists, then using touch updates the file’s timestamp to the current date and time. The touch command also updates a file’s access and modification times, even if its content remains the same.

Use the long format of ls to verify that you created the file successfully:

The 0 between the group and the timestamp indicates that hello_terminal.py is currently empty. You’ll use the echo command to add content to hello_terminal.py in a moment. Before you do so, have a look at what echo does when you type the command followed by some text:

As a Python developer, you know that the text you just provided to echo is a print() function call. However, for the echo command, it’s a plain string, which it outputs back into the terminal. More specifically, the echo command sends the string to the standard output stream ( stdout ).

The stdout is the default destination for data that a command-line program sends. The data is displayed on the screen, but you can tell the terminal to redirect stdout to a file:

Again, you’re using echo to output a given string. But this time, you use the caret symbol ( > ) to send the output into hello_terminal.py .

Note: Be careful when redirecting the stdout to existing files. Any content that the file contains will be overwritten without warning.

When you redirect the output of the echo command into a nonexistent file, then you’re creating the file in the same step.

One way to check if the command worked is to list the contents of your folder again:

Perfect, the size of hello_terminal.py is 26 bytes now. To verify that it contains the print() function call, you can use the cat command:

Disappointingly, the cat command doesn’t have to do anything with cats. It’s short for concatenate.

When you use cat with multiple files as arguments, you can concatenate them and display the contents one after another. If you use cat with only one file, then cat is a convenient way to display the contents of a file in the terminal.

Now that you know that hello_terminal.py contains valid Python code, you can run the Python script:

When you’re using the python command, the terminal looks for the Python executable in your PATH.

If you run the python command without any arguments, then you’ll launch the interactive Python interpreter, also known as the REPL. When you run the command with a script file as an argument, then Python runs the provided script.

In this case, you’re executing hello_terminal.py , and you see the output of your print() function directly in the terminal. This works because Python’s print() uses stdout by default.

Note: When you run a Python script in the terminal, the script will output any error messages to the standard error stream ( stderr ). The standard error stream is a separate output channel that’s used specifically for error messages, warnings, and other diagnostic information.

With this separate output channel for error messages, you can redirect or filter regular output and diagnostic messages independently.

With the knowledge gained in this section, you can now create, edit, and inspect Python files within the terminal. You’re now well equipped to move on to working with a command-line tool that’s essential on your journey as a Python developer. It’s called pip , and it enables you to include external packages in your Python projects.

Manage Packages With pip

The pip package manager is an essential tool for managing Python packages. To avoid installing packages directly into your system Python installation, you can use a virtual environment.

A virtual environment provides an isolated Python interpreter for your project. Any packages that you use inside this environment will be independent of your system interpreter. This means that you can keep your project’s dependencies separate from other projects and the system at large.

Create a Virtual Environment

Python has the built-in venv module for creating virtual environments. This module helps you create virtual environments with an isolated Python installation. Once you’ve activated the virtual environment, you can install packages into this environment. The packages that you install into one virtual environment are isolated from all the other environments on your system.

You can follow these steps to create and activate a virtual environment named venv :

  • Windows
  • Linux + macOS

Note that the command prompt has changed. This is a reminder that you’re working within the indicated virtual environment.

Note: When you’re done working with this virtual environment, then you can deactivate it by running the deactivate command.

When you activate a virtual environment with Python’s venv module, you’re adding a new entry to the PATH environment variable. The new entry points to the location of the virtual environment’s Python executable. This ensures that when you run Python commands or scripts, they’ll use this specific Python executable instead of any other version of Python that may be installed on your system.

Install a Package

In this section, you’ll install the Rich library by Will McGugan, which enables you to create colorful text user interface (TUI) applications for the terminal.

Before you install rich , check which Python packages are currently installed in your virtual environment:

Running python -m pip list lists all the packages installed in the current environment. Both pip and setuptools are default packages that you’ll find when you start a new virtual environment.

To install rich , use the command below:

Besides rich , you also installed some other dependencies that you need when you want to use rich . To check all the currently installed packages, you can run python -m pip list again:

To see the capabilities that rich offers, run rich without any arguments:

Depending on your terminal’s capabilities, you should see examples that look like this:

Example output of the rich Python package

In the screenshot above, you can get an impression of what you can do with the rich library. The terminal doesn’t have to be a dark place after all!

Now that your screen is filled from top to bottom, you may want to clear your terminal window again. For this, you can use the clear command:

You use the clear command to clear the terminal screen. It removes all the text and content currently displayed on the terminal, leaving a blank screen. For example, you might want to clear the terminal screen before you run new commands.

In some terminals, you can use Ctrl + L or Cmd + L as keyboard shortcuts to clear the screen.

You’ve learned how to use pip directly from the terminal in this section. Knowing how to use pip in the terminal is crucial for any Python developer, as it allows you to effectively manage and update the packages that you use in your projects.

If you want to learn more about virtual environments and pip , then you can check out Real Python’s primer on Python virtual environments and tutorial on how to use Python’s pip to manage your projects’ dependencies. Both are essential tools to make your life as a Python developer more convenient.

Another helpful tool to manage your projects is Git. Read on to learn how to improve your terminal skills and dive into the world of version control with Git.

Interact With Git

Git is a version control system that developers commonly use, no matter which programming language they’re writing their code in. A version control system tracks changes made to files over time and helps you revert code to a previous version if needed.

In this section, you’ll learn how to interact with Git directly from the terminal. You’ll initialize a Git repository, track files, and create commits.

There are a bunch of GUI clients for Git. They can be convenient to use and help you understand Git logic better by providing rich visual feedback.

However, it’s still a good idea to learn the basics of interacting with Git in the terminal. Learning the basic Git terminal commands can help you understand how Git works under the hood.

Initiate a Git Repository

The first step in using Git is to initialize a repository. A repository is a container that holds all your project files, folders, and metadata.

Create a new Git repository with the command below:

When you run the git init command, Git creates an empty repository in the current working directory. This creates a new subdirectory named .git/ that contains all of the necessary repository files.

Note: If you get an error when you use the git command, then you may need to download and install a current version of Git for your operating system.

After initializing the repository, you can check the status of your repository:

The git status command shows your repository’s current status. It displays which branch you’re on and whether or not there are any commits.

A Git commit is a snapshot of the changes made to the files in a Git repository. When you make changes to your files and save them, you can take a snapshot of those changes by creating a commit on a branch. As you make new commits, the branch points to the latest commits.

In this case, you’re on the main branch, and there are no commits yet. You can also create new branches to work on new features or bug fixes and then switch between branches as needed. If you want to, then you can create multiple branches to work on various versions of your codebase simultaneously.

Additionally, git status shows you which files are untracked, meaning that Git isn’t tracking them. You might want to ignore specific files and folders, such as the venv/ folder, so that Git won’t track them.

Which Files to Ignore Show/Hide

A general rule of thumb for ignoring files in a Git repository is to ignore any files that are specific to your local development environment or files that are generated by your build process. Some examples of files that should typically be ignored include:

  • Files containing sensitive information, such as passwords or private keys
  • Binary files that are generated by your build process, like compiled executables or object files
  • Files specific to your local development environment, such as virtual environment files or user-specific editor configuration files
  • Temporary files or files created by your operating system, such as .DS_Store on macOS or Thumbs.db on Windows
  • Log files or other files that your application generates at runtime

Check out GitHub’s collection of .gitignore templates to get an overview of common .gitignore files. There you’ll also find a Python specific .gitignore example.

You can ignore files in Git by creating a .gitignore file and listing the files and folders that you want to ignore in that file:

As you learned before, this command creates a new file named .gitignore and writes venv to it. Verify the current items in your Git repository by leveraging another command that you already know:

You now have a .gitignore file next to your hello_terminal.py file, your venv/ folder, and the .git/ folder. To check if Git ignores the venv/ folder, run git status again:

Perfect, Git now only shows .gitignore and hello_terminal.py as untracked files. Git knows the files are there, but you haven’t yet added them to the repository.

Track Files With Git

When you start a new project, you’ll likely want to keep track of your changes over time. In the previous section, you initialized a new repository with git init . Now it’s time to start tracking files.

You use the git add command to tell Git which files you want to track:

Remember the dot . in the directory listing before? The dot refers to the current directory. Using . at the end of the git add command tells Git to track all the files in the current directory. Once you’ve added files to the repository, you can check the status of your files using the git status command:

You can see in the output that the files hello_terminal.py and .gitignore are added and ready to be committed:

With the git commit command, you take a snapshot of the current state of your files and store it in the repository’s history. The -m flag allows you to include a message describing your changes. The output shows the branch that you’re on and the number of files changed.

After you commit any changes, it’s a good idea to check the status of your Git repository again:

You can see in the output that there’s nothing to commit, meaning that all changes have been successfully committed.

The workflow that you used in this section is typical when you use Git in the terminal. You use the git add command to tell Git which files to track. Then you use git commit to take a snapshot of the current state of your files and save it to the repository’s history.

Additionally, it’s good practice to use git status often to check the current status of your repository.

While you’ve gotten an introduction to using Git in the terminal, there’s much more that Git has to offer you as a Python developer. If you’re interested in learning more about Git, then you can check out the introduction to Git and GitHub for Python developers and dive even deeper with advanced Git tips for Python developers.

Next Steps

The more you use the terminal, the more comfortable you’ll get. A fun way to introduce the terminal into your workflows as a Python developer is to create Python scripts with command-line interfaces. For example, you can build a:

Especially for a Python developer, knowing how to work with the terminal can be extremely useful for various reasons. Besides using pip and Git to manage your Python projects, there are even more examples of when the terminal comes in handy:

  • Command-line interfaces: Many popular Python libraries and frameworks—such as Django, Flask, and Poetry—come with command-line interfaces that allow you to perform tasks such as creating new projects, running development servers, and managing databases.
  • Automation and scripting: The terminal allows you to automate repetitive tasks and create scripts to manage your development workflow—for example, running tests or deploying your application.
  • Debugging: The terminal can be useful for debugging your code. For instance, you can use print() or logging in Python to show output in the terminal and understand what’s happening in your code. You can also use pdb for debugging your Python code.
  • Performance: Many command-line tools are faster than their GUI counterparts and ideal for working with large datasets or performing advanced tasks such as data processing and analysis.

Overall, the terminal is a powerful tool that can help you streamline your development workflow, automate tasks, debug your code, and access advanced features of libraries and frameworks. With practice, you’ll find the terminal an invaluable tool for your journey as a Python developer.

Conclusion

When you’re comfortable using the terminal, then you’ll probably be able to navigate your file system faster and with more control than when using your mouse and clicking buttons.

In this tutorial, you’ve learned how to:

  • Find the terminal on your operating system
  • Open the terminal for the first time
  • Navigate your file system with basic commands
  • Create files and folders with the terminal
  • Manage packages with pip commands
  • Keep track of your files with Git in the terminal

You’ve boosted your programming skills by learning how to do three really important tasks in the terminal: navigate the file system, manage Python packages with pip , and make commits to Git. Learning terminal commands is a great investment for you as a Python developer. Just take your time and get to know this powerful tool step by step. Soon enough, it’ll be an important tool in your repertoire that you can’t live without.

How important is the terminal for your workflow as a Python developer? Are there any essential commands that you would add to the tutorial? Let the Real Python community know in the comments below!

Free Download: Click here to get a free cheat sheet of useful commands to get you started working with the terminal.

Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Using the Terminal on Windows

Get a short & sweet Python Trick delivered to your inbox every couple of days. No spam ever. Unsubscribe any time. Curated by the Real Python team.

Python Tricks Dictionary Merge

About Philipp Acsany

Philipp is a Berlin-based software engineer with a graphic design background and a passion for full-stack web development.

Each tutorial at Real Python is created by a team of developers so that it meets our high quality standards. The team members who worked on this tutorial are:

Aldren Santos

Geir Arne Hjelle

Ian Currie

Kate Finegan

Martin Breuss

Master Real-World Python Skills With Unlimited Access to Real Python

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

Master Real-World Python Skills
With Unlimited Access to Real Python

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

What Do You Think?

What’s your #1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment below and let us know.

Commenting Tips: The most useful comments are those written with the goal of learning from or helping out other students. Get tips for asking good questions and get answers to common questions in our support portal. Looking for a real-time conversation? Visit the Real Python Community Chat or join the next “Office Hours” Live Q&A Session. Happy Pythoning!

В этой главе вы запустите свою первую программу на языке Python, hello_world.py. Сначала вы проверите, установлен ли Python на вашем компьютере, и если нет — установите его. Также будет установлен текстовый редактор для подготовки программ Python. Текстовые редакторы распознают код Python и выделяют синтаксические конструкции во время работы, упрощая понимание структуры кода разработчиком.

Подготовка среды программирования

Поддержка Python слегка отличается в разных операционных системах, поэтому вы должны учитывать некоторые аспекты. В этой главе представлены две основные версии Python, используемые в наше время, и описаны основные действия по настройке Python в вашей системе.

Python 2 и Python 3

Сейчас доступны две версии Python: Python 2 и более новая версия Python 3. Каждый язык программирования развивается с появлением новых идей и технологий, и разработчики Python неустанно трудятся над тем, чтобы сделать язык более мощным и гибким. Многие изменения имеют второстепенный характер и малозаметны на первый взгляд, но в отдельных случаях код, написанный на Python 2, некорректно работает в системах с установленной поддержкой Python 3. В книге я буду указывать на существенные различия между Python 2 и Python 3, так что вы сможете следовать приведенным инструкциям независимо от используемой версии.

Если в вашей системе установлены обе версии или вы еще не установили Python, используйте Python 3. Если в вашей системе установлена только версия Python 2 и вы предпочитаете с ходу взяться за написание кода, не желая возиться с установкой, начните с Python 2. Но чем скорее вы перейдете на Python 3, тем лучше — все же полезнее использовать самую новую версию.

Выполнение фрагментов кода Python

В поставку Python входит интерпретатор, который выполняется в терминальном окне и позволяет опробовать фрагменты кода Python без сохранения и запуска всей программы.

В этой книге встречаются фрагменты следующего вида:

(1) >>> print(«Hello Python interpreter!»)

Hello Python interpreter!

Жирным шрифтом выделен текст, который вы вводите и выполняете нажатием клавиши Enter. Большинство примеров в книге представляет собой небольшие самостоятельные программы, которые запускаются из редактора, потому что именно так вы будете писать бульшую часть своего кода. Но в некоторых случаях базовые концепции будут проиллюстрированы серией фрагментов в терминальном сеансе Python для более эффективной демонстрации отдельных концепций. Каждый раз, когда в листинге встречаются три угловые скобки (1) , это означает, что перед вами вывод терминального сеанса. Вскоре мы опробуем возможность программирования в интерпретаторе для вашей системы.

В мире программирования издавна принято начинать освоение нового языка с программы, выводящей на экран сообщение Hello world! — считается, что это приносит удачу.

На языке Python программа Hello World состоит всего из одной строки:

Даже такая простая программа выполняет вполне конкретную функцию. Если она запускается в вашей системе, то и любая программа, которую вы напишете на Python, тоже должна запускаться нормально. О том, как написать эту программу для вашей конкретной системы, мы поговорим чуть ниже.

Python в разных операционных системах

Python является кросс-платформенным языком программирования; это означает, что он работает во всех основных операционных системах. Любая программа на языке Python, написанная вами, должна выполняться на любом современном компьютере с установленной поддержкой Python. Впрочем, способы настройки Python для разных операционных систем слегка отличаются.

В этом разделе вы узнаете, как подготовить Python к работе и запустить программу Hello World в вашей системе. Сначала вы проверите, установлена ли поддержка Python в вашей системе, и если нет — установите ее. Затем вы установите простой текстовый редактор и сохраните пустой файл Python с именем hello_world.py. Наконец, вы запустите программу Hello World и устраните любые неполадки. Этот процесс будет описан для всех операционных систем, так что в итоге в вашем распоряжении появится простая и удобная среда программирования на Python.

Python в системе Linux

Системы семейства Linux ориентированы на программистов, поэтому поддержка Python уже установлена на большинстве компьютеров Linux. Люди, которые ­занимаются разработкой и сопровождением Linux, ожидают, что в какой-то момент вы займетесь программированием, и всячески способствуют этому. По этой причине для перехода к программированию вам почти ничего не придется устанавливать, а количество необходимых настроек будет минимальным.

Проверка версии Python

Откройте терминальное окно, запустив приложение Terminal в вашей системе (в Ubuntu нажмите клавиши Ctrl+Alt+T). Чтобы проверить, установлена ли поддержка Python в вашей системе, введите команду python (со строчной буквы p). На экране появится информация о том, какая версия Python у вас установлена, и приглашение >>>, в котором можно вводить команды Python:

Python 2.7.6 (default, Mar 22 2014, 22:59:38)

[GCC 4.8.2] on linux2

Type «help», «copyright», «credits» or «license» for more information.

Этот вывод сообщает, что Python 2.7.6 в настоящее время является версией Python по умолчанию, установленной на данном компьютере. Нажмите Ctrl+D или введите exit(), чтобы выйти из приглашения Python и вернуться к приглашению терминала.

Чтобы проверить наличие Python 3, возможно, вам придется указать эту версию; итак, даже при том, что в качестве версии по умолчанию в выходных данных указан Python 2.7, попробуйте ввести команду python3:

Python 3.5.0 (default, Sep 17 2015, 13:05:18)

[GCC 4.8.4] on linux

Type «help», «copyright», «credits» or «license» for more information.

Из выходных данных видно, что в системе также установлена версия Python 3, так что вы сможете использовать любую из этих версий. Каждый раз, когда вы встречаете команду python в этой книге, вводите вместо нее команду python3. В большинстве дистрибутивов Linux поддержка Python уже установлена, но, если по какой-то причине в вашей системе ее нет или ваша система была укомплектована Python 2, а вы хотите установить Python 3, обращайтесь к приложению А.

Установка текстового редактора

Geany — простой и удобный текстовый редактор; он легко устанавливается, позволяет запускать практически любые программы прямо из редактора (вместо терминала) и использует цветовое выделение синтаксиса, а код выполняется в терминальном окне. В приложении Б приведена информация о других текстовых редакторах, но я рекомендую использовать Geany, если только у вас нет веских причин для работы в другом редакторе.

В большинстве систем Linux установка Geany выполняется одной строкой:

$ sudo apt-get install geany

Если команда не работает, обращайтесь к инструкциям по адресу http://geany.org/Download/ThirdPartyPackages/.

Запуск программы Hello World

Чтобы запустить свою первую программу, откройте Geany. Нажмите клавишу Super (она также часто называется клавишей Windows) и найдите Geany в вашей системе. Создайте ярлык, перетащив значок на панель задач или рабочий стол. Создайте папку для своих проектов и присвойте ей имя python_work. (В именах файлов и папок лучше использовать буквы нижнего регистра и символы подчеркивания, потому что это соответствует соглашениям об именах Python.) Вернитесь к Geany и сохраните пустой файл Python (File—>Save As) с именем hello_world.py в папке python_work. Расширение .py сообщает Geany, что файл содержит программу Python. Оно также подсказывает Geany, как следует запускать программу и как правильно выделить элементы синтаксиса.

После того как файл будет сохранен, введите следующую строку:

print(«Hello Python world!»)

Если в системе установлено несколько версий Python, проследите за тем, чтобы в Geany была настроена правильная версия. Откройте окно Build—>Set Build Commands. В окне приведены команды Compile и Execute, рядом с каждой из которых располагается команда. Geany предполагает, что правильной командой в каждом случае является python, но, если в системе должна использоваться команда python3, настройку необходимо изменить.

Если команда python3 работала в терминальном сеансе, измените команды Compile и Execute так, чтобы в Geany использовался интерпретатор Python 3. Команда Compile должна выглядеть так:

python3 -m py_compile «%f»

Команда должна быть введена точно в таком виде без малейших изменений. Проследите за правильностью регистра символов и расстановки пробелов.

Команда Execute должна выглядеть так:

И снова тщательно проверьте пробелы и регистр символов. На рис. 1.1 показано, как эти команды должны выглядеть в меню конфигурации Geany.

Теперь выполните программу hello_world.py: выберите команду меню Build—>Execute, щелкните на кнопке Execute (с шестеренками) или нажмите клавишу F5.

На экране появляется терминальное окно со следующим выводом:

Hello Python world!

(program exited with code: 0)

Press return to continue

Если вы не увидели это сообщение, проверьте каждый символ во введенной строке. Может, вы случайно набрали print с прописной буквы? Пропустили одну или обе

Рис. 1.1. Настройка Geany для использования Python 3 в Linux

кавычки или круглые скобки? В языках программирования используется предельно конкретный синтаксис, и при малейшем его нарушении произойдет ошибка. Если программа так и не заработала, обращайтесь к разделу «Решение проблем с установкой» на с. 28.

Запуск Python в терминальном сеансе

Для выполнения фрагментов кода Python можно открыть терминальное окно и ввести команду python или python3, как мы поступили при проверке версии. Сделайте то же самое, но на этот раз введите в терминальном сеансе следующую строку:

>>> print(«Hello Python interpreter!»)

Hello Python interpreter!

Сообщение выводится прямо в текущем терминальном окне. Вспомните, что интерпретатор Python закрывается комбинацией клавиш Ctrl+D или командой exit().

Python в системе OS X

В большинстве систем OS X поддержка Python уже установлена. Даже если вы уверены в том, что Python устанавливать не нужно, вам придется установить текстовый редактор и убедиться в том, что он правильно настроен.

Проверка наличия Python

Откройте терминальное окно (команда Applications—>Utilities—>Terminal). Также можно нажать Command+пробел, ввести terminal и нажать Enter. Чтобы проверить, установлена ли поддержка Python в вашей системе, введите команду python (со строчной буквы p). На экране появится информация о том, какая версия Python у вас установлена, и приглашение >>>, в котором можно вводить команды Python:

Python 2.7.5 (default, Mar 9 2014, 22:15:05)

[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin

Type «help», «copyright», «credits», or «license» for more information.

Этот вывод сообщает, что Python 2.7.5 в настоящее время является версией Python по умолчанию, установленной на данном компьютере. Нажмите Ctrl+D или введите exit(), чтобы выйти из приглашения Python и вернуться к приглашению терминала.

Чтобы проверить наличие Python 3, попробуйте ввести команду python3. На экране может появиться сообщение об ошибке, но, если из вывода следует, что версия Python 3 в вашей системе установлена, вы сможете использовать ее без необходимости установки. Если команда python3 работает в вашей системе, каждый раз, когда вы встречаете команду python в этой книге, вводите вместо нее команду python3. Если по какой-то причине в вашей системе нет Python или ваша система была укомплектована Python 2, а вы хотите установить Python 3, обращайтесь к приложению А.

Запуск Python в терминальном сеансе

Для выполнения фрагментов кода Python можно открыть терминальное окно и ввести команду python или python3, как мы поступили при проверке версии. Сделайте то же самое, но на этот раз введите в терминальном сеансе следующую строку:

>>> print(«Hello Python interpreter!»)

Hello Python interpreter!

Сообщение выводится прямо в текущем терминальном окне. Вспомните, что интерпретатор Python закрывается комбинацией клавиш Ctrl+D или командой exit().

Установка текстового редактора

Sublime Text — простой и удобный текстовый редактор; он легко устанавливается в OS X, позволяет запускать практически любые программы прямо из редактора (вместо терминала) и использует цветовое выделение синтаксиса, а код выполняется в терминальном окне, встроенном в окно Sublime Text. В приложении Б приведена информация о других текстовых редакторах, но я рекомендую использовать Sublime Text, если только у вас нет веских причин для работы в другом редакторе.

Программу установки Sublime Text можно загрузить по адресу http://sublimetext.com/3. Щелкните на ссылке загрузки и найдите программу установки для OS X. Политика лицензирования Sublime Text более чем либеральна: вы можете бесплатно пользоваться редактором сколь угодно долго, но автор требует приобрести лицензию, если программа вам понравилась и вы собираетесь использовать ее в будущем. После того как программа установки будет загружена, откройте ее и перетащите значок Sublime Text в папку Applications.

Настройка Sublime Text для Python 3

Если для запуска терминального сеанса Python вместо python используется другая команда, вам придется настроить Sublime Text, чтобы программа знала, где найти правильную версию Python в вашей системе. Чтобы узнать полный путь к интерпретатору Python, введите следующую команду:

python3 is /usr/local/bin/python3

Теперь откройте Sublime Text и выберите команду Tools—>Build System—>New Build System. Команда открывает новый конфигурационный файл. Удалите его текущее содержимое и введите следующий код:

. .»cmd»: [«/usr/local/bin/python3», «-u», «$file»],

Этот код приказывает Sublime Text использовать команду python3 вашей системы для запуска текущего открытого файла. Проследите за тем, чтобы в коде использовался путь, полученный при выполнении команды type -a python3 на предыдущем шаге. Сохраните файл с именем Python3.sublime-build в каталоге по умолчанию, который Sublime Text открывает при выполнении команды Save.

Запуск программы Hello World

Чтобы запустить свою первую программу, запустите Sublime Text — откройте папку Applications и сделайте двойной щелчок на значке Sublime Text. Также можно нажать Command+пробел и ввести sublime text в открывшейся панели поиска.

Создайте для своих проектов папку с именем python_work. (В именах файлов и папок лучше использовать буквы нижнего регистра и символы подчеркивания, потому что это соответствует соглашениям об именах Python.) Сохраните пустой файл Python (File—>Save As) с именем hello_world.py в папке python_work. Расширение .py сообщает Sublime Text, что файл содержит программу Python. Оно также подсказывает Sublime Text, как следует запускать программу и как правильно выделить элементы синтаксиса.

После того как файл будет сохранен, введите следующую строку:

print(«Hello Python world!»)

Если команда python работает в вашей системе, программу можно запустить ­командой меню Tools—>Build или комбинацией клавиш Ctrl+B. Если вы настроили Sublime Text на использование другой команды вместо python, выберите команду меню Tools—>Build System, а затем Python 3. Тем самым вы назначаете Python 3 версией Python по умолчанию, и в дальнейшем программы можно будет запускать командой Tools—>Build или комбинацией клавиш Command+B.

Терминальное окно должно отображаться в нижней части окна Sublime Text со следующим текстом:

Hello Python world!

[Finished in 0.1s]

Если вы не увидели это сообщение, проверьте каждый символ во введенной строке. Может, вы случайно набрали print с прописной буквы? Пропустили одну или обе кавычки или круглые скобки? В языках программирования используется предельно конкретный синтаксис, и при малейшем его нарушении произойдет ошибка. Если программа так и не заработала, обращайтесь к разделу «Решение проблем с установкой» на с. 28.

Python в системе Windows

Windows далеко не всегда включает поддержку Python. Скорее всего, вам придется загрузить и установить Python, а затем загрузить и установить текстовый редактор.

Для начала проверьте, установлена ли поддержка Python в вашей системе. ­Откройте окно командной строки: введите command в меню Пуск или щелкните на ­рабочем столе с нажатой клавишей Shift и выберите команду Open command window here. Введите в окне командной строки команду python в нижнем регистре.

Рис. 1.2. Не забудьте установить флажок Add Python to PATH

Если на экране появится приглашение >>>, значит, в системе установлена поддержка Python. Впрочем, скорее всего вместо приглашения появится сообщение об ошибке, в котором говорится, что команда python не опознана системой.

В таком случае загрузите программу установки Python для Windows. Откройте страницу http://python.org/downloads/. Вы увидите на ней две кнопки: для загрузки Python 3 и для загрузки Python 2. Щелкните на кнопке Python 3, которая запускает автоматическую загрузку правильного установочного пакета для вашей системы. После того как загрузка файла будет завершена, запустите программу установки. Не забудьте установить флажок Add Python to PATH — это упростит правильную настройку системы. На рис. 1.2 изображено окно мастера установки с активным флажком.

Запуск терминального сеанса

Настроить текстовый редактор будет несложно, если вы сначала подготовите систему к запуску Python в терминальном сеансе. Откройте окно командной строки и введите команду python в нижнем регистре. Если на экране появится приглашение Python (>>>), значит, система Windows обнаружила установленную версию Python:

Python 3.5.0 (v3.5.0:374f501f4567, Sep 13 2015, 22:15:05) [MSC v.1900 32 bit

Type «help», «copyright», «credits» or «license» for more information.

Если команда сработала, переходите к следующему разделу «Запуск Python в терминальном сеансе».

Однако вывод может выглядеть и так:

‘python’ is not recognized as an internal or external command, operable

program or batch file.

В этом случае необходимо сообщить Windows, как найти свежеустановленную версию Python. Команда python в вашей системе обычно хранится на диске C; запустите Проводник Windows и откройте диск C. Найдите папку, имя которой начинается с Python, откройте ее и найдите файл python (в нижнем регистре). Например, на моем компьютере существует папка Python35, в которой находится файл с именем python, поэтому путь к команде python в вашей системе имеет вид C:\Python35\python. Если найти файл не удалось, введите строку python в поле поиска в Проводнике Windows — система поиска покажет, где именно хранится команда python в вашей системе.

Когда вы решите, что знаете путь к команде, проверьте его: введите этот путь в терминальном окне. Откройте окно командной строки и введите только что найденный полный путь:

Python 3.5.0 (v3.5.0:374f501f4567, Sep 13 2015, 22:15:05) [MSC v.1900 32 bit

Type «help», «copyright», «credits» or «license» for more information.

Если команда успешно работает, то вы знаете, как запустить Python в вашей системе.

Запуск Python в терминальном сеансе

Введите в терминальном сеансе следующую строку и убедитесь в том, что на экране появился вывод Hello Python world!:

>>> print(«Hello Python world!»)

Hello Python interpreter!

Каждый раз, когда вы захотите выполнить фрагмент кода Python, откройте окно командной строки и запустите терминальный сеанс Python. Чтобы закрыть терминальный сеанс, нажмите Ctrl+Z или введите команду exit().

Установка текстового редактора

Geany — простой и удобный текстовый редактор; он легко устанавливается, позволяет запускать практически любые программы прямо из редактора (вместо терминала) и использует цветовое выделение синтаксиса, а код выполняется в терминальном окне. В приложении Б приведена информация о других текстовых редакторах, но я рекомендую использовать Geany, если только у вас нет веских причин для работы в другом редакторе.

Программу установки Geany для Windows можно загрузить по адресу http://geany.org/. Щелкните в строке Releases меню Download и найдите пакет geany-1.25_setup.exe (или что-нибудь в этом роде). Запустите программу и подтвердите все значения по умолчанию.

Чтобы запустить свою первую программу, откройте Geany: нажмите клавишу Windows и найдите Geany в вашей системе. Создайте ярлык, перетащив значок на панель задач или рабочий стол. Создайте папку для своих проектов и присвойте ей имя python_work. (В именах файлов и папок лучше использовать буквы нижнего регистра и символы подчеркивания, потому что это соответствует соглашениям об именах Python.) Вернитесь к Geany и сохраните пустой файл Python (File—>Save As) с именем hello_world.py в папке python_work. Расширение .py сообщает Geany, что файл содержит программу Python. Оно также подсказывает Geany, как следует запускать программу и как правильно выделить элементы синтаксиса.

После того как файл будет сохранен, введите следующую строку:

print(«Hello Python world!»)

Если команда python успешно сработала в вашей системе, то дополнительная настройка Geany не нужна; пропустите следующий раздел и переходите к разделу «Запуск программы Hello World» на с. 28. Если для запуска интерпретатора Python пришлось вводить полный путь вида C:\Python35\python, выполните инструкции по настройке Geany для вашей системы, приведенные в следующем разделе.

Чтобы настроить Geany для работы с Python, откройте окно Build—>Set Build Commands. В окне приведены команды Compile и Execute, рядом с каждой из которых располагается команда. Команды Compile и Execute начинаются с команды python, записанной символами нижнего регистра, но Geany не знает, где в вашей системе находится исполняемый файл python. К команде нужно добавить путь, который вы ввели в окне командной строки.

Добавьте в начало команд Compile и Execute диск и путь к папке, в которой находится файл. Команда Compile должна выглядеть примерно так:

C:\Python35\python -m py_compile «%f»

Возможно, в вашей системе путь будет выглядеть немного иначе; проследите за правильностью регистра символов и расстановки пробелов.

Рис. 1.3. Настройка Geany для использования Python 3 в Windows

Команда Execute должна выглядеть примерно так:

И снова внимательно проверьте пробелы и регистр символов. На рис. 1.3 показано, как эти команды должны выглядеть в меню конфигурации Geany.

Завершив настройку команд, нажмите кнопку OK.

Запуск программы Hello World

Все должно быть готово для успешного выполнения программы. Запустите программу hello_world.py: выберите команду меню Build—>Execute, щелкните на кнопке Execute (с шестеренками) или нажмите клавишу F5. На экране появляется терминальное окно со следующим выводом:

Hello Python world!

(program exited with code: 0)

Press return to continue

Если вы не увидели это сообщение, проверьте каждый символ во введенной строке. Может, вы случайно набрали print с прописной буквы? Пропустили одну или обе кавычки или круглые скобки? В языках программирования используется предельно конкретный синтаксис, и при малейшем его нарушении произойдет ошибка. Если программа так и не заработала, возможно, следующий раздел поможет вам в этом.

Решение проблем с установкой

Хочется надеяться, что вы успешно настроили среду разработки на своем компьютере. Но если вам так и не удалось запустить программу hello_world.py, возможно, вам помогут следующие полезные советы.

• Если программа содержит серьезную ошибку, Python выводит данные трассировки. Python анализирует содержимое файла и пытается составить отчет о проблеме. Возможно, трассировка подскажет, что именно мешает выполнению программы.

• Отойдите от компьютера, отдохните и попробуйте снова. Помните, что синтаксис в программировании очень важен: даже пропущенное двоеточие, неверно расположенная кавычка или непарная скобка могут помешать нормальной работе программы. Перечитайте соответствующие части главы, еще раз проанализируйте, что было сделано, и попробуйте найти ошибку.

• Начните заново. Вероятно, ничего переустанавливать не придется, но хотя бы попробуйте удалить файл hello_world.py и создать его «с нуля».

• Попросите кого-нибудь повторить действия, описанные в этой главе, на вашем (или на другом) компьютере. Внимательно понаблюдайте за происходящим. Возможно, вы упустили какую-нибудь мелочь, которую заметят другие.

• Найдите специалиста, хорошо знающего Python, и попросите его помочь. Вполне может оказаться, что такой специалист есть среди ваших знакомых.

• Инструкции по настройке среды программирования, приведенные в этой главе, также доступны по адресу https://www.nostarch.com/pythoncrashcourse/. Возможно, сетевая версия будет для вас более удобной.

• Обратитесь за помощью в Интернет. В приложении В перечислены некоторые ресурсы (форумы, чаты и т.д.), где вы сможете проконсультироваться у людей, уже сталкивавшихся с вашей проблемой.

Не стесняйтесь обращаться к опытным программистам. Любой программист в какой-то момент своей жизни заходил в тупик; многие программисты охотно помогут вам правильно настроить вашу систему. Если вы сможете четко объяснить, что вы хотите сделать, что уже пытались и какие результаты получили, скорее всего, кто-нибудь вам поможет. Как упоминалось во введении, сообщество Python доброжелательно относится к новичкам.

Python должен нормально работать на любом современном компьютере, и если у вас все же возникли проблемы — обращайтесь за помощью. На первых порах проблемы могут быть весьма неприятными, но с ними стоит разобраться. Когда программа hello_world.py заработает, вы сможете приступить к изучению Python, а ваша работа станет намного более интересной и принесет больше удовольствия.

Запуск программ Python в терминале

Большинство программ, написанных вами в текстовом редакторе, ­будут запускаться прямо из редактора. Тем не менее иногда бывает полезно запускать программы из терминала — например, если вы хотите просто выполнить готовую программу, не открывая ее для редактирования.

Это можно сделать в любой системе с установленной поддержкой Python; необходимо лишь знать путь к каталогу, в котором хранится файл программы. Приведенные ниже примеры предполагают, что вы сохранили файл hello_world.py в папке python_work на рабочем столе.

Запуск программы Python в терминальном сеансе в системах Linux и OS X осуществляется одинаково. Команда cd (Change Directory) используется для перемещения по файловой системе в терминальном сеансе. Команда ls (LiSt) выводит список всех не-скрытых файлов в текущем каталоге. Откройте новое терминальное окно и введите следующие команды для запуска программы hello_world.py:

/Desktop/python_work$ python hello_world.py

. .Hello Python world!

Команда cd используется для перехода к папке python_work, находящейся в ­папке Desktop (1) . Затем команда ls проверяет, что файл hello_world.py действительно ­находится в этой папке (2). Далее файл запускается командой python hello_world.py (3).

Как видите, все просто. По сути вы просто используете команду python (или python3) для запуска программ Python.

Команда cd (Change Directory) используется для перемещения по файловой системе в окне командной строки. Команда dir (DIRectory) выводит список всех файлов в текущем каталоге.

Откройте новое терминальное окно и введите следующие команды для запуска программы hello_world.py:

(1) C:\> cd Desktop\python_work

(3)C:\Desktop\python_work> python hello_world.py

. .Hello Python world!

Команда cd используется для перехода к папке python_work, находящейся в папке Desktop (1) . Затем команда dir проверяет, что файл hello_world.py действительно находится в этой папке (2). Далее файл запускается командой python hello_world.py (3).

Если вы еще не настроили свою систему для использования простой команды python, возможно, вам придется использовать более длинную версию этой команды:

C:\$ cd Desktop\python_work

C:\Desktop\python_work$ C:\Python35\python hello_world.py

Hello Python world!

В основном ваши программы будут нормально запускаться прямо из редактора. Со временем ваша работа станет более сложной, и может оказаться, что какие-то программы придется запускать в режиме терминала.

Упражнения этой главы в основном направлены на самостоятельный поиск информации. Начиная с главы 2, упражнения будут ориентированы на решение задач по изложенному материалу.

1-1. Python.org: изучите домашнюю страницу Python (http://python.org/) и найдите темы, которые вас заинтересуют. Со временем вы лучше узнаете Python, и другие разделы этого сайта покажутся вам более полезными.

1-2. Опечатки в Hello World: откройте только что созданный файл hello_world.py. Сделайте где-нибудь намеренную опечатку и снова запустите программу. Удастся ли вам сделать опечатку, которая приводит к ошибке? Поймете ли вы смысл сообщения об ошибке? Удастся ли вам сделать опечатку, которая не приводит к ошибке? Как вы думаете, почему на этот раз выполнение обходится без ­ошибки?

1-3. Бесконечное мастерство: если бы вы были программистом с неограниченными возможностями, за какой проект вы бы взялись? Вы сейчас учитесь программировать. Если у вас имеется ясное представление о конечной цели, вы сможете немедленно применить свои новые навыки на практике; попробуйте набросать общие описания тех программ, над которыми вам хотелось бы поработать. Заведите «блокнот идей», к которому вы сможете обращаться каждый раз, когда вы собираетесь начать новый проект. Выделите пару минут и составьте описания трех программ, которые вам хотелось бы создать.

Run Python Script – How to Execute Python Shell Commands in the Terminal

Suchandra Datta Suchandra Datta

Run Python Script – How to Execute Python Shell Commands in the Terminal

When you’re starting out learning a new programming language, your very first program is likely to be one that prints «hello world!».

Let’s say you want to do this in Python. There are two ways of doing it: using the Python shell or writing it as a script and running it in the terminal.

What is a Shell?

An operating system is made up of a bunch of programs. They perform tasks like file handling, memory management, and resource management, and they help your applications run smoothly.

All the work we do on computers, like analyzing data in Excel or playing games, is facilitated by the operating system.

Operating system programs are of two types, called shell and kernel programs.

Kernel programs are the ones who perform the actual tasks, like creating a file or sending interrupts. Shell is another program, whose job is to take input and decide and execute the required kernel program to do the job and show the output.

The shell is also called the command processor.

What is a Terminal?

The terminal is the program that interacts with the shell and allows us to communicate with it via text-based commands. This is why it’s also called the command line.

To access the terminal on Windows, hit the Windows logo + R, type cmd, and press Enter.

To access the terminal on Ubuntu, hit Ctrl + Alt + T.

What is the Python Shell?

Python is an interpreted language. This means that the Python interpreter reads a line of code, executes that line, then repeats this process if there are no errors.

The Python Shell gives you a command line interface you can use to specify commands directly to the Python interpreter in an interactive manner.

You can get a lot of detailed information regarding the Python shell in the official docs.

How to Use the Python Shell

To start the Python shell, simply type python and hit Enter in the terminal:

The interactive shell is also called REPL which stands for read, evaluate, print, loop. It’ll read each command, evaluate and execute it, print the output for that command if any, and continue this same process repeatedly until you quit the shell.

There are different ways to quit the shell:

  • you can hit Ctrl+Z on Windows or Ctrl+D on Unix systems to quit
  • use the exit() command
  • use the quit() command

What Can You Do in the Python Shell?

You can do pretty much everything that the Python language allows, from using variables, loops, and conditions to defining functions and more.

The >>> is the shell prompt where you type in your commands. If you have commands that span across several lines – for example when you define loops – the shell prints the . characters which signifies that a line continues.

Let’s see an example:

Here we defined a list with some TV show names via the Python shell.

Next, let’s define a function that accepts a list of shows and randomly returns a show:

Note the continuation lines ( . ) of the Python shell here.

Finally to invoke the function from the shell, you simply call the function the way you would do in a script:

You can inspect Python modules from the shell, as shown below:

You can see what methods and attributes a module offers by using the dir() method:

Here you can see that Numpy has 606 methods and properties in total.

How to Run Python Scripts

The Python shell is useful for executing simple programs or for debugging parts of complex programs.

But really large Python programs with a lot of complexity are written in files with a .py extension, typically called Python scripts. Then you execute them from the terminal using the Python command.

The usual syntax is:

All the commands we executed previously via the shell, we can also write it in a script and run in this way.

Conclusion

In this article, we learnt about the shell, terminal, how to use the Python shell. We also saw how to run Python scripts from the command line.

I hope this article helps you understand what the Python shell is and how you can use it in your day to day lives. Happy learning!

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *