Question

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.

Was it helpful?

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()

OTHER TIPS

Write that like:

import sys

def main(num):
    ans = int(num)**int(num)
    with open('test.out', 'w') as fout:
        fout.write(str(ans))

if __name__ == '__main__':
    main(sys.argv[1])

so that your main() function doesn't have to know about sys.argv - it just handles the parameters being passed in to it.

Without modifying test.py you can still run it just as you have it, just do call.py:

import test

test.main()

then $ python call.py ARG will still work. Since you've already imported sys in test, you don't need to reimport it unless you want to use sys in call.py. Note that sys.argv[0]=='call.py' not test.py if use test through call.

Create a function to do your calculation and file writing, which can be called from any other module:

power.py:

import sys

def power(arg):    
    ans = arg ** arg
    with open('test.out', 'w') as fout:
        fout.write(str(ans))

if __name__ == '__main__':
    power(int(sys.argv[1]))

other.py:

import power

power.power(2)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top