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?
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With