Python Forum

Full Version: module either imported by a command or itself run as a command
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
i have a module that sometimes i want to run as a command. the problem is that the script that is importing it could be used as a command. thus, there are two scenarios in which variable __name__ would have the value "__main__". but. i want to be able to distinguish these two scenarios so that the module can stay being one file (perhaps named "foo.py") and be imported by a script (done simply like "import foo") where the importing script (perhaps named "bar.py") is run as a command. how can i make the module determine that it is invoked as a command without being confused by the importing script being invoked as a command.
I would simply write the main code in a function, for example
# foo.py

def spam():
    ...

def eggs():
    ...

def main_task():
    print('Running main task')

if __name__ ==  '__main__':
    main_task()
Now you can use it in three different ways
# bar.py

# first way: import as a module
import foo
# second way: execute main task
import foo
foo.main_task()
# third way: run as subprocess
subprocess.run([sys.executable, 'foo.py'])
that seems to work. __name__ has "foo", presumably the name it is imported as.
Output:
lt1a/forums/1 /home/forums 20> box foo.py bar.py +----<foo.py>-----------------------------------------------------+ | def spam(): | | print('Green ham') | | | | def eggs(): | | print('Green eggs') | | | | def main_task(): | | print('Running main task where __name__ is',repr(__name__)) | | | | if __name__ == '__main__': | | main_task() | +-----------------------------------------------------------------+ +----<bar.py>-------------------------------------------------+ | ## # first way: import as a module | | ## import foo | | # second way: execute main task | | import foo | | print('foo') | | print('running main task where __name__ is',repr(__name__)) | | foo.main_task() | | print('bar') | | ### third way: run as subprocess | | ##subprocess.run([sys.executable, 'foo.py']) | +-------------------------------------------------------------+ lt1a/forums/1 /home/forums 21> python3 foo.py Running main task where __name__ is '__main__' lt1a/forums/1 /home/forums 22> python3 bar.py foo running main task where __name__ is '__main__' Running main task where __name__ is 'foo' bar lt1a/forums/1 /home/forums 23>