- How to Run a Python Script
- Different ways to run Python Script
- 2. Using the Python Interpreter¶
- 2.1.1. Argument Passing¶
- 2.1.2. Interactive Mode¶
- 2.2. The Interpreter and Its Environment¶
- 2.2.1. Source Code Encoding¶
- Table of Contents
- Python Run Another Python Script
- Use the import Statement to Run a Python Script in Another Python Script
- Use the execfile() Method to Run a Python Script in Another Python Script
- Use the subprocess Module to Run a Python Script in Another Python Script
How to Run a Python Script
Python is a well known high-level programming language. The Python script is basically a file containing code written in Python. The file containing python script has the extension ‘ .py ’ or can also have the extension ‘ .pyw ’ if it is being run on a windows machine. To run a python script, we need a python interpreter that needs to be downloaded and installed.
Here is a simple python script to print ‘ Hello World! ’:
Here, the ‘ print() ’ function is to print out any text written within the parenthesis. We can write the text that we want to be printed using either a single quote as shown in the above script or a double quote.
If you are coming from any other language then you will also notice that there is no semicolon at the end of the statement as with Python, you no need to specify the end of the line. And also we don’t need to include or import any files to run a simple python script.
There is more than one way to run a python script but before going toward the different ways to run a python script, we first have to check whether a python interpreter is installed on the system or not. So in windows, open ‘cmd’ (Command Prompt) and type the following command.
This command will give the version number of the Python interpreter installed or will display an error if otherwise.
Different ways to run Python Script
Here are the ways with which we can run a Python script.
- Interactive Mode
- Command Line
- Text Editor (VS Code)
- IDE (PyCharm)
- Interactive Mode:
In Interactive Mode, you can run your script line by line in a sequence. To enter in an interactive mode, you will have to open Command Prompt on your windows machine and type ‘ python ’ and press Enter . Example 1:
Run the following line in the interactive mode:Output:
Output: Example 3:
Run the following line one by one in the interactive mode:Output:Note: To exit from this mode, press ‘ Ctrl+Z ’ and then press ‘Enter’ or type ‘ exit() ’ and then press Enter .
Command Line
To run a Python script store in a ‘ .py ’ file in command line, we have to write ‘ python ’ keyword before the file name in the command prompt.You can write your own file name in place of ‘hello.py’. Output:
- Text Editor (VS Code)
To run Python script on a text editor like VS Code (Visual Studio Code) then you will have to do the following:- Go in the extension section or press ‘ Ctrl+Shift+X ’ on windows, then search and install the extension named ‘ Python ’ and ‘ Code Runner ’. Restart your vs code after that.
- Now, create a new file with the name ‘hello.py’ and write the below code in it:
Output:
- IDE (PyCharm)
To run Python script on a IDE (Integrated Development Environment) like PyCharm, you will have to do the following:- Create a new project.
- Give a name to that project as ‘GfG’ and click on Create.
- Select the root directory with the project name we specified in the last step. Right click on it, go in New and click on ‘Python file’ option. Then give the name of the file as ‘hello’ (you can specify any name as per your project requirement). This will create a ‘hello.py’ file in the project root directory.
Note: You don’t have to specify the extension as it will take it automatically. - Now write the below Python script to print the message:
2. Using the Python Interpreter¶
The Python interpreter is usually installed as /usr/local/bin/python3.11 on those machines where it is available; putting /usr/local/bin in your Unix shell’s search path makes it possible to start it by typing the command:
to the shell. 1 Since the choice of the directory where the interpreter lives is an installation option, other places are possible; check with your local Python guru or system administrator. (E.g., /usr/local/python is a popular alternative location.)
On Windows machines where you have installed Python from the Microsoft Store , the python3.11 command will be available. If you have the py.exe launcher installed, you can use the py command. See Excursus: Setting environment variables for other ways to launch Python.
Typing an end-of-file character ( Control — D on Unix, Control — Z on Windows) at the primary prompt causes the interpreter to exit with a zero exit status. If that doesn’t work, you can exit the interpreter by typing the following command: quit() .
The interpreter’s line-editing features include interactive editing, history substitution and code completion on systems that support the GNU Readline library. Perhaps the quickest check to see whether command line editing is supported is typing Control — P to the first Python prompt you get. If it beeps, you have command line editing; see Appendix Interactive Input Editing and History Substitution for an introduction to the keys. If nothing appears to happen, or if ^P is echoed, command line editing isn’t available; you’ll only be able to use backspace to remove characters from the current line.
The interpreter operates somewhat like the Unix shell: when called with standard input connected to a tty device, it reads and executes commands interactively; when called with a file name argument or with a file as standard input, it reads and executes a script from that file.
A second way of starting the interpreter is python -c command [arg] . , which executes the statement(s) in command, analogous to the shell’s -c option. Since Python statements often contain spaces or other characters that are special to the shell, it is usually advised to quote command in its entirety.
Some Python modules are also useful as scripts. These can be invoked using python -m module [arg] . , which executes the source file for module as if you had spelled out its full name on the command line.
When a script file is used, it is sometimes useful to be able to run the script and enter interactive mode afterwards. This can be done by passing -i before the script.
All command line options are described in Command line and environment .
2.1.1. Argument Passing¶
When known to the interpreter, the script name and additional arguments thereafter are turned into a list of strings and assigned to the argv variable in the sys module. You can access this list by executing import sys . The length of the list is at least one; when no script and no arguments are given, sys.argv[0] is an empty string. When the script name is given as ‘-‘ (meaning standard input), sys.argv[0] is set to ‘-‘ . When -c command is used, sys.argv[0] is set to ‘-c’ . When -m module is used, sys.argv[0] is set to the full name of the located module. Options found after -c command or -m module are not consumed by the Python interpreter’s option processing but left in sys.argv for the command or module to handle.
2.1.2. Interactive Mode¶
When commands are read from a tty, the interpreter is said to be in interactive mode. In this mode it prompts for the next command with the primary prompt, usually three greater-than signs ( >>> ); for continuation lines it prompts with the secondary prompt, by default three dots ( . ). The interpreter prints a welcome message stating its version number and a copyright notice before printing the first prompt:
$ python3.11 Python 3.11 (default, April 4 2021, 09:25:04) [GCC 10.2.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>>
Continuation lines are needed when entering a multi-line construct. As an example, take a look at this if statement:
>>> the_world_is_flat = True >>> if the_world_is_flat: . print("Be careful not to fall off!") . Be careful not to fall off!
For more on interactive mode, see Interactive Mode .
2.2. The Interpreter and Its Environment¶
2.2.1. Source Code Encoding¶
By default, Python source files are treated as encoded in UTF-8. In that encoding, characters of most languages in the world can be used simultaneously in string literals, identifiers and comments — although the standard library only uses ASCII characters for identifiers, a convention that any portable code should follow. To display all these characters properly, your editor must recognize that the file is UTF-8, and it must use a font that supports all the characters in the file.
To declare an encoding other than the default one, a special comment line should be added as the first line of the file. The syntax is as follows:
where encoding is one of the valid codecs supported by Python.
For example, to declare that Windows-1252 encoding is to be used, the first line of your source code file should be:
One exception to the first line rule is when the source code starts with a UNIX “shebang” line . In this case, the encoding declaration should be added as the second line of the file. For example:
#!/usr/bin/env python3 # -*- coding: cp1252 -*-
On Unix, the Python 3.x interpreter is by default not installed with the executable named python , so that it does not conflict with a simultaneously installed Python 2.x executable.
Table of Contents
Python Run Another Python Script
- Use the import Statement to Run a Python Script in Another Python Script
- Use the execfile() Method to Run a Python Script in Another Python Script
- Use the subprocess Module to Run a Python Script in Another Python Script
A basic text file containing Python code that is intended to be directly executed by the client is typically called a script, formally known as a top-level program file.
Scripts are meant to be directly executed in Python. Learning to run scripts and code is a fundamental skill to learn in the world of python programming. Python script usually has the extension ‘.py’ . If the script is run on a windows machine, it might have an extension, .pyw .
This tutorial will discuss different methods to run a Python script inside another Python script.
Use the import Statement to Run a Python Script in Another Python Script
The import statement is used to import several modules to the Python code. It is used to get access to a particular code from a module. This method uses the import statement to import the script in the Python code and uses it as a module. Modules can be defined as a file that contains Python definitions and statements.
def func1(): print ("Function 1 is active") if __name__ == '__main__': # Script2.py executed as script # do something func1()
import Script1.py def func2(): print("Function 2 is active") if __name__ == '__main__': # Script2.py executed as script # do something func2() Script1.func1()
Function 2 is active Function 1 is active
Use the execfile() Method to Run a Python Script in Another Python Script
The execfile() function executes the desired file in the interpreter. This function only works in Python 2. In Python 3, the execfile() function was removed, but the same thing can be achieved in Python 3 using the exec() method.
# Python 2 code execfile("Script1.py")
Use the subprocess Module to Run a Python Script in Another Python Script
The subprocess module is capable of spawning new processes and can also return their outputs. This is a new module and is intended to replace several older modules like os.system , which was previously used to run a Python script in another Python script.
def func1(): print ("Function 1 is active") if __name__ == '__main__': # Script2.py executed as script # do something func1()
import subprocess subprocess.call("Script1.py", shell=True)
Although all three methods work just fine, this method holds an advantage over the other two methods. Editing an existing Python script and putting all the code it contains into a subroutine is not needed in this method.
Vaibhhav is an IT professional who has a strong-hold in Python programming and various projects under his belt. He has an eagerness to discover new things and is a quick learner.