I created a module called parameter.py and wanted to import it using sys.argv as shown below.
import sys
from sys.argv[1] import *
But when I run the python file I get the following error:
python test.py parameter
File "test.py", line 17
from sys.argv[1] import *
^
SyntaxError: invalid syntax
Why doesn't it work and what else can I do to make it work?
Variables are not allowed in import statement
import sys
__import__(sys.argv[1])
Global Import
import sys
globals().update(__import__(sys.argv[1]).__dict__)
Example Usage
import sys
sys.argv.append("math")
pi = __import__(sys.argv[-1]).pi
print(pi)
Or
import sys
sys.argv.append("math")
globals().update({k: v for k, v in __import__(sys.argv[-1]).__dict__.items() if not k.startswith("__")})
print(pi)
print(__name__)
Output
3.141592653589793
__main__