raggot
raggot

Reputation: 1012

How to import the main function from a Python file not defining "def main" in it?

I am writing a Python (3.5) module in which I'd like to make use of an existing Python module from an open source project. The module I want to import contains:

but does not contain a def main(args) function.

Because there is no actual main function, I cannot import it by means of import module and use it as module.main(). Although I did find options to separately execute it as script via the commands os.system() and subprocess.Popen(), I am actually looking for a way to make this call an integral part of my code.

I understand I can add the def main() part myself in the original code, but because it comes from an open source project, I am looking for ways to leave it untouched, so that I don't need to maintain it myself if it gets updated.

I have gone through other very similar questions, such as this and this that could not solve my issue. This answer gives me the feeling what I am trying to do is not trivial.

Is there any way to do this?

Upvotes: 0

Views: 399

Answers (1)

ChootsMagoots
ChootsMagoots

Reputation: 670

When you import a module for the first time, (as distinguished from importing a function), all code in that module executes. That means functions become defined, global variables become defined, etc. The reason we write an if __name__ == "__main__": block is so that when importing a module, that code does not execute (it will only execute if name == "main"). If you simply remove the if __name__ == "__main__": line and fix the indentation, that code will execute when you import the module. take this module hello.py for example:

def hello_world():
    print("Hello world")
if __name__ == "__main__":
    hello_world()

then if we import:

import hello
hello_world()

The code below will do the same thing as this case where the first module is again hello.py:

def hello_world():
    print("hello world")
hello_world()

module to be executed:

import hello

I recommend you do not do it this way though, you really should just edit to include a main function.

Upvotes: 2

Related Questions