bjskistad bjskistad - 2 months ago 10
Python Question

How to execute file in Python with arguments using import?

I read that you can execute a file using

import
like this

file.py:

#!/usr/bin/env python
import file2


file2.py:

#!/usr/bin/env python
print "Hello World!"


And file.py will print
Hello World
. How would I execute this file with arguments, using
import
?

Answer

Program arguments are available in sys.argv and can be used by any module. You could change file2.py to

import sys
print "Here are my arguments", sys.argv

You can use the argparse module for more complex parsing.