skistaddy
skistaddy

Reputation: 2224

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?

Upvotes: 0

Views: 1436

Answers (2)

Bharel
Bharel

Reputation: 26901

Import is not meant for execution of scripts. It is used in order to fetch or "import" functions, classes and attributes it contains.

If you wish to execute the script using a different interpreter, and give it arguments, you should use subprocess.run().


In Python 2 you may use subprocess.call() or subprocess.check_output() if you need the programs output.

Upvotes: 1

tdelaney
tdelaney

Reputation: 77337

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.

Upvotes: 1

Related Questions