Как запустить скрипт на Python
Начинающий разработчик на Python, помимо синтаксиса и основных правил использования операторов этого языка, должен уметь запускать код на исполнение. Ведь только так можно понять, работает ли написанный вами скрипт, или в нем содержатся ошибки. Рассмотрим подробнее, как можно запустить скрипты в терминале операционной системы, в интегрированной среде разработки или просто из интерфейса ОС. Это позволит вам выбрать подходящий вариант и повысить эффективность своей работы.
Интерпретатор Python
Рассматриваемый язык программирования является одним из самых прогрессивных на текущий момент. Он позволяет быстро и эффективно решать задачи в самых разных областях. Однако под термином Python понимают также интерпретатор, то есть программу на компьютере, которая позволяет запускать на исполнение написанные скрипты. Она представляет собой дополнительный программный слой между аппаратным обеспечением ПК и кодом.
Существует несколько интерпретаторов:
- написанные на языке программирования С;
- написанные на языке программирования Java;
- написанные на языке Python;
- программы, реализованные в среде .NET.
Выбор конкретного варианта для конечного пользователя значения не имеет. Независимо от вида программы, написанный код будет выполняться именно так, как предусмотрено правилами этого языка.
Запуск возможен двумя способами: как готовая к использованию программная последовательность (скрипт или модуль) или как отдельные куски кода, которые вводятся прямо в окно программы.
Интерактивный запуск кода
Для тестирования отдельных команд можно использовать интерпретатор в режиме интерактивного сеанса. Для этого необходимо открыть командную строку операционной системы и ввести команду, которая запускает интерпретатор.
Для ОС Linux это будет выглядеть следующим образом:
Теперь можно вводить команды, которые будут выполняться сразу после этого. Минус подобного подхода в том, что вся введенная последовательность не сохраняется после закрытия текущей сессии.
Интерактивное исполнение кода необходимо для того, чтобы немедленно протестировать фрагмент написанного кода. Кроме того, его можно использовать в процессе обучения для проверки действий тех или иных операторов «на лету». Этот способ интерпретации команд позволяет попробовать нужные вам функции языка, не прибегая к написанию отдельных скриптов для этого.
Выйти из интерактивного режима можно с помощью команды quit(), или просто закрыв окно терминала в Windows.
Для открытия терминала или командной строки перед запуском самого интерпретатора необходимо:
- В Windows нажать комбинацию клавиш «Флажок» + «R», после чего ввести команду cmd и нажать на кнопку «ОК» в диалоговом окне.
- В Linux или других подобных операционных системах доступ к командной строке предоставляется с помощью дополнительной программы. Можно использовать xterm или Konsole.
- В macOS для получения доступа к терминалу необходимо выбрать меню «Приложения», после чего перейти в раздел «Утилиты» и кликнуть на элементе «Терминал».
Как работает интерпретатор Python для скриптов
Запуск на исполнение написанных скриптов или модулей производится в пакетном режиме. И выполняется по сложной схеме, которая состоит из следующих этапов:
- Последовательная обработка всех операторов, которые записаны в скрипте.
- Компиляция исходного хода в промежуточный формат. Интерпретатор создает байт-код, который представляет собой язык программирования низкого уровня, независимый от платформы и операционной системы. Байт-код необходим для оптимизации процесса выполнения скрипта.
- Исполнение полученного кода. На этом этапе вступает в действие виртуальная машина Python (PVM), которая циклично перебирает каждый оператор из скрипта и запускает его на исполнение. Как будто вы вводите каждую команду последовательно в интерактивном интерпретаторе.
Запуск скриптов в командной строке
В интерактивном режиме, который обсуждался выше, можно записывать и выполнять любое количество строк кода. Но после закрытия окна терминала они не сохраняются. Поэтому реальные программы на Python пишутся в виде скриптов и представляют собой обычные текстовые файлы. Чтобы избежать путаницы при их хранении, им присваиваются расширения .py или .piw.
Создавать текстовый файл можно с помощью любого редактора, в том числе Notepad. Однако лучше использовать более продвинутые решения, например Sublime Text. Для примера возьмем наиболее простой скрипт, с которого начинается знакомство с любым языком программирования.
Файл можно сохранить в вашем рабочем каталоге с любым именем и расширением .py.
Чтобы запустить скрипт на исполнение, нужно использовать интерпретатор языка программирования и в качестве дополнительного параметра указать имя созданного вами файла.
В приведенном выше примере файл был назван «hello.py». После ввода команды нужно нажать клавишу «Ввод», и на экране появится результат работы скрипта. То есть надпись «Привет, Мир» или классическое английское «Hello World»!
Если файл с программой сохранен не в каталоге с интерпретатором, нужно указывать путь к нему.
Переназначение устройства вывода информации
При исполнении программного кода на Python иногда необходимо сохранять результаты, которые отображает на экране программа. Они в дальнейшем анализируются для поиска ошибок или других целей. В этом случае скрипт необходимо запускать следующей командой:
По результатам работы скрипта создается файл с именем output.txt, в который сохраняется все то, что должно было появиться на экране во время работы в программе. Это стандартный синтаксис, предусмотренный операционной системой.
Если файла с заданным именем не существует, ОС создает его автоматически. Если существует – данные в нем перезаписываются без сохранения предыдущих. В случае, когда есть необходимость в добавлении данных в конец текстового файла, вместо одного значка > необходимо указать два >>.
Прокачать навык программирования на Python и найти работу Junior Python разработчика помогут наши менторы Выбрать ментора
Запуск из командной строки без интерпретатора
В последних версиях операционной системы Windows добавлена возможность запускать скрипты на Python без ввода в командной строке названия программы-интерпретатора. То есть необходимо просто написать название файла с расширением.
Обусловлено это тем, что при клике на файле или запуске его из командной строки операционная система автоматически ищет связанное приложение и запускает его. Точно так же вы открываете файлы Word, просто кликнув на них курсором мыши.
В Unix таким образом тоже можно запускать скрипты. Однако для этого в первую строку текстового файла с командами необходимо добавить текст #!/Usr/bin/env python. Он указывает на программу, с помощью которой производится запуск. А интерпретатор языка программирования расценивает строку как комментарий и пропускает её.
Запуск скриптов из интерактивного режима
Находясь в интерактивном режиме (описан в первом разделе), пользователь может загрузить файл с написанной ранее последовательностью команд и запустить его на исполнение. Такой способ можно применять, когда модуль содержит вызовы функций, методов или других операторов, генерирующих текст на экране. В противном случае видимых результатов работы программы не будет.
Запустить скрипт из интерактивного режима можно командой:
Обратите внимание, что эта команда срабатывает один раз за интерактивный сеанс. Поэтому, если внести изменения в файл со скриптом и перезапустить его этой командой, ничего не произойдет.
Заключение
Теперь вы знаете, что команды и скрипты Python можно запускать разными способами и в разных режимах. Это позволит вам выбрать нужный вариант для решения конкретной задачи, увеличить скорость своей работы, сделать ее продуктивной и гибкой.
Running Python File in Terminal
Trying to learn how to run my scripts through Ubuntu’s terminal regularly. That being said I am familiar with bash , wget , and awk being called but how do I call python files to run in the terminal? I would like to learn this but I am unsure on where to research it. I have a .pyw file that references several .py files in a folder.
7 Answers 7
Option 1: Call the interpreter
- For Python 2: python <filename>.py
- For Python 3: python3 <filename>.py
Option 2: Let the script call the interpreter
- Make sure the first line of your file has #!/usr/bin/env python .
- Make it executable — chmod +x <filename>.py .
- And run it as ./<filename>.py
Just prefix the script’s filename with python . E.g.:
It’s also worth mentioning that by adding a -i flag after python , you can keep your session running for further coding. Like this:
pyw should run in the same manner, I think. You can also start an interactive console with just
Also, you can avoid having to invoke python explicitly by adding a shebang at the top of the script:
. or any number of variations thereof
First run following command
Then at the top of the script, add #! and the path of the Python interpreter:
If you would like the script to be independent of where the Python interpreter lives, you can use the env program. Almost all Unix variants support the following, assuming the Python interpreter is in a directory in the user’s $PATH :
Change directories using cd to the directory containing the .py and run one of the following two commands:
Alternatively run one of the following two commands:
Try using the command python3 instead of python . If the script was written in Python3, and you try to run it with Python2, you could have problems. Ubuntu has both; changing the program name to python3 (instead of replacing python ) made this possible. Ubuntu needs v2.7 (as of 2/16/2017) so DON’T delete or remove Python2, but keep them both. Make a habit of using Python3 to run scripts, which can run either.
How to Run Your Python Scripts
One of the most important skills you need to build as a Python developer is to be able to run Python scripts and code. This is going to be the only way for you to know if your code works as you planned. It’s even the only way of knowing if your code works at all!
This step-by-step tutorial will guide you through a series of ways to run Python scripts, depending on your environment, platform, needs, and skills as a programmer.
You’ll have the opportunity to learn how to run Python scripts by using:
- The operating system command-line or terminal
- The Python interactive mode
- The IDE or text editor you like best
- The file manager of your system, by double-clicking on the icon of your script
This way, you’ll get the knowledge and skills you’ll need to make your development cycle more productive and flexible.
Free Download: Get a sample chapter from Python Tricks: The Book that shows you Python’s best practices with simple examples you can apply instantly to write more beautiful + Pythonic code.
Take the Quiz: Test your knowledge with our interactive “How to Run Your Python Scripts” quiz. Upon completion you will receive a score so you can track your learning progress over time:
Scripts vs Modules
In computing, the word script is used to refer to a file containing a logical sequence of orders or a batch processing file. This is usually a simple program, stored in a plain text file.
Scripts are always processed by some kind of interpreter, which is responsible for executing each command sequentially.
A plain text file containing Python code that is intended to be directly executed by the user is usually called script, which is an informal term that means top-level program file.
On the other hand, a plain text file, which contains Python code that is designed to be imported and used from another Python file, is called module.
So, the main difference between a module and a script is that modules are meant to be imported, while scripts are made to be directly executed.
In either case, the important thing is to know how to run the Python code you write into your modules and scripts.
What’s the Python Interpreter?
Python is an excellent programming language that allows you to be productive in a wide variety of fields.
Python is also a piece of software called an interpreter. The interpreter is the program you’ll need to run Python code and scripts. Technically, the interpreter is a layer of software that works between your program and your computer hardware to get your code running.
Depending on the Python implementation you use, the interpreter can be:
- A program written in C, like CPython, which is the core implementation of the language
- A program written in Java, like Jython
- A program written in Python itself, like PyPy
- A program implemented in .NET, like IronPython
Whatever form the interpreter takes, the code you write will always be run by this program. Therefore, the first condition to be able to run Python scripts is to have the interpreter correctly installed on your system.
The interpreter is able to run Python code in two different ways:
- As a script or module
- As a piece of code typed into an interactive session
How to Run Python Code Interactively
A widely used way to run Python code is through an interactive session. To start a Python interactive session, just open a command-line or terminal and then type in python , or python3 depending on your Python installation, and then hit Enter .
Here’s an example of how to do this on Linux:
The standard prompt for the interactive mode is >>> , so as soon as you see these characters, you’ll know you are in.
Now, you can write and run Python code as you wish, with the only drawback being that when you close the session, your code will be gone.
When you work interactively, every expression and statement you type in is evaluated and executed immediately:
An interactive session will allow you to test every piece of code you write, which makes it an awesome development tool and an excellent place to experiment with the language and test Python code on the fly.
To exit interactive mode, you can use one of the following options:
- quit() or exit() , which are built-in functions
- The Ctrl + Z and Enter key combination on Windows, or just Ctrl + D on Unix-like systems
Note: The first rule of thumb to remember when using Python is that if you’re in doubt about what a piece of Python code does, then launch an interactive session and try it out to see what happens.
If you’ve never worked with the command-line or terminal, then you can try this:
On Windows, the command-line is usually known as command prompt or MS-DOS console, and it is a program called cmd.exe . The path to this program can vary significantly from one system version to another.
A quick way to get access to it is by pressing the Win + R key combination, which will take you to the Run dialog. Once you’re there, type in cmd and press Enter .
On GNU/Linux (and other Unixes), there are several applications that give you access to the system command-line. Some of the most popular are xterm, Gnome Terminal, and Konsole. These are tools that run a shell or terminal like Bash, ksh, csh, and so on.
In this case, the path to these applications is much more varied and depends on the distribution and even on the desktop environment you use. So, you’ll need to read your system documentation.
On Mac OS X, you can access the system terminal from Applications → Utilities → Terminal.
How Does the Interpreter Run Python Scripts?
When you try to run Python scripts, a multi-step process begins. In this process the interpreter will:
Process the statements of your script in a sequential fashion
Compile the source code to an intermediate format known as bytecode
This bytecode is a translation of the code into a lower-level language that’s platform-independent. Its purpose is to optimize code execution. So, the next time the interpreter runs your code, it’ll bypass this compilation step.
Strictly speaking, this code optimization is only for modules (imported files), not for executable scripts.
Ship off the code for execution
At this point, something known as a Python Virtual Machine (PVM) comes into action. The PVM is the runtime engine of Python. It is a cycle that iterates over the instructions of your bytecode to run them one by one.
The PVM is not an isolated component of Python. It’s just part of the Python system you’ve installed on your machine. Technically, the PVM is the last step of what is called the Python interpreter.
The whole process to run Python scripts is known as the Python Execution Model.
Note: This description of the Python Execution Model corresponds to the core implementation of the language, that is, CPython. As this is not a language requirement, it may be subject to future changes.
How to Run Python Scripts Using the Command-Line
A Python interactive session will allow you to write a lot of lines of code, but once you close the session, you lose everything you’ve written. That’s why the usual way of writing Python programs is by using plain text files. By convention, those files will use the .py extension. (On Windows systems the extension can also be .pyw .)
Python code files can be created with any plain text editor. If you are new to Python programming, you can try Sublime Text, which is a powerful and easy-to-use editor, but you can use any editor you like.
To keep moving forward in this tutorial, you’ll need to create a test script. Open your favorite text editor and write the following code:
Save the file in your working directory with the name hello.py . With the test script ready, you can continue reading.
Using the python Command
To run Python scripts with the python command, you need to open a command-line and type in the word python , or python3 if you have both versions, followed by the path to your script, just like this:
If everything works okay, after you press Enter , you’ll see the phrase Hello World! on your screen. That’s it! You’ve just run your first Python script!
If this doesn’t work right, maybe you’ll need to check your system PATH , your Python installation, the way you created the hello.py script, the place where you saved it, and so on.
This is the most basic and practical way to run Python scripts.
Redirecting the Output
Sometimes it’s useful to save the output of a script for later analysis. Here’s how you can do that:
This operation redirects the output of your script to output.txt , rather than to the standard system output ( stdout ). The process is commonly known as stream redirection and is available on both Windows and Unix-like systems.
If output.txt doesn’t exist, then it’s automatically created. On the other hand, if the file already exists, then its contents will be replaced with the new output.
Finally, if you want to add the output of consecutive executions to the end of output.txt , then you must use two angle brackets ( >> ) instead of one, just like this:
Now, the output will be appended to the end of output.txt .
Running Modules With the -m Option
Python offers a series of command-line options that you can use according to your needs. For example, if you want to run a Python module, you can use the command python -m <module-name> .
The -m option searches sys.path for the module name and runs its content as __main__ :
Note: module-name needs to be the name of a module object, not a string.
Using the Script Filename
On recent versions of Windows, it is possible to run Python scripts by simply entering the name of the file containing the code at the command prompt:
This is possible because Windows uses the system registry and the file association to determine which program to use for running a particular file.
On Unix-like systems, such as GNU/Linux, you can achieve something similar. You’ll only have to add a first line with the text #!/usr/bin/env python , just as you did with hello.py .
For Python, this is a simple comment, but for the operating system, this line indicates what program must be used to run the file.
This line begins with the #! character combination, which is commonly called hash bang or shebang, and continues with the path to the interpreter.
There are two ways to specify the path to the interpreter:
- #!/usr/bin/python : writing the absolute path
- #!/usr/bin/env python : using the operating system env command, which locates and executes Python by searching the PATH environment variable
This last option is useful if you bear in mind that not all Unix-like systems locate the interpreter in the same place.
Finally, to execute a script like this one, you need to assign execution permissions to it and then type in the filename at the command-line.
Here’s an example of how to do this:
With execution permissions and the shebang line properly configured, you can run the script by simply typing its filename at the command-line.
Finally, you need to note that if your script isn’t located at your current working directory, you’ll have to use the file path for this method to work correctly.
How to Run Python Scripts Interactively
It is also possible to run Python scripts and modules from an interactive session. This option offers you a variety of possibilities.
Taking Advantage of import
When you import a module, what really happens is that you load its contents for later access and use. The interesting thing about this process is that import runs the code as its final step.
When the module contains only classes, functions, variables, and constants definitions, you probably won’t be aware that the code was actually run, but when the module includes calls to functions, methods, or other statements that generate visible results, then you’ll witness its execution.
This provides you with another option to run Python scripts:
You’ll have to note that this option works only once per session. After the first import , successive import executions do nothing, even if you modify the content of the module. This is because import operations are expensive and therefore run only once. Here’s an example:
These two import operations do nothing, because Python knows that hello has already been imported.
There are some requirements for this method to work:
- The file with the Python code must be located in your current working directory.
- The file must be in the Python Module Search Path (PMSP), where Python looks for the modules and packages you import.
To know what’s in your current PMSP, you can run the following code:
Running this code, you’ll get the list of directories and .zip files where Python searches the modules you import.
Using importlib and imp
In the Python Standard Library, you can find importlib , which is a module that provides import_module() .
With import_module() , you can emulate an import operation and, therefore, execute any module or script. Take a look at this example:
Once you’ve imported a module for the first time, you won’t be able to continue using import to run it. In this case, you can use importlib.reload() , which will force the interpreter to re-import the module again, just like in the following code:
An important point to note here is that the argument of reload() has to be the name of a module object, not a string:
If you use a string as an argument, then reload() will raise a TypeError exception.
Note: The output of the previous code has been abbreviated ( . ) in order to save space.
importlib.reload() comes in handy when you are modifying a module and want to test if your changes work, without leaving the current interactive session.
Finally, if you are using Python 2.x, then you’ll have imp , which is a module that provides a function called reload() . imp.reload() works similarly to importlib.reload() . Here’s an example:
In Python 2.x, reload() is a built-in function. In versions 2.6 and 2.7, it is also included in imp , to aid the transition to 3.x.
Note: imp has been deprecated since version 3.4 of the language. The imp package is pending deprecation in favor of importlib .
Using runpy.run_module() and runpy.run_path()
The Standard Library includes a module called runpy . In this module, you can find run_module() , which is a function that allows you to run modules without importing them first. This function returns the globals dictionary of the executed module.
Here’s an example of how you can use it:
The module is located using a standard import mechanism and then executed on a fresh module namespace.
The first argument of run_module() must be a string with the absolute name of the module (without the .py extension).
On the other hand, runpy also provides run_path() , which will allow you to run a module by providing its location in the filesystem:
Like run_module() , run_path() returns the globals dictionary of the executed module.
The path_name parameter must be a string and can refer to the following:
- The location of a Python source file
- The location of a compiled bytecode file
- The value of a valid entry in the sys.path , containing a __main__ module ( __main__.py file)
Hacking exec()
So far, you’ve seen the most commonly used ways to run Python scripts. In this section, you’ll see how to do that by using exec() , which is a built-in function that supports the dynamic execution of Python code.
exec() provides an alternative way for running your scripts:
This statement opens hello.py , reads its content, and sends it to exec() , which finally runs the code.
The above example is a little bit out there. It’s just a “hack” that shows you how versatile and flexible Python can be.
Using execfile() (Python 2.x Only)
If you prefer to use Python 2.x, you can use a built-in function called execfile() , which is able to run Python scripts.
The first argument of execfile() has to be a string containing the path to the file you want to run. Here’s an example:
Here, hello.py is parsed and evaluated as a sequence of Python statements.
How to Run Python Scripts From an IDE or a Text Editor
When developing larger and more complex applications, it is recommended that you use an integrated development environment (IDE) or an advanced text editor.
Most of these programs offer the possibility of running your scripts from inside the environment itself. It is common for them to include a Run or Build command, which is usually available from the tool bar or from the main menu.
Python’s standard distribution includes IDLE as the default IDE, and you can use it to write, debug, modify, and run your modules and scripts.
Other IDEs such as Eclipse-PyDev, PyCharm, Eric, and NetBeans also allow you to run Python scripts from inside the environment.
Advanced text editors like Sublime Text and Visual Studio Code also allow you to run your scripts.
To grasp the details of how to run Python scripts from your preferred IDE or editor, you can take a look at its documentation.
How to Run Python Scripts From a File Manager
Running a script by double-clicking on its icon in a file manager is another possible way to run your Python scripts. This option may not be widely used in the development stage, but it may be used when you release your code for production.
In order to be able to run your scripts with a double-click, you must satisfy some conditions that will depend on your operating system.
Windows, for example, associates the extensions .py and .pyw with the programs python.exe and pythonw.exe respectively. This allows you to run your scripts by double-clicking on them.
When you have a script with a command-line interface, it is likely that you only see the flash of a black window on your screen. To avoid this annoying situation, you can add a statement like input(‘Press Enter to Continue. ‘) at the end of the script. This way, the program will stop until you press Enter .
This trick has its drawbacks, though. For example, if your script has any error, the execution will be aborted before reaching the input() statement, and you still won’t be able to see the result.
On Unix-like systems, you’ll probably be able to run your scripts by double-clicking on them in your file manager. To achieve this, your script must have execution permissions, and you’ll need to use the shebang trick you’ve already seen. Likewise, you may not see any results on screen when it comes to command-line interface scripts.
Because the execution of scripts through double-click has several limitations and depends on many factors (such as the operating system, the file manager, execution permissions, file associations), it is recommended that you see it as a viable option for scripts already debugged and ready to go into production.
Conclusion
With the reading of this tutorial, you have acquired the knowledge and skills you need to be able to run Python scripts and code in several ways and in a variety of situations and development environments.
You are now able to run Python scripts from:
- The operating system command-line or terminal
- The Python interactive mode
- The IDE or text editor you like best
- The file manager of your system, by double-clicking on the icon of your script
These skills will make your development process much faster, as well as more productive and flexible.
Take the Quiz: Test your knowledge with our interactive “How to Run Your Python Scripts” quiz. Upon completion you will receive a score so you can track your learning progress over time:
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: Running Python Scripts
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.
About Leodanis Pozo Ramos
Leodanis is an industrial engineer who loves Python and software development. He's a self-taught Python developer with 6+ years of experience. He's an avid technical writer with a growing number of articles published on Real Python and other sites.
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:
Run Python Script – How to Execute Python Shell Commands in the Terminal
Suchandra Datta
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!