2

I would like to run this function from a script instead of the command line. For example, the function is:

def main():
    parser = argparse.ArgumentParser(description='Caffe prototxt to mxnet model parameter converter.\
                    Note that only basic functions are implemented. You are welcomed to contribute to this file.')
    parser.add_argument('caffe_prototxt', help='The prototxt file in Caffe format')
    parser.add_argument('caffe_model', help='The binary model parameter file in Caffe format')
    parser.add_argument('save_model_name', help='The name of the output model prefix')
    args = parser.parse_args()
    ...

How can i run it like this?

file.main('file_1.csv', 'file_2.csv', 'name')

And why would someone write a function that I can only run from the command line? It feels inconvenient.

Leopd
  • 41,333
  • 31
  • 129
  • 167
kklw
  • 858
  • 3
  • 13
  • 28
  • This function is written because it's usually bad to write code under `if name == '__main__'`. – wRAR Mar 27 '16 at 07:51
  • Hi @wRAR, do you have any references for me to read up why is it so? Thanks a lot. – kklw Mar 27 '16 at 07:59
  • It's simple, you can't call code written under `if name == '__main__'` as easily as code written in a separate function, when you need to call it from a different place. – wRAR Mar 27 '16 at 08:03
  • ah. i mean why not just write a function with parameters. eg. def main(file1, file2, name):... @wRAR – kklw Mar 27 '16 at 09:33
  • You may want to call `main()` from different scripts etc. OTOH it is a very good idea to separate the actual code that works with parsed arguments to a separate function. – wRAR Mar 27 '16 at 09:38
  • What does `main` do with `args`? The part you showed us just parses the command line (something has to do that if it can be run as a script). The real action follows. Does it, for example, pass `args` (or its attributes) to another function? – hpaulj Mar 27 '16 at 15:53

2 Answers2

4

You can use sys.argv:

import sys

sys.argv.extend(['file_1.csv', 'file_2.csv', 'name'])
file.main()
Mike Müller
  • 82,630
  • 20
  • 166
  • 161
0

You probably want to do a little light re-factoring. Pull the argparse stuff into its own method which then calls main(args), and then instantiate your own argparse.Namespace() that you pass into main with your configuration.

And yes, I agree the code would be better if it was already factored this way. But people code pragmatically to meet their immediate needs.

Leopd
  • 41,333
  • 31
  • 129
  • 167