2

I want to import variables from a file that is specified as an argument. How do I achieve that?

For example: Say my file is myfile.py I call it as

python myfile.py service.py

Now I want to import the variables of service.py in my myfile.py.

How do I go about this?

Ryan Haining
  • 35,360
  • 15
  • 114
  • 174
user2359303
  • 261
  • 2
  • 7
  • 15

2 Answers2

2

inside of myfile.py insert an __import__

module = __import__(sys.argv[1].replace('.py', ''))

will import the first command line argument as module which you can then use as any other module that was imported. The return value from __import__ is a module.

Really in python, import mod is just a shorthand for mod = __import__('mod'), and you are allowed to call the __import__ function if you do so choose.

An example:

>>> module = __import__("math")  #same as "import math as module"
>>> module.sqrt(16)
4.0

If you wish to pollute your global namespace with the contents of the command line argument, you can read about how to do a from * import here: How does one do the equivalent of "import * from module" with Python's __import__ function?

Community
  • 1
  • 1
Ryan Haining
  • 35,360
  • 15
  • 114
  • 174
-1

There are two questions that you could be asking. The could be how do I import files to process on from the command line? You can get the strings like this

fileName = sys.argv(1)
fileHandle = open(fileName, 'r')

If you want to find arguments in that file, It is a little bit harder. I would need to know more about the format to help you.

dakillakan
  • 240
  • 2
  • 9