4

I have a python file that I am not the maintainer of that looks like the code below. Without modifying the code to put everything under the if __name__, is there a way to import this from another module so I can execute it and pass arguments programmatically?

import configargparse

if __name__ == '__main__':
    args = get_args()
    #more code to execute...
John
  • 443
  • 1
  • 4
  • 8

1 Answers1

0

You can't, for the most part. That code isn't exposed in a useful fashion. If you are able to modify the source file, the typical solution would be to move all of that code out of the if __name__ == '__main__' block and put it into a main() function instead.

It's possible to use the execfile function to sort of do what you want, as described here, but this is an ugly solution for a number of reasons (the import statement is being used only for side effects, because you're cheating and using it to get the filename, and module level variables will probably not behave as you expect when referenced as module.var, as described in some of the comments on that page).

And even in this example, it's not clear that there's a useful way to pass arguments. I guess you could set sys.argv explicitly, but look how hacky this is already smelling...

larsks
  • 277,717
  • 41
  • 399
  • 399
  • I have it sort of working by launching command shells, but I was hoping for a cleaner solution without touching code that isn't mine. Thanks though. – John Jul 28 '16 at 19:34
  • 3
    how about using runpy https://docs.python.org/3/library/runpy.html? It looks like it is intended for this exact purpose – Mark Adamson Sep 15 '18 at 09:05
  • 6
    @MarkAdamson I got a trivial example working with `import runpy; runpy.run_module('other_main_module', run_name='__main__')` – sitaktif Nov 21 '19 at 15:21