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...
3
  • Definitely a duplicate, thanks. After reading that it looks like the answer is it isn't possible. Commented Jul 28, 2016 at 19:33
  • No, unless the module just uses if __name__ == '__main__' to call a main() function, you can't do it unfortunately. Commented Jul 28, 2016 at 19:34
  • See this answer: stackoverflow.com/a/71967141/1364242 Commented Apr 22, 2022 at 10:18

1 Answer 1

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...

Sign up to request clarification or add additional context in comments.

4 Comments

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.
how about using runpy docs.python.org/3/library/runpy.html? It looks like it is intended for this exact purpose
@MarkAdamson I got a trivial example working with import runpy; runpy.run_module('other_main_module', run_name='__main__')
You might add that as an answer, since I was searching quite some time before reading these comments! Maybe also mention it in related questions like here and here

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.