Reputation: 4515
def nearbin():
parser = argparse.ArgumentParser(description = "choose near bin")
parser.add_argument("-bin", type=int,action = "store", default = "10", help="bin number")
args = parser.parse_args()
bin = args.bin
print bin
return f(bin)
if __name__ == "__main__":
nearbin()
In command line, I can use "python test.py -bin 10" to run the program
If I want to import test
in another python script and use function nearbin(bin)
in another script, how can I do this?
Upvotes: 1
Views: 159
Reputation: 179392
My usual approach:
def nearbin(bin):
...
def main(args):
parser = argparse.ArgumentParser(...)
...
args = parser.parse_args(args)
nearbin(args.bin)
if __name__ == '__main__':
sys.exit(main(sys.argv[1:]))
This lets you support direct command-line invocation (./script.py -bin 20
), invocation with command line args (main("-bin 20".split())
), and programmatic invocation (nearbin(20)
).
Upvotes: 3
Reputation: 17312
Then you should parse the command line arguments inside the __main__
check and pass them to nearbin
, something like this:
def nearbin(bin):
print bin
return f(bin)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description = "choose near bin")
parser.add_argument("-bin", type=int,action = "store", default = "10", help="bin number")
args = parser.parse_args()
bin = args.bin
nearbin(bin)
Upvotes: 2