How To Run Python Script In Python Shell In Windows
Your Python lawmaking tin can exist 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 accept a look at 7 means to execute Python code and scripts. No matter what your operating organisation is, your Python environs or the location of your code – nosotros will show yous how to execute that piece of lawmaking!
Tabular array of Contents
- Running Python Code Interactively
- How are Python Script is Executed
- How to Run Python Scripts
- How to Run Python Scripts using Command Line
- How to Run Python Code Interactively
- Running Python Code from a Text Editor
- Running Python Code from an IDE
- How to Run Python Scripts from a File Director
- How to Run Python Scripts from Another Python Script
Where to run Python scripts and how?
You tin run a Python script from:
- Bone Command line (also known as shell or Final)
- Run Python scripts with a specific Python Version on Anaconda
- Using a Crontab
- Run a Python script using another Python script
- Using FileManager
- Using Python Interactive Mode
- Using IDE or Code Editor
Running Python Code Interactively
To kickoff an interactive session for Python code, but open up your Last or Command line and type in Python(or Python 3 depending on your Python version). And, as soon every bit you hit enter, y'all'll be in the interactive mode.
Hither'south how y'all enter interactive mode in Windows, Linux and MacOS.
Interactive Python Scripting Mode On Linux
Open up your Terminal.
It should look something like
$ python Python 3.7.3 (default, Mar 27 2019, 22:xi:17) [GCC 7.3.0] :: Anaconda, Inc. on linux Type "help", "copyright", "credits" or "license" for more data.
Enter the Python script interactive mode after pressing "Enter".
Interactive Python Scripting Manner On Mac OSX
Launching interactive Python script mode on Mac Bone is pretty similar to Linux. The epitome below shows the interactive fashion on Mac Bone.
Interactive Python Scripting Mode On Windows
On Windows, go to your Control Prompt and write "python". In one case you hit enter you should come across something like this:
Running Python Scripts Interactively
With interactive Python script fashion, you lot can write code snippets and execute them to see if they give desired output or whether they fail.
Have an example of the for loop below.
Our code snippet was written to impress everything including 0 and upto 5. So, what you lot see afterward print(i) is the output here.
To exit interactive Python script style, write the following:
>>>exit()
And, hit Enter. Y'all should be back to the command line screen that you started with initially.
There are other ways to go out the interactive Python script style too. With Linux yous tin can but to Ctrl + D and on Windows you lot need to press Ctrl + Z + Enter to go out.
Annotation that when you leave 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 past using the diagram below. The cake represents a Python script (or function) nosotros wrote, and each block inside information technology, represents a line of code.
When y'all run this Python script, Python interpreter goes from height to bottom executing each line.
And, that's how Python interpreter executes a Python script.
But that's not information technology! There's a lot more that happens.
Catamenia Nautical chart of How Python Interpreter Runs Codes
Step 1: Your script or .py file is compiled and a binary format is generated. This new format is in either .pyc or .pyo.
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, yous may desire to larn and understand bytecode to write highly optimized Python scripts.
Yous can also use it to sympathize and guide your Python script's design decisions. Y'all tin can look at certain factors and understand why some functions/information structures are faster than others.
How to run Python scripts?
To run a Python script using control line, you need to commencement save your lawmaking as a local file.
Permit'southward take the case of our local Python file again. If you were to save it to a local .py file named python_script.py.
There are many ways to do that:
- Create a Python script from control line and save it
- Create a Python script using a text editor or IDE and salvage it
Saving a Python script from a code editor is pretty easy. Basically as uncomplicated as saving a text file.
But, to do it via Command line, there are a couple of steps involved.
First, head to your control line, and change your working directory to where you wish to save the Python script.
Once you are in the right directory, execute the post-obit command in Terminal:
$ sudo nano python_script.py
Once you hit enter, you'll get into a control line interface that looks something similar this:
Now, y'all tin can write a Python code here and easily run information technology using control line.
How to run Python scripts using command line?
Python scripts tin can be run using Python command over a control line interface. Make sure yous specify the path to the script or have the aforementioned working directory. To execute your Python script(python_script.py) open control 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
for i in range(0,5): print(i)
And, the output on your command line looks something like this
Allow's say, we want to save the output of the Python code which is 0, 1, two, 3, 4 – we use something called a pipe operator.
In our case, all nosotros have to do is:
$python python_script.py > newfile.txt
And, a file named "newfile.txt" would be created with our output saved in it.
How to run Python lawmaking interactively
At that place are more than 4 ways to run a Python script interactively. And, in the next few sections nosotros 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 oftentimes. You tin can write your ain Python script(let's say code1.py) and import it into another lawmaking without writing the whole code in the new script again.
Here'southward how you can import code1.py in your new Python script.
>>> import code1
Merely, doing so would mean that you import everything that's in code1.py to your Python lawmaking. That isn't an result till you start working in situations where your code has to be well optimized for performance, scalability and maintainability.
So, permit's say, we had a small function inside code1 that draws a cute nautical chart e.g. chart_code1(). And, that function is the merely reason why nosotros wish to import the entire code1.py script. Rather than having to telephone call the unabridged Python script, we can simply call the role instead.
Here's how you lot would typically do it
>>> from code1 import chart_code1
And, you should be able to employ chart_code1 in your new Python script as if it were present in your current Python code.
Adjacent, allow's look at other means 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 nosotros have to do is:
import importlib import.import_module('code1')
In that location's no need to add .py in import_module().
Let's go through a example where we have complex directory structures and we wish to use importlib. Directory structure of the Python code nosotros desire to run is below:
level1
|
+ – __init__.py
– level2
|
+ – __init__.py
– level3.py
In this case if you retrieve you can do importlib.import_module("level3"), yous'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
importlib.import_module(".level3", "level1.level")
or you can practice
importlib.import_module("level1.level2.level3").
Run Python code using runpy
Runpy module locates and executes a Python script without importing it. Usage is pretty simple equally you can hands telephone call the module proper name inside of run_module().
To execute our code1.py module using runpy. Hither'south what we will do.
>>> import runpy >>> runpy.run_module(mod_name="code1")
Run Python Lawmaking Dynamically
We are going to accept a await at exec() function to execute Python scripts dynamically. In Python 2, exec function was actually a statement.
Here's how it helps you lot execute a Python code dynamically in case of a cord.
>>> print_the_string = 'print("Dynamic Lawmaking Was Executed")' >>> exec(print_the_string)
Dynamic Lawmaking Was Executed
Withal, 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 similar Office + F5 or simply F5(depending on your Os).
Here's an example of Python script being executed in IDLE.
Source: pitt.edu
However, note that you practise not control the virtual surroundings like how you typically would from a command line interface execution.
That's where IDEs and Advanced text editors are far meliorate than Code Editors.
Running Python Scripts from an IDE
When it comes to executing scripts from an IDE, you can not but run your Python code, just 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
What if there was a way to run a Python script just by double clicking on it? You can actually do that by creating executable files of your lawmaking. For example, in the case of Windows OS, you can merely create a .exe extension of your Python script and run it by double clicking on it.
How to run Python scripts from some other Python script
Although we haven't already stated this, just, if y'all go back up and read, yous'll observe that you can:
- Run a Python script via a command line that calls some other Python script in it
- Use a module like import to load a Python script
That'due south it!
Fundamental Takeaway
- You lot can write a Python code in interactive and not interactive modes. One time you exit interactive style, you lose the data. So, sudo nano your_python_filename.py it!
- You can too run your Python Lawmaking via IDE, Code Editors or Control line
- There are different ways to import a Python code and use it for another script. Choice wisely and look at the advantages and disadvantages.
- Python reads the lawmaking yous write, translates information technology into bytecodes, which are then used as instructions – all of that happen when you lot run a Python script. And then, learn how to utilise bytecode to optimize your Python code.
Recommended Python Preparation
Course: Python 3 For Beginners
Over 15 hours of video content with guided teaching for beginners. Acquire how to create real earth applications and master the basics.
Source: https://www.pythonforbeginners.com/development/how-run-your-python-scripts
Posted by: blanchardhologe.blogspot.com
0 Response to "How To Run Python Script In Python Shell In Windows"
Post a Comment