2

Currently I have config.py in my package and I can access variables defined in config.py from other py files as

import config
var1 = config.var1

First of all, Can I pass file as argument? test.py config.py

But is there way to pass config file through command line as argument and access the variables defined in it? I see there is sys module to get arguments passed through command line. But can I get variables defined in passed file?

edit Now 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.

8
  • 1
    Are you referring to command-line parameters, like my_script.py a=1 b=abc d=1,23,5? Commented Jan 4, 2016 at 17:47
  • Look at this topic stackoverflow.com/questions/301134/… Commented Jan 4, 2016 at 17:49
  • Just get the file name from sys.argv, then import the file and access the variables. Commented Jan 4, 2016 at 17:50
  • @ChadS. I tried sys.argv but I get error import by filename is not supported I tried __import__(sys.argv[1]) and passed python test.py ./config.py Commented Jan 4, 2016 at 18:20
  • @user2661518: What if you strip off the path prefix and the py suffix? Also, why not store the variables in a language agnostic way (e.g. JSON or XML) and use a Python library to read the variables from the file? Commented Jan 4, 2016 at 18:25

1 Answer 1

3

What you do with import config is make all names from config.py available in your script.

You can do this using __import__(sys.args[1]) like stated in answers to this question.

But for actual program configuration, sure do take a look at the argparse module!

p = argparse.ArgumentParser(description="...")
p.add_argument("--var1", type=int)
p.add_argument("--var2", type=str)

config = p.parse_args() # will look at sys.args by default

if config.var1 > 10:
    ....
Sign up to request clarification or add additional context in comments.

3 Comments

With argparse you can't pass the file, right? I tried sys.argv but I get error import by filename is not supported I tried __import__(sys.argv[1]) and passed python test.py ./config.py
got it ! I ran it as python test.py config But how can call config file through path? e.g. python test.py ~/Desktop/config
On windows, you can set PATH=%PATH%;c:/dir/with/script, and then you can run your script from anywhere.

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.