Search code examples
pythonbashargvsys

Using sys.argv from another .py file - python


I have a file (test.py) that receives sys.argv from the console/bash:

import sys

def main():
    ans = int(sys.argv[1])**int(sys.argv[1])
    with open('test.out', 'w') as fout:
        fout.write(str(ans))

if __name__ == '__main__':
    main()

Usually, I could just do $ python test.py 2 to produce the test.out file. But I need to call the main() function from test.py from another script.

I could do as below in (call.py) but is there any other way to run pass an argument to sys.argv to main() in `test.py?

import os

number = 2
os.system('python test.py '+str(number))

Please note that I CANNOT modify test.py and I also have a main() in call.py which does other things.


Solution

  • You can use your program as it is. Because, irrespective of the file invoked by python, all the python files will get the command line arguments passed.

    But you can make the main function accept sys.argv as the default parameter. So, main will always take the sys.argv by default. When you pass a different list, it will take the first element and process it.

    test.py

    import sys
    
    def main(args = sys.argv):
        ans = int(args[1])**int(args[1])
        with open('test.out', 'w') as fout:
            fout.write(str(ans))
    

    call.py

    import sys, test
    test.main()