Posts: 4,647
Threads: 1,494
Joined: Sep 2016
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.
Tradition is peer pressure from dead people
What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Posts: 4,647
Threads: 1,494
Joined: Sep 2016
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>
Tradition is peer pressure from dead people
What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.