0

I got answer for how to pass file as argument here How to access variables from file passed through command line

But I am asking separately since don't wanna mix two. I am able to access variables in passed file as __import__(sys.argv[1]) and called python test.py config. But can I call config.py file by giving pythonpath? e/g/ python test.py ~/Desktop/config or PYTHONPATH='~/Desktop/' python test.py config? Because if I do this I get no module error.

Community
  • 1
  • 1
user2661518
  • 2,677
  • 9
  • 42
  • 79

1 Answers1

1

You're trying to import a python module using the __import__ call. It only accepts the module name. If you need to add a directory to the PYTHONPATH, you can add it to sys.path and then import the module:

#File: ~/Projects/py/main.py

import sys

python_path = sys.argv[1]
module_name = sys.argv[2]

sys.path.insert(1, python_path)

print "Importing {} from {}".format(module_name, python_path)
__import__(module_name)

Now I created another file named masnun.py on ~/Desktop:

# File: ~/Desktop/masnun.py

print "Thanks for importing masnun.py"

Now I try to run main.py like this:

python main.py ~/Desktop masnun

So I am passing the Python path as argv[1] and the module name as argv[2]. Now it works. I get this output:

enter image description here

masnun
  • 11,635
  • 4
  • 39
  • 50
  • this I can do in test.py But how can I declare pythonpath through command line because at command line I am running `python test.py config` – user2661518 Jan 04 '16 at 19:18
  • OK, I updated the answer with detailed codes and commands. Please see if it helps now. – masnun Jan 04 '16 at 19:30