Python how to execute file
Python how to execute file
How to Execute a File with Arguments in Python?
In this article, you’ll learn three ways to execute Python and non-Python programs from within a Python program.
Table of Contents
Method 1: Execute a File with Subprocess
Challenge: In Python, sometimes you need to execute another file, script, or program from within your own Python program and provide arguments.
There are a number of ways to do this, but I find the most straightforward to be with the “subprocess” import.
Sometimes, command line arguments can be complex and building out the list of arguments isn’t easy. I recommend playing around with the shlex library in an interactive terminal until you get a hang of it. You won’t need this in your production code, but might help make the concept more clear.
If after following these steps you’re still struggling to get your command to execute, consider the following: using the full path of the file to be executed (e.g. /home/user/script.py or C:\Program Files\Python 3.9\python.exe ), checking the permissions of the file you are attempting to execute to ensure it is in fact executable, checking for typos or case sensitivity.
In summary, the steps to execute a file with arguments from within a Python script are:
Now that we’ve covered how to execute a file with arguments, how can we create a Python script for ourselves that handles command line arguments?
Method 2: Execute a Python File with Arguments Using sys.argv
In order to pass arguments to your Python script, you will need to import the sys module. Once this module is imported in your code, upon execution sys.argv will exist, containing a list of all of the arguments passed to your script.
Consider the following script:
Notice that even though only two arguments were provided to the script, three arguments are listed. Element 0 of the list is always the name of the script itself. If the user renames the script on their endpoint, sys.argv[0] will reflect that name.
Often, when writing a program in Python it is important to know how many arguments are passed to the script for the purposes of error checking. If insufficient parameters are supplied by the user, a helpful error message giving usage instructions could be provided.
Consider the following code:
This is the rough and rudimentary way of processing command line arguments. In summary:
Another thing to consider is that Python also has a module named argparse that allows us to do more with command line arguments in a more readable way, as well as easily handle optional and positional parameters.
Now that you know how to incorporate command line arguments into your script, how do you use them if you’re using an IDE like PyCharm?
Method 3: Execute a Python File with Arguments in PyCharm
Inside of the PyCharm development environment, the top toolbar will include a Run tab. Click on it and choose “Edit Configurations”. A new window will pop up that will allow you to enter in the necessary parameters to execute your script.
This works identically to passing arguments via the command line.
Execute a file with arguments in Python shell
I would like to run a command in Python Shell to execute a file with an argument.
For example: execfile(«abc.py») but how to add 2 arguments?
13 Answers 13
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
Actually, wouldn’t we want to do this?
Note that when abc.py finishes, control will be returned to the calling program. Note too that abc.py can call quit() if indeed finished.
execfile runs a Python file, but by loading it, not as a script. You can only pass in variable bindings, not arguments.
For more interesting scenarios, you could also look at the runpy module. Since python 2.7, it has the run_path function. E.g:
You’re confusing loading a module into the current interpreter process and calling a Python script externally.
The former can be done by import ing the file you’re interested in. execfile is similar to importing but it simply evaluates the file rather than creates a module out of it. Similar to «sourcing» in a shell script.
The latter can be done using the subprocess module. You spawn off another instance of the interpreter and pass whatever parameters you want to that. This is similar to shelling out in a shell script using backticks.
How To Execute a File Within the Python Interpreter
No matter the stage of your Python development career, you probably already appreciate the importance of running and testing your code. This is the only way to ensure it works as planned and does what you need it to do. But how do you actually run scripts and code? This article will give you a brief overview of the various methods available.
Table of Contents
What is a Python Interpreter
To start with let’s just clarify what the Python Interpreter actually is. I believe the simplest description is the best – it interprets the Python code you write and makes it understandable to the computer you want to run the code on.
Running Python Scripts
To start with, let’s create a test script. I will use the script below which I will save in a file called test_script.py in the directory C:\Users\Rikesh :
All the methods outlined below look at different ways of executing this one simple line of code, using a Windows 10 machine running Python v.3.8.6.
Method 1: Using the Command Line
For me, this is the simplest way of running your scripts. Whilst there may be variations in the specific syntax, the principle is the same – invoke the Python interpreter and then tell it the name of the script you want to run.
To walk through how this is done:
Open a command line prompt and navigate to the same working directory as your script:
Using the Command Line in Windows
If you are running Windows, you have a few more options for running your scripts from the command line.
py is the Python launcher utility that comes with Python installations on Windows. It will, by default, use the latest Python version that is installed on your machine. So, to run Python scripts on a Windows machine we can also use:
Method 2: Running Scripts Interactively Using Import
There may be times when it is impractical to run scripts or code through the command line, so we can also run them directly through the Python interactive shell. To start with, we need to open a Python interactive shell by typing python in our command line. Again, we need to make sure we are in the same working directory as our script.
We know this has worked when we see the ‘>>>’ which shows us we are in the Python shell.
If you have had any experience using Python, you will probably be familiar with the import module when importing scripts and libraries for later use. The import module also executes any code as part of this process as well, although this is only seen when visible output is being generated. Given our script is essentially a print statement, we can therefore use it to our advantage:
Be warned however that you can only run this command once per Python session. If you try to run the same command again in the same session it will not execute the file as the import operation has already been run:
Method 3: Running Scripts Interactively Using the Python Standard Library: Importlib
The import_module of importlib works in the same way as the standard import module described previously.
Whilst this has been successful as with the previous import module, the script can only be executed once as we are importing the script as a module. So if we try to run the code again, the script is not executed:
Method 4: Running Scripts Interactively Using the Python Standard Library: Runpy
The runpy module is used to locate and run Python modules without importing them first.
Within this module there are two functions that can help us execute our file : runpy.run_module() and runpy.run_path( ). Whilst I have included the code below, it should be noted that in addition to executing the script, it also returns the entire globals dictionary of the module. When I first tried this, my initial reaction was that there was an error as the print statement output was lost in the dictionary output.
Alternatively you can use run_path() which allows you to run a file based on location:
Method 5: The exec() Function
This is a built-in Python function that dynamically executes the Python script/code and can be used as follows:
When I initially saw this function, it appeared to be the most logical of all the interactive examples. As the command line indicates, we are opening the file ( ‘test_script.py’ ), reading it and then using the exec() function to execute. No dictionaries are printed and you can use this function multiple times with no issues. In my opinion, this is the simplest and most effective way of running Python scripts interactively.
However, whilst it appears to work well and is recommended on sites such as stackoverflow, many feel it is the method of ‘last resort’. They consider it to be slow, unpredictable and can be open to security issues. Caution is therefore recommended in using this function.
Summary
As you can see, there are various ways of executing files within the Python Interpreter – which makes sense as Python is such a versatile language. The best way of executing files appears to be dependent on multiple factors including the version of Python being used, the actual script and code being executed – and most importantly user preference.
Related Tutorials
Why Finxter?
Learning Resources
Execute Python scripts
Execute Python scripts in the terminal or an IDE. Python files have the .py extension. Whenever you make a Python script, save it as name.py
A simple program (hello.py) is shown below. The first line indicates that we want to use the Python interpreter. The 3rd line outputs a line of text “hello wlrd” to the screen.
The text below can be copied into a text editor and save as hello.py. Python works with files that end in .py.
You can use any text editor to create a Python program. I recommend using a text editor that supports syntax highlighting (text colouring) and line numbers.
Run Python
Run from terminal
You can start a Python program with the terminal or command line. This works on all platforms (Mac OS, Windows, Linux).
To open a terminal on Windows: press the windows key + r key (run program), type cmd or command and press enter.
On Mac OS use finder to start a terminal. You can hit command+space and type terminal, then hit enter.
Start program
To start the program, we have to open the command line and type:
For this to work you need to be in the correct directory. That means, the directory where your python program is located.
On Mac OS and Linux you can see the current directory with the command pwd.
If you use Windows the directory is shown in the command line title bra.
To change directory use the command ‘cd’ like this ‘cd /home/user/pythonprojects’ or ‘cd C:\Projects\’.
Run from IDE
In the PyCharm IDE:
Other IDEs have a similar process to run a Python program (start project, add file, run button).
Output
You should see a line of text showing “hello world”.
Exercise
Try the exercises below:
After completing these continue with the next exercise.
How to Run or Execute Python Program on Windows
In this tutorial, learn how to execute Python program or code on Windows. Execute Python program on Command prompt or use Python IDLE GUI mode to run Python code.
How to Execute Python Program Using Command Prompt
Here is the simple code of Python given in the Python file demo.py. It contains only single line code of Python which prints the text “Hello World!” on execution.
So, how you can execute the Python program using the command prompt. To see this, you have to first open the command prompt using the ‘window+r’ keyboard shortcut. Now, type the word ‘cmd’ to open the command prompt.
You can use the cmd command ‘cd’ to change the directory location. Use ‘cd..’ to come out of directory and “cd” to come inside of the directory. Get the file location where you saved your Python file.
To execute the Python file, you have to use the keyword ‘Python’ followed by the file name with extension. See the example given in the screen above with the output of the file.
You can also execute the code directly in the interactive mode with the next section.
Interactive Mode to Execute Python Program
To execute the code directly in the interactive mode. You have to open the interactive mode. Press the window button and type the text “Python”. Click the “Python 3.7(32 bit) Desktop app” as given below to open the interactive mode of Python.
You can type the Python code directly in the Python interactive mode. Here, in the image below contains the print program of Python.
Press the enter button to execute the print code of Python. The output gives the text ‘”Hello World!” after you press the enter button.
Type any code of Python you want to execute and run directly on interactive mode.
However, you can also execute the Python program using the Python GUI. You have to use the below section and follow the examples with pictures.
Using IDLE(Python GUI) to Execute Python Program
Another useful method of executing the Python code. Use the Python IDLE GUI Shell to execute the Python program on Windows system.
Open the Python IDLE shell by pressing the window button of the keyboard. Type “Python” and click the “IDLE(Python 3.7 32 bit)” to open the Python shell.
It contains the simple Python code which prints the text “Hello World!”. In order to execute the Python code, you have to open the ‘run’ menu and press the ‘Run Module’ option.
You can also use the keyboard shortcut ‘F5’ to run the Python code file.
A new shell window will open which contains the output of the Python code. Create your own file and execute the Python code using this simple method using Python IDLE.
A Python IDLE mode can also execute the direct code.
To execute the direct code, you have to write the Python code directly on the Python IDLE shell. Here, a print function of Python prints the text “Hello World” on execution.
Hope, you like this tutorial of how to run Python program on windows.