Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do I determine whether a python script is imported as module or run as script?

Tags:

python

module

The question is rather straightforward but not answered by searching. How do I determine in a python script whether this script is imported as a module or run as a script? Is there a difference at all in python?

The problem is, that I want to evaluate the command line parameters only if run as a script, but not if the module is only imported to use it in another script. (I want to be able to use one script as both library and program.) I am afraid the vanilla way would be to build the lib and a second script that uses it, but I'd like to have a second option for small tool/libs.

like image 668
Don Johe Avatar asked Sep 07 '09 11:09

Don Johe


People also ask

What is the difference between Python scripts and modules?

A script is a Python file that's intended to be run directly. When you run it, it should do something. This means that scripts will often contain code written outside the scope of any classes or functions. A module is a Python file that's intended to be imported into scripts or other modules.

How do you check if a module is imported?

Use: if "sys" not in dir(): print("sys not imported!")

Why is Python running a module when I import it?

Because this is just how Python works - keywords such as class and def are not declarations. Instead, they are real live statements which are executed. If they were not executed your module would be empty.


1 Answers

from python docs:

When you run a Python module with

python fibo.py

the code in the module will be executed, just as if you imported it, but with the __name__ set to "__main__". That means that by adding this code at the end of your module:

if __name__ == '__main__':     # Running as a script 

you can make the file usable as a script as well as an importable module, because the code that parses the command line only runs if the module is executed as the “main” file

like image 144
Nadia Alramli Avatar answered Oct 05 '22 02:10

Nadia Alramli