Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
How to call Python module from command line?
To call a Python module from the command line, you can use the python command followed by flags like -m or -c, or run the script file directly. This article covers the most common approaches with practical examples.
Running a Module with python -m
The -m flag tells Python to run a module by its module name (without the .py extension). Python searches sys.path for the module and executes its __main__ block −
~$ python -m module_name
For example, to run the built-in json.tool module for formatting JSON −
~$ echo '{"name":"Alice"}' | python -m json.tool
{
"name": "Alice"
}
For your own modules, ensure the file has an if __name__ == "__main__" guard so that code runs only when the module is executed directly.
Running a Script File Directly
The simplest approach is to run a .py file directly and use sys.argv to accept command-line arguments ?
Example
Create a file called my_script.py ?
import sys
def multiply(a, b):
return a * b
if __name__ == "__main__":
if len(sys.argv) != 3:
print("Usage: python my_script.py arg1 arg2")
else:
arg1 = int(sys.argv[1])
arg2 = int(sys.argv[2])
print(multiply(arg1, arg2))
Run it from the command line ?
~$ python my_script.py 5 7 35
Calling a Specific Function with python -c
The -c flag lets you pass a Python command as a string. This is useful for calling a specific function from a module without modifying the file ?
Example
Create a file called example.py ?
def add_numbers(num1, num2):
return num1 + num2
Call the function from the command line ?
~$ python -c "import example; print(example.add_numbers(2, 3))" 5
This imports the example module and calls add_numbers with arguments 2 and 3, then prints the result.
Example: Calling a Function with String Arguments
Given a file greetings.py ?
def greet(name):
return f"Hello, {name}!"
Call it from the command line ?
~$ python -c "import greetings; print(greetings.greet('Alice'))"
Hello, Alice!
Conclusion
Use python script.py with sys.argv for scripts that accept arguments, python -m module_name to run a module by name, and python -c for quick one-off function calls. Always include an if __name__ == "__main__" guard in modules meant to be both imported and executed directly.
