I want to implement certain functionality using python that can be used in two ways:
- as simple command line script, like
python mylib.py
- by importing into other python code
My first attempts look like this.
mylib.py:
from __future__ import print_function
import sys
class A(object):
def __init__(self, args):
print("my args: {}".format(args))
def main():
a = A(sys.argv)
print("got {}".format(a))
main()
Which I can directly invoke, or use elsewhere, like usage.py:
import mylib
mylib.A("bla")
That works, but it seems the import causes main()
to be executed as well:
python scripts/using.py blub
my args: ['scripts/using.py', 'blub']
got <mylib.A object at 0x7ff17bc736d0>
my args: bla
Questions:
- Is there a way to prevent
main()
from running when I go forpython using.pl
?
And beyond that:
- Is this a good approach? Or are there well established best practices in python that I am violating here?
- In other words: are there things I should do differently?