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?

Bharel
  • 23,672
  • 5
  • 40
  • 80
baranskistad
  • 2,176
  • 1
  • 21
  • 42

2 Answers2

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.

Bharel
  • 23,672
  • 5
  • 40
  • 80
  • 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. – tdelaney Sep 23 '16 at 22:16
  • I'm using 2.7, is there any way to do this in 2.7? Or do I need to upgrade to 3.x? – baranskistad Sep 23 '16 at 22:28
  • @bjskistad added for Python 2. – Bharel Sep 23 '16 at 22:32
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.

tdelaney
  • 73,364
  • 6
  • 83
  • 116
  • 1
    He doesn't want the arguments to be received from terminal. He wants to send them through the "import" statement. – Bharel Sep 23 '16 at 22:18
  • @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 Sep 23 '16 at 22:22
  • @tdelaney I'm sorry, apparently my instructions weren't clear enough. But I want to **execute** a file using import, if possible. – baranskistad Sep 23 '16 at 22:27
  • @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. – tdelaney Sep 23 '16 at 22:31
  • 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? – tdelaney Sep 23 '16 at 22:34