0

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?

monosix
  • 3
  • 2
  • 1
    "a module called parameter.py that I created using sys.argv" What exactly do you think this means? How do you believe you are "creating" modules "using sys.argv", and why do you think `parameter.py` is such a module? (Please be sure to distinguish the *module name* from the *file name*.) – Karl Knechtel Apr 16 '21 at 05:43
  • 2
    If names in `import` statements would be evaluated as expressions, then `import foo` would mean “import the module with the name that variable `foo` contains”, not “import module foo”… – deceze Apr 16 '21 at 05:44
  • 1
    It's also completely unclear what *problem you hope to solve* by doing this. If you don't know ahead of time which module will be imported, how do you know that importing it is a good idea? – Karl Knechtel Apr 16 '21 at 05:44
  • 1
    Anyway, the syntax doesn't make any sense for the same reason that `'parameter' = 3` doesn't make any sense. Strings are not the same as identifiers. – Karl Knechtel Apr 16 '21 at 05:45
  • Sorry for the confusion! I meant to say I created a module that I want to import using sys.argv. I edited my question to be more clear! – monosix Apr 16 '21 at 08:03

1 Answers1

0

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__
BaiJiFeiLong
  • 3,716
  • 1
  • 30
  • 28
  • Thanks for your comment! I tried both out and seems like the globals method does import it correctly (exactly what I wanted!) except that `__name__` is now also switched to the name of the module I have imported. If I were to import the module using `from module import *`, the `__name__` remains as `__main__`. What's the difference here? And is there a way I could import using sys.argv (like it did with globals()) while keeping `__name__` as `__main__`? – monosix Apr 16 '21 at 08:19
  • @monosix Sorry for forgetting to exclude members like `__name__`, `__doc__`, `__package__`, `__loader__`, `__spec__`. I've changed the answer now. – BaiJiFeiLong Apr 16 '21 at 08:30