0

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?

2

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

He doesn't want the arguments to be received from terminal. He wants to send them through the "import" statement.
@Bharel OP never stated where the arguments come from or how they are consumed in file2.py. He certainly did not say they were not standard program arguments.
@tdelaney I'm sorry, apparently my instructions weren't clear enough. But I want to execute a file using import, if possible.
@bjskistad - what do you mean by "execute"? Importing causes the module to be executed. Its __name__ is file2 instead of __main__ but otherwise it is pretty much the same as executing it directly from the command line.
Perhaps you could add a few lines to file2.py to show how you want to use the arguments and add some detail about where these arguments come from - is it from the command line? Is file1.py generating them?
1

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.

3 Comments

Yes and no. If you install a package, modules aren't in the system PATH and its common to include helper scripts in the PATH to run them. Also, this import technique lets you fiddle with the system environment before the target script is run.
I'm using 2.7, is there any way to do this in 2.7? Or do I need to upgrade to 3.x?
@bjskistad added for Python 2.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.