module either imported by a command or itself run as a command - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: General (https://python-forum.io/forum-1.html) +--- Forum: News and Discussions (https://python-forum.io/forum-31.html) +--- Thread: module either imported by a command or itself run as a command (/thread-41189.html) |
module either imported by a command or itself run as a command - Skaperen - Nov-24-2023 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. RE: module either imported by a command or itself run as a command - Gribouillis - Nov-25-2023 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']) RE: module either imported by a command or itself run as a command - Skaperen - Dec-04-2023 that seems to work. __name__ has "foo", presumably the name it is imported as.
|