Cannot import a module from a variable

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Jia Lu

    #1

    Cannot import a module from a variable

    Hi all:

    I try to do things below:
    >>>import sys
    >>for i in sys.modules.key s():
    import i
    Traceback (most recent call last):
    File "<pyshell#6 7>", line 2, in <module>
    import i
    ImportError: No module named i

    But it seems that import donot know what is i ? why?

    Thanks/

  • Christian Joergensen

    #2
    Re: Cannot import a module from a variable

    "Jia Lu" <Roka100@gmail. comwrites:
    Hi all:
    >
    I try to do things below:
    >>>>import sys
    >>>for i in sys.modules.key s():
    import i
    Traceback (most recent call last):
    File "<pyshell#6 7>", line 2, in <module>
    import i
    ImportError: No module named i
    >
    But it seems that import donot know what is i ? why?
    Try using __import__(i) instead.

    --
    Christian Joergensen | Linux, programming or web consultancy
    http://www.razor.dk | Visit us at: http://www.gmta.info

    Comment

    • Colin J. Williams

      #3
      Re: Cannot import a module from a variable

      Christian Joergensen wrote:
      "Jia Lu" <Roka100@gmail. comwrites:
      >
      >Hi all:
      >>
      >I try to do things below:
      >>>>import sys
      >>>>for i in sys.modules.key s():
      > import i
      >Traceback (most recent call last):
      > File "<pyshell#6 7>", line 2, in <module>
      > import i
      >ImportError: No module named i
      >>
      >But it seems that import donot know what is i ? why?
      >
      Try using __import__(i) instead.
      >
      (a) you need something like exec('import ' + i) for most cases
      but (b) "encodings" is a package i.e. it points to a directory which has
      an __init__.py file.

      Colin W.

      Comment

      • Bruno Desthuilliers

        #4
        Re: Cannot import a module from a variable

        Jia Lu wrote:
        Hi all:
        >
        I try to do things below:
        >>>import sys
        >>>for i in sys.modules.key s():
        import i
        Traceback (most recent call last):
        File "<pyshell#6 7>", line 2, in <module>
        import i
        ImportError: No module named i
        >
        But it seems that import donot know what is i ?
        The import statement expects a name (a symbol), not a string.

        --
        bruno desthuilliers
        python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
        p in 'onurb@xiludom. gro'.split('@')])"

        Comment

        • Tim Williams

          #5
          Re: Cannot import a module from a variable

          On 16/10/06, Bruno Desthuilliers <onurb@xiludom. growrote:
          Jia Lu wrote:
          Hi all:

          I try to do things below:
          >>import sys
          >>for i in sys.modules.key s():
          import i
          Traceback (most recent call last):
          File "<pyshell#6 7>", line 2, in <module>
          import i
          ImportError: No module named i

          But it seems that import donot know what is i ?
          >
          The import statement expects a name (a symbol), not a string.
          >
          eval( 'import %s' % modname)

          and

          eval( 'reload(%s)' % modname)

          Usual warnings about eval apply, but in this case it is usable.

          HTH :)

          Comment

          • Fredrik Lundh

            #6
            Re: Cannot import a module from a variable

            Tim Williams wrote:
            eval( 'reload(%s)' % modname)
            reload takes a module object, not a module name. since you need to have the
            object, you might as well pass it to the reload() function.

            </F>



            Comment

            • Duncan Booth

              #7
              Re: Cannot import a module from a variable

              "Tim Williams" <tim@tdw.netwro te:
              >The import statement expects a name (a symbol), not a string.
              >>
              >
              eval( 'import %s' % modname)
              >
              and
              >
              eval( 'reload(%s)' % modname)
              >
              Usual warnings about eval apply, but in this case it is usable.
              Did you actually try your suggestion before posting?
              >>modname = 'os'
              >>eval( 'import %s' % modname)
              Traceback (most recent call last):
              File "<pyshell#4 >", line 1, in <module>
              eval( 'import %s' % modname)
              File "<string>", line 1
              import os
              ^
              SyntaxError: invalid syntax
              >>>
              Also, it is pretty pointless to import the module and not know which
              arbitrary variable name it will have created. It is much simpler just to
              use the __import__ builtin:
              >>module = __import__(modn ame)
              >>module
              <module 'os' from 'C:\Python25\li b\os.pyc'>

              Comment

              • Cameron Walsh

                #8
                Re: Cannot import a module from a variable

                Hi,

                This has actually been answered in a previous post ("user modules"
                started by myself), for which I was very grateful. I have since
                expanded on their solutions to create the following code, of which parts
                or all may be useful. You'll probably be most interested in the last
                part of the code, from "# Now we actually import the modules" onwards.
                >>import os
                >>import glob
                >># import_extensio n_modules(direc tory)
                >># Imports all the modules in the sub-directory "directory"
                >># "directory" MUST be a single word and a sub-directory of that
                >># name MUST exist.
                >># Returns then as a dictionary of {"module_name": module}
                >># This works for both .py (uncompiled modules)
                >># and .pyc (compiled modules where the source code is not given)
                >># TODO: Fix limitations above, clean up code.
                >>#
                >>def import_extensio n_modules(direc tory):
                previous_direct ory = os.getcwd()
                try:
                os.chdir(direct ory)
                uncompiled_file s = glob.glob("*.py ")
                compiled_files = glob.glob("*.py c")
                all_files = []
                modules = {}
                for filename in uncompiled_file s:
                all_files.appen d(filename[0:-3]) # Strip off the ".py"
                for filename in compiled_files:
                # Add any pre-compiled modules without source code.
                filename = filename[0:-4] # Strip off the ".pyc"
                if filename not in all_files:
                all_files.appen d(filename)
                if "__init__" in all_files:
                # Remove any occurrences of __init__ since it does
                # not make sense to import it.
                all_files.remov e("__init__")
                # Now we actually import the modules
                for module_name in all_files:
                # The last parameter must not be empty since we are using
                # import blah.blah
                # format because we want modules not packages.
                # see 'help(__import_ _)' for details.
                module = __import__("%s. %s" %(directory,mod ule_name), None,
                None,["some string to make this a non-empty list"])
                modules[module.__name__] = module
                return modules
                finally:
                os.chdir(previo us_directory)
                >>user_module s = import_extensio n_modules("user _modules")
                >>user_module s
                {'user_modules. funky_module': <module 'user_modules.f unky_module' from
                'C:\Projects\mo dule_import_tes ter\src\user_mo dules\funky_mod ule.pyc'>}

                Woah, that actually works? Having the "finally" after the "return"?
                That could make some things easier, and some things harder...

                Hope that helps,

                Cameron.

                Comment

                • Gabriel Genellina

                  #9
                  Re: Cannot import a module from a variable

                  At Wednesday 18/10/2006 22:51, Cameron Walsh wrote:
                  previous_direct ory = os.getcwd()
                  try:
                  os.chdir(direct ory)
                  [ ... ]
                  return modules
                  finally:
                  os.chdir(previo us_directory)
                  >
                  >Woah, that actually works? Having the "finally" after the "return"?
                  >That could make some things easier, and some things harder...
                  Note that moving the return statement after the finally does
                  *exactly* the same thing, generates shorter code, and is a lot more
                  readable (IMHO).


                  --
                  Gabriel Genellina
                  Softlab SRL





                  _______________ _______________ _______________ _____
                  Preguntá. Respondé. Descubrí.
                  Todo lo que querías saber, y lo que ni imaginabas,
                  está en Yahoo! Respuestas (Beta).
                  ¡Probalo ya!


                  Comment

                  • Cameron Walsh

                    #10
                    Re: Cannot import a module from a variable

                    Gabriel Genellina wrote:
                    At Wednesday 18/10/2006 22:51, Cameron Walsh wrote:
                    >
                    > previous_direct ory = os.getcwd()
                    > try:
                    > os.chdir(direct ory)
                    > [ ... ]
                    > return modules
                    > finally:
                    > os.chdir(previo us_directory)
                    >>
                    >Woah, that actually works? Having the "finally" after the "return"?
                    >That could make some things easier, and some things harder...
                    >
                    Note that moving the return statement after the finally does *exactly*
                    the same thing, generates shorter code, and is a lot more readable (IMHO).
                    >
                    >
                    I wholeheartedly agree, the above version is hideous. It was a
                    copy-paste error that got it after the return statement and I was
                    surprised to see it actually worked.

                    Comment

                    • Fredrik Lundh

                      #11
                      Re: Cannot import a module from a variable

                      Cameron Walsh wrote:
                      Woah, that actually works? Having the "finally" after the "return"?
                      That could make some things easier, and some things harder...
                      The whole point of having a clean-up handler is to make sure it runs no
                      matter what:

                      When a return, break or continue statement is executed in the
                      try suite of a try-finally statement, the finally clause is also
                      executed "on the way out".



                      </F>

                      Comment

                      Working...