3

I have a program main.py which uses sys.argv to run functions from other modules:

e.g:
python main.py gui should run the main function in gui.py
python main.py server start should run the main function in server.py.

But if the program simply runs server.main() in this example, sys.argv is ['main.py', 'server', 'start'] when it should be [something, 'start'].

Since server.py also relies on the correct argv, I need to make sure that the argv used in server.py is different from the argv recieved by main.py. How can I change these values?

1 Answers1

7

sys.argv can just be replaced:

saved_argv = sys.argv
try:
    sys.argv = ['./server.py', 'start']
    server.main()
finally:
    sys.argv = saved_argv

That said, the fact that you want to do this (outside of a unit test, where this pattern is actually pretty common) indicates that you might want to work on building a better API for your modules.

For example, perhaps server.py can have a main function for when it's run as a standalone module, but also another function like run_server() which can take its own arguments rather than relying on sys.argv.

Daniel Pryden
  • 59,486
  • 16
  • 97
  • 135