How to import module when module name has a '-' dash or hyphen in it?

后端 未结 5 1914
遇见更好的自我
遇见更好的自我 2020-11-28 03:27

I want to import foo-bar.py. This works:

foobar = __import__(\"foo-bar\")

This does not:

from \"foo-bar\" import *
<         


        
5条回答
  •  抹茶落季
    2020-11-28 04:06

    you can't. foo-bar is not an identifier. rename the file to foo_bar.py

    Edit: If import is not your goal (as in: you don't care what happens with sys.modules, you don't need it to import itself), just getting all of the file's globals into your own scope, you can use execfile

    # contents of foo-bar.py
    baz = 'quux'
    
    >>> execfile('foo-bar.py')
    >>> baz
    'quux'
    >>> 
    

提交回复
热议问题