Different Methods to Run Python Scripts
There are the following four methods to run python scripts:
RUN PYTHON SCRIPT USING COMMAND LINE
The easiest way to run Python scripts is to use the command prompt.
TO OPEN THE COMMAND PROMPT:
-
On Windows, the command line is called the command prompt or MS-DOS console. A faster way to access it is to go to “Start” → “Run” and type cmd.
-
On GNU/Linux, Multiple applications can access the command line such as xterm, Gnome terminal or console.
- In MAC OS X, call the system terminal through Application → Utilities → Terminal.
After successfully opening the command prompt, type the word cd followed by the path to your script file or python file and press Enter.
Then write filename.py now press Enter again, and You are Done!! The screen will display the output.
You can also read about the Multilevel Inheritance in Python, and Convert String to List Python
RUN PYTHON SCRIPTS USING AN IDE OR TEXT EDITOR
While developing more significant and complex applications, it’s suggested that you should use an Integrated Development Environment (IDE) or a text editor.
IDE:
An IDE (or Integrated Development Environment) is a program committed to programming improvement. As the name infers, IDEs compose a few tools explicitly intended for software development.
These tools usually include an editor, run, build, execution, debugging and many more.
Python’s standard distribution includes IDLE as the default IDE to write, debug, modify, and run your code and scripts. Other IDEs such as Eclipse-PyDev, PyCharm, Eric, etc., also allow you to run Python scripts inside the environment.
If you want to run a Python script from your IDE:
-
Launch PYTHON IDLE from the START MENU
-
Create a new file and write your required script.
- Now save it (you can use CTRL+S ) with the .py extension.
The .py extension is used on all of these files to indicate Python executable files. In Windows, pyw is another extension for Python files.
You can use the default “Run” command or fast keys like Function + F5 or just F5 to run Python scripts.
- Bingo! Now you can see the output on your screen.
Let's say you want to write a Python code that prints "Hello, World!" to the screen. Let us understand this with an example how you can do it:
1. Launch Python IDLE:
- First, we to go to our Start Menu. Then search for Python IDLE and open it.
2. Create a New File:
- In the IDLE, there will be a menu, click on File and select New File. A new window will open where we can write our Python code.
3. Write our Code:
- In the new file, we have to type the following Python code:
print("Hello, World!")
4. Save the File:
- Now, press CTRL+S to save the file or we can save it manually by to going to the menu again.
- We have to give a proper name to the file in which we have written the code, for example, hello_world.py. The .py extension indicates that it is a Python executable file.
5. Run the code:
- To run the code, we can simply press F5 or go to the Run menu and select Run Module.
6. View the Output:
- After running the script, the output will appear in the Python Shell:
Hello, World!
Text Editors
The formal definition is: “A text editor is a program that edits text files”.
Basically, a text editor is a program on your computer that allows you to create and edit files in various programming languages.
It manages hand codes in various languages, such as HTML, CSS, JavaScript, PHP, Ruby, Python, etc. In addition, there are many text editors you can choose from, like Sublime Text Editor, Notepad++, TextWrangler(Mac Only), gedit, etc.
If you are starting with Python, you can use simple text editors like Sublime or Notepad++ or any other text editor.
You must now write a sample script. To do this:
-
Launch your preferred text editor and write your script.
-
Save the file to your desktop under the name samplefile.py or whatever you want.
-
Remember that you only need to provide the .py extension.
-
Click build in the toolbar.
- Subsequently, the screen will display the required output according to your script.
For example, we want to write a simple Python script that calculates the square of a number and displays the result. Let's see how we can do it using a text editor like Sublime Text or Notepad++:
1. Launch Your Text Editor
- Open your preferred text editor, such as Sublime Text or Notepad++.
2. Write Your Python Script
- In the text editor, type the following code:
# Script to calculate the square of a number
number = int(input("Enter a number: "))
square = number * number
print(f"The square of {number} is {square}")
3. Save the Script
- Save the file to your desktop or another location.
- Name it samplefile.py (make sure to include the .py extension).
4. Run the Script
-
Option 1: Run directly in the text editor:
- In Sublime Text: Go to Tools > Build or press Ctrl+B.
-
Option 2: Run from the terminal or command prompt:
- Open the terminal or command prompt.
- Navigate to the folder where you saved samplefile.py.
- Type python samplefile.py and press Enter.
5. View the Output
- When prompted, enter a number (e.g., 4).
- The output will be:
Enter a number: 4
The square of 4 is 16
RUN PYTHON SCRIPT USING INTERACTIVE MODE
An Interactive mode is a great way to get started with Python since it allows you to test each piece of code while you’re working on it.
-
All you have to do now is start the Python Interactive session.
-
To do so, open a terminal or command line and type Python or Python3 depending on the Python version installed on your machine, then press Enter.
- The >>> represents the standard Interactive mode prompt on the terminal.
Note: If you don’t see these characters, your system has to be reinstalled with Python.
When working with an interactive session, the statements you type are evaluated and performed immediately, though the main drawback is that the code is lost when the interactive session ends.
But, the advantage is you don’t have to wait until your code is finished to test it. Instead, you can try it out on the spot.
So, whenever you’re working with Python and aren’t sure what a specific block of code does, just open the interactive session, paste the code, and watch what happens.
Once you’ve completed all of your testings, you can quit interactive mode by selecting one of the following alternatives:
-
Exit() or quit() are built-in functions.
-
For Windows, use the Ctrl+Z and Enter combination.
- Use Ctrl+D on Unix-like platforms.
Let us see an example how we can use Python's Interactive Mode:
1. Start Python Interactive Mode:
-
Windows: Open the Command Prompt.
-
Unix-like systems (Linux/MacOS): Open the terminal.
- Type python or python3 (depending on the version installed on your system) and press Enter.
You should see the Python prompt >>>, indicating that you are in interactive mode.
$ python3
Python 3.x.x (default, Jul 21 2022, 11:32:11)
[GCC 7.5.0] on linux Type "help", "copyright", "credits" or "license" for more information.
>>>
2. Test Code Snippets:
- You can now type Python code directly into the prompt, and it will execute immediately.
- For example, try calculating the sum of two numbers:
>>> 5 + 7
12
- You can also define a variable and perform operations:
>>> x = 10
>>> x * 2
20
3. Experiment with More Complex Code:
- You can even define functions or classes and test them on the spot:
>>> def greet(name):
... return f"Hello, {name}!"
...
>>> greet("Alice") 'Hello, Alice!'
- This immediate feedback is useful for debugging and understanding how different parts of your code work.
4. Exit Interactive Mode:
- Once you're done testing, you can exit interactive mode:
-
Windows: Press Ctrl+Z and then press Enter.
-
Unix-like systems: Press Ctrl+D.
- You can also type exit() or quit() and press Enter:
>>> exit() $
Exiting will return you to your regular command prompt or terminal.
RUN PYTHON SCRIPT USING FILE MANAGER
A Python script can also be started by double-clicking on its icon in the file manager.
In order to do so, you must satisfy specific requirements, which varies based on the operating system you’re using.
-
Pythonw.exe and Python.exe are related to the extensions .pyw and .py, respectively, on Windows. This facilitates the scripts to be run by just double-clicking the icon.
- If the script has a command-line interface, a black window will appear on the screen for a second.
To prevent this, add input(‘Press Enter at Continue…’) to the script’s end, and as soon as you press Enter, the software will be terminated.
There are certain disadvantages to this strategy. Assume your script has a bug. Even before it reaches the statement mentioned above, the execution will be halted.
As a result, you will be unable to view the results.
- You need to set execution rights in the script if you are working on Unix-like systems and then run the scripts by simply double-clicking the icon in the file manager.
Note: This method should only be used for scripts that have already been debugged and are ready to go into production because double-clicking the scripts have restrictions and rely on various things such as the file manager, operating system, file association, execution rights, etc.
Let us see two examples to illustrate how to run a Python script by double-clicking its icon in the file manager:
1. Running a Python Script on Windows
We have a Python code that prints a simple message:
1. Create the Script:
- We have to open our text editor or Python IDLE. Then we have to type the following code:
print("Hello from the double-click script!")
input('Press Enter to continue...')
2. Save the Script:
- Then save the file with a proper name for example, python_script.py on your desktop or in any other folder.
3. Run the Script:
- Now, go to the folder where we have saved our code file. Then Double-click the icon of the code. Then we will see a command-line window. This window will display the message "Hello from the double-click script!" followed by the prompt "Press Enter to continue...".
- The window will remain open until you press Enter, allowing you to see the output.
2. Running a Python Script on Unix-like Systems (Linux/MacOS)
1. Create the Script:
- We have to open our text editor. Then we have to type the following code:
print("Hello from the Unix double-click script!")
input('Press Enter to continue...')
2. Save the Script:
- Then save the file with a proper name for example, python_script.py on your desktop or in any other folder
3. Set Execution Rights:
- Open the terminal and navigate to the directory where the script is located. Then run the following command to make the script executable:
chmod +x double_click_script.py
4. Run the Script:
- Now, open your file manager and navigate to the location of the file of our code.
- Double-click the script icon.
- The terminal window will open, displaying the message "Hello from the Unix double-click script!" followed by the prompt "Press Enter to continue...".
- The terminal will remain open until you press Enter.
Check out this article - Quicksort Python
Frequently Asked Questions
How do I run a .py file?
There are the following four methods to run python scripts:
1. Using Command-Line prompt.
2. Using an IDE or Text Editor
3. Python Interactive Mode
4. Using File Manager
Can you write Python in the terminal?
Yes, we can write Python scripts in the terminal.
How do I run python from the command line?
After successfully opening the command prompt, type the word cd followed by the path to your script file or python file and press Enter. Then write filename.py now press Enter again, and output will be displayed on the screen.
What is a Python terminal?
The Python interpreter (REPL) running inside a terminal window. In Windows, it is called Command Prompt. In macOS or Linux, it should be called Terminal.
Can you run Python online?
Yes, there are many online Python Interpreters like Jupyter, OnlineGDB etc.
How do I practice Python code?
At Coding Ninjas, you will get an adaptive and excelling Python Course and practice problems which will help you ease working in larger, more advanced Python environments.
Conclusion
In this blog, we discussed How To Run Python In Terminal. It is a fundamental skill that every Python developer should master. Whether you are writing simple scripts or developing complex applications, knowing how to execute Python code from the terminal allows you to streamline your workflow and quickly test and debug your programs.
Here, you gained the knowledge and skills about how to run Python in terminal using the following methods:
-
The command-line prompt
-
Your preferred integrated development environment (IDE) or text editor.
-
Using Interactive Mode
-
Using File Manager
Recommended Readings:
After learning these fundamental ways, I would suggest you explore Coding Ninjas Python Course once because this provides you more ease at working in larger and more advanced Python environments, which will improve the development process and boost your efficiency.