How to run python code in python
How to run python code in python
How To Run Your Python Scripts
Author: PFB Staff Writer
Last Updated: June 8, 2020
Your Python code can be up on a code editor, IDE or a file. And, it won’t work unless you know how to execute your Python script.
In this blog post, we will take a look at 7 ways to execute Python code and scripts. No matter what your operating system is, your Python environment or the location of your code – we will show you how to execute that piece of code!
Table of Contents
Where to run Python scripts and how?
You can run a Python script from:
Running Python Code Interactively
To start an interactive session for Python code, simply open your Terminal or Command line and type in Python(or Python 3 depending on your Python version). And, as soon as you hit enter, you’ll be in the interactive mode.
Here’s how you enter interactive mode in Windows, Linux and MacOS.
Interactive Python Scripting Mode On Linux
Open up your Terminal.
It should look something like
Enter the Python script interactive mode after pressing “Enter”.
Interactive Python Scripting Mode On Mac OSX
Launching interactive Python script mode on Mac OS is pretty similar to Linux. The image below shows the interactive mode on Mac OS.
Interactive Python Scripting Mode On Windows
On Windows, go to your Command Prompt and write “python”. Once you hit enter you should see something like this:
Running Python Scripts Interactively
With interactive Python script mode, you can write code snippets and execute them to see if they give desired output or whether they fail.
Take an example of the for loop below.
Our code snippet was written to print everything including 0 and upto 5. So, what you see after print(i) is the output here.
To exit interactive Python script mode, write the following:
And, hit Enter. You should be back to the command line screen that you started with initially.
There are other ways to exit the interactive Python script mode too. With Linux you can simply to Ctrl + D and on Windows you need to press Ctrl + Z + Enter to exit.
Note that when you exit interactive mode, your Python scripts won’t be saved to a local file.
How are Python scripts executed?
A nice way to visualize what happens when you execute a Python script is by using the diagram below. The block represents a Python script (or function) we wrote, and each block within it, represents a line of code.
When you run this Python script, Python interpreter goes from top to bottom executing each line.
And, that’s how Python interpreter executes a Python script.
But that’s not it! There’s a lot more that happens.
Flow Chart of How Python Interpreter Runs Codes
Step 2: The binary file generated, is now read by the interpreter to execute instructions.
Think of them as a bunch of instructions that leads to the final outcome.
There are some benefits of inspecting bytecode. And, if you aim to turn yourself into a pro level Pythonista, you may want to learn and understand bytecode to write highly optimized Python scripts.
You can also use it to understand and guide your Python script’s design decisions. You can look at certain factors and understand why some functions/data structures are faster than others.
How to run Python scripts?
To run a Python script using command line, you need to first save your code as a local file.
There are many ways to do that:
Saving a Python script from a code editor is pretty easy. Basically as simple as saving a text file.
But, to do it via Command line, there are a couple of steps involved.
First, head to your command line, and change your working directory to where you wish to save the Python script.
Once you are in the right directory, execute the following command in Terminal:
Once you hit enter, you’ll get into a command line interface that looks something like this:
Now, you can write a Python code here and easily run it using command line.
How to run Python scripts using command line?
Python scripts can be run using Python command over a command line interface. Make sure you specify the path to the script or have the same working directory. To execute your Python script(python_script.py) open command line and write python3 python_script.py
Replace python3 with python if your Python version is Python2.x.
Here’s what we saved in our python_script.py
And, the output on your command line looks something like this
Let’s say, we want to save the output of the Python code which is 0, 1, 2, 3, 4 – we use something called a pipe operator.
In our case, all we have to do is:
And, a file named “newfile.txt” would be created with our output saved in it.
How to run Python code interactively
There are more than 4 ways to run a Python script interactively. And, in the next few sections we will see all major ways to execute Python scripts.
Using Import to run your Python Scripts
We all use import module to load scripts and libraries extremely frequently. You can write your own Python script(let’s say code1.py) and import it into another code without writing the whole code in the new script again.
Here’s how you can import code1.py in your new Python script.
But, doing so would mean that you import everything that’s in code1.py to your Python code. That isn’t an issue till you start working in situations where your code has to be well optimized for performance, scalability and maintainability.
So, let’s say, we had a small function inside code1 that draws a beautiful chart e.g. chart_code1(). And, that function is the only reason why we wish to import the entire code1.py script. Rather than having to call the entire Python script, we can simply call the function instead.
Here’s how you would typically do it
And, you should be able to use chart_code1 in your new Python script as if it were present in your current Python code.
Next, let’s look at other ways to import Python code.
Using and importlib to run Python code
import_module() of importlib allows you to import and execute other Python scripts.
The way it works is pretty simple. For our Python script code1.py, all we have to do is:
Let’s go through a case where we have complex directory structures and we wish to use importlib. Directory structure of the Python code we want to run is below:
In this case if you think you can do importlib.import_module(“level3”), you’ll get an error. This is called relative import, and the way you do it is by using a relative name with anchor explicit.
So, to run Python script level3.py, you can either do
Run Python code using runpy
Runpy module locates and executes a Python script without importing it. Usage is pretty simple as you can easily call the module name inside of run_module().
To execute our code1.py module using runpy. Here’s what we will do.
Run Python Code Dynamically
We are going to take a look at exec() function to execute Python scripts dynamically. In Python 2, exec function was actually a statement.
Here’s how it helps you execute a Python code dynamically in case of a string.
Dynamic Code Was Executed
However, using exec() should be a last resort. As it is slow and unpredictable, try to see if there are any other better alternatives available.
Running Python Scripts from a Text Editor
To run Python script using a Python Text Editor you can use the default “run” command or use hot keys like Function + F5 or simply F5(depending on your OS).
Here’s an example of Python script being executed in IDLE.
However, note that you do not control the virtual environment like how you typically would from a command line interface execution.
That’s where IDEs and Advanced text editors are far better than Code Editors.
Running Python Scripts from an IDE
When it comes to executing scripts from an IDE, you can not only run your Python code, but also debug it and select the Python environment you would like to run it on.
While the IDE’s UI interface may vary, the process would be pretty much similar to save, run and edit a code.
How to run Python scripts from a File Manager
How to run Python scripts from another Python script
Although we haven’t already stated this, but, if you go back up and read, you’ll notice that you can:
Key Takeaway
Related
Recommended Python Training
Course: Python 3 For Beginners
Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.
Interacting With Python
Table of Contents
At this point, you should have a working Python 3 interpreter at hand. If you need help getting Python set up correctly, please refer to the previous section in this tutorial series.
Here’s what you’ll learn in this tutorial: Now that you have a working Python setup, you’ll see how to actually execute Python code and run Python programs. By the end of this article, you’ll know how to:
It’s time to write some Python code!
Hello, World!
There is a long-standing custom in the field of computer programming that the first code written in a newly installed language is a short program that simply displays the string Hello, World! to the console.
Note: This is a time-honored tradition dating back to the 1970s. See Hello, World! for a brief history. You seriously risk upsetting the qi of the universe if you don’t abide by this custom.
The simplest Python 3 code to display Hello, World! is:
You will explore several different ways to execute this code below.
Using the Python Interpreter Interactively
The most straightforward way to start talking to Python is in an interactive Read-Eval-Print Loop (REPL) environment. That simply means starting up the interpreter and typing commands to it directly. The interpreter:
The session continues in this manner until you instruct the interpreter to terminate. Most of the example code in this tutorial series is presented as REPL interaction.
Starting the Interpreter
In a GUI desktop environment, it is likely that the installation process placed an icon on the desktop or an item in the desktop menu system that starts Python.
For example, in Windows, there will likely be a program group in the Start menu labeled Python 3.x, and under it a menu item labeled Python 3.x (32-bit), or something similar depending on the particular installation you chose.
Clicking on that item will start the Python interpreter:
The Python interpreter (REPL) running inside a terminal window.
Alternatively, you can open a terminal window and run the interpreter from the command line. How you go about opening a terminal window varies depending on which operating system you’re using:
Using your operating system’s search function to search for “command” in Windows or “terminal” in macOS or Linux should find it.
This example is from the Windows Command Prompt window:
If you are not seeing the >>> prompt, then you are not talking to the Python interpreter. This could be because Python is either not installed or not in your terminal window session’s path. It’s also possible that you just haven’t found the correct command to execute it. You can refer to our installing Python tutorial for help.
Executing Python Code
If you are seeing the prompt, you’re off and running! The next step is to execute the statement that displays Hello, World! to the console:
The interpreter’s response should appear on the next line. You can tell it is console output because the >>> prompt is absent:
If your session looks like the above, then you have executed your first Python code! Take a moment to celebrate.
Congratulations!
Did something go wrong? Perhaps you made one of these mistakes:
You forgot to enclose the string to be printed in quotation marks:
You remembered the opening quotation mark but forgot the closing one:
You used different opening and closing quotation marks:
You forgot the parentheses:
You entered extra whitespace characters before the command:
(You will see in an upcoming section why this matters.)
If you got some sort of error message, go back and verify that you typed the command exactly as shown above.
Exiting the Interpreter
When you are finished interacting with the interpreter, you can exit a REPL session in several ways:
Type exit() and press Enter :
In Windows, type Ctrl + Z and press Enter :
Running a Python Script from the Command Line
Entering commands to the Python interpreter interactively is great for quick testing and exploring features or functionality.
Eventually though, as you create more complex applications, you will develop longer bodies of code that you will want to edit and run repeatedly. You clearly don’t want to re-type the code into the interpreter every time! This is where you will want to create a script file.
A Python script is a reusable set of code. It is essentially a Python program—a sequence of Python instructions—contained in a file. You can run the program by specifying the name of the script file to the interpreter.
Python scripts are just plain text, so you can edit them with any text editor. If you have a favorite programmer’s editor that operates on text files, it should be fine to use. If you don’t, the following are typically installed natively with their respective operating systems:
Using whatever editor you’ve chosen, create a script file called hello.py containing the following:
Now save the file, keeping track of the directory or folder you chose to save into.
Start a command prompt or terminal window. If the current working directory is the same as the location in which you saved the file, you can simply specify the filename as a command-line argument to the Python interpreter: python hello.py
For example, in Windows it would look like this:
If the script is not in the current working directory, you can still run it. You’ll just have to specify the path name to it:
In Linux or macOS, your session may look more like this:
Interacting with Python through an IDE
An Integrated Development Environment (IDE) is an application that more or less combines all the functionality you have seen so far. IDEs usually provide REPL capability as well as an editor with which you can create and modify code to then submit to the interpreter for execution.
You may also find cool features such as:
Most Python installations contain a rudimentary IDE called IDLE. The name ostensibly stands for Integrated Development and Learning Environment, but one member of the Monty Python troupe is named Eric Idle, which hardly seems like a coincidence.
The procedure for running IDLE varies from one operating system to another.
Starting IDLE in Windows
Click on the icon to start IDLE.
Starting IDLE in macOS
Starting IDLE in Linux
If you get an error saying command not found or something to that effect, then IDLE is apparently not installed, so you’ll need to install it.
Follow whatever procedure is appropriate for your distribution to install IDLE. Then, type idle3 in a terminal window and press Enter to run it. Your installation procedure may have also set up a program icon somewhere on the desktop to start IDLE as well.
Using IDLE
Once IDLE is installed and you have started it successfully, you should see a window titled Python 3.x.x Shell, where 3.x.x corresponds to your version of Python:
The >>> prompt should look familiar. You can type REPL commands interactively, just like when you started the interpreter from a console window. Mindful of the qi of the universe, display Hello, World! again:
The interpreter behaves more or less the same as when you ran it directly from the console. The IDLE interface adds the perk of displaying different syntactic elements in distinct colors to make things more readable.
It also provides context-sensitive help. For example, if you type print( without typing any of the arguments to the print function or the closing parenthesis, then flyover text should appear specifying usage information for the print() function.
One other feature IDLE provides is statement recall:
You can also create script files and run them in IDLE. From the Shell window menu, select File → New File. That should open an additional editing window. Type in the code to be executed:
From the menu in that window, select File → Save or File → Save As… and save the file to disk. Then select Run → Run Module. The output should appear back in the interpreter Shell window:
Once both windows are open, you can switch back and forth, editing the code in one window, running it and displaying its output in the other. In that way, IDLE provides a rudimentary Python development platform.
Although it is somewhat basic, it supports quite a bit of additional functionality, including code completion, code formatting, and a debugger. See the IDLE documentation for more details.
Thonny
Thonny is free Python IDE developed and maintained by the Institute of Computer Science at the University of Tartu, Estonia. It is targeted at Python beginners specifically, so the interface is simple and uncluttered as well as easy to understand and get comfortable with quickly.
Like IDLE, Thonny supports REPL interaction as well as script file editing and execution:
Thonny performs syntax highlighting and code completion in addition to providing a step-by-step debugger. One feature that is particularly helpful to those learning Python is that the debugger displays values in expressions as they are evaluated while you are stepping through the code:
Thonny is especially easy to get started with because it comes with Python 3.6 built in. So you only need to perform one install, and you’re ready to go!
Versions are available for Windows, macOS, and Linux. The Thonny website has download and installation instructions.
IDLE and Thonny are certainly not the only games going. There are many other IDEs available for Python code editing and development. See our Python IDEs and Code Editors Guide for additional suggestions.
Online Python REPL Sites
As you saw in the previous section, there are websites available that can provide you with interactive access to a Python interpreter online without you having to install anything locally.
This approach may be unsatisfactory for some of the more complicated or lengthy examples in this tutorial. But for simple REPL sessions, it should work well.
The Python Software Foundation provides an Interactive Shell on their website. On the main page, click on the button that looks like one of these:
You should get a page with a window that looks something like this:
The familiar >>> prompt shows you that you are talking to the Python interpreter.
Here are a few other sites that provide Python REPL:
Conclusion
Larger applications are typically contained in script files that are passed to the Python interpreter for execution.
But one of the advantages of an interpreted language is that you can run the interpreter and execute commands interactively. Python is easy to use in this manner, and it is a great way to get your feet wet learning how the language works.
The examples throughout this tutorial have been produced by direct interaction with the Python interpreter, but if you choose to use IDLE or some other available IDE, the examples should still work just fine.
Continue to the next section, where you will start to explore the elements of the Python language itself.
Run function from the command line
I have this code:
How would I run this directly from the command line?
18 Answers 18
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
Alternatively, if you don’t care about namespace pollution:
And the middle ground:
Just put hello() somewhere below the function and it will execute when you do python your_file.py
For a neater solution you can use this:
That way the function will only be executed if you run the file, not when you import the file.
However, if hello() is your «permanent» main entry point in your Python script, then the usual way to do this is as follows:
add this snippet to the bottom of your script
You can now call your function by running
update: if you would like the function to accept a parameter from the command line, you can pass in sys.argv[2] like this:
Save this in a file called PyRun
Here is a sample module to show how it works. This is saved in a file called PyTest.py:
Try running these examples:
Note the last example of escaping the parentheses to pass in a tuple as the only parameter to the Second method.
If you pass too few parameters for what the method needs you get an error. If you pass too many, it ignores the extras. The module must be in the current working folder, put PyRun can be anywhere in your path.
How do I execute a string containing Python code in Python?
How do I execute a string containing Python code in Python?
14 Answers 14
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
For statements, use exec(string) (Python 2/3) or exec string (Python 2):
When you need the value of an expression, use eval(string) :
However, the first step should be to ask yourself if you really need to. Executing code should generally be the position of last resort: It’s slow, ugly and dangerous if it can contain user-entered code. You should always look at alternatives first, such as higher order functions, to see if these can better meet your needs.
In the example a string is executed as code using the exec function.
eval and exec are the correct solution, and they can be used in a safer manner.
As discussed in Python’s reference manual and clearly explained in this tutorial, the eval and exec functions take two extra parameters that allow a user to specify what global and local functions and variables are available.
In essence you are defining the namespace in which the code will be executed.
Avoid exec and eval
Using exec and eval in Python is highly frowned upon.
There are better alternatives
From the top answer (emphasis mine):
However, the first step should be to ask yourself if you really need to. Executing code should generally be the position of last resort: It’s slow, ugly and dangerous if it can contain user-entered code. You should always look at alternatives first, such as higher order functions, to see if these can better meet your needs.
set and get values of variables with the names in strings
[while eval ] would work, it is generally not advised to use variable names bearing a meaning to the program itself.
Instead, better use a dict.
It is not idiomatic
Python is not PHP
Don’t try to circumvent Python idioms because some other language does it differently. Namespaces are in Python for a reason and just because it gives you the tool exec it does not mean you should use that tool.
It is dangerous
So eval is not safe, even if you remove all the globals and the builtins!
The problem with all of these attempts to protect eval() is that they are blacklists. They explicitly remove things that could be dangerous. That is a losing battle because if there’s just one item left off the list, you can attack the system.
So, can eval be made safe? Hard to say. At this point, my best guess is that you can’t do any harm if you can’t use any double underscores, so maybe if you exclude any string with double underscores you are safe. Maybe.
It is hard to read and understand
First, exec makes it harder to human beings to read your code. In order to figure out what’s happening, I don’t just have to read your code, I have to read your code, figure out what string it’s going to generate, then read that virtual code. So, if you’re working on a team, or publishing open source software, or asking for help somewhere like StackOverflow, you’re making it harder for other people to help you. And if there’s any chance that you’re going to be debugging or expanding on this code 6 months from now, you’re making it harder for yourself directly.
How to Run Your Python Scripts
Table of Contents
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
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:
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:
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:
How to Run Python Code Interactively
Here’s an example of how to do this on Linux:
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:
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 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
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:
Using the python Command
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:
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.
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.
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:
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:
These two import operations do nothing, because Python knows that hello has already been imported.
There are some requirements for this method to work:
To know what’s in your current PMSP, you can run the following code:
Using importlib and imp
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.
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.
Using runpy.run_module() and runpy.run_path()
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 path_name parameter must be a string and can refer to the following:
Hacking exec()
exec() provides an alternative way for running your scripts:
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)
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.
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:
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:
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!
Related Tutorial Categories: basics python