Python - how do I call external python programs?

前端 未结 4 1614
轮回少年
轮回少年 2020-12-17 08:45

I\'ll preface this by saying it\'s a homework assignment. I don\'t want code written out for me, just to be pointed in the right direction.

4条回答
  •  余生分开走
    2020-12-17 09:03

    If you want to load an external Python file and run it inside the current interpreter without the burden to dealing with modules, you can use the standard importlib.util module.

    This is useful when you need to ship some Python scripts for demonstration purposes, but you don't want to make them part of a (sub-)module--while still being able to run them automatically, like during integration testing. Here is an example:

    # A sample Python script
    sh$ cat snippet/demo.py 
    SOME_MODULE_GLOBAL=True
    print("Hello, here is the demo snippet!")
    # There is no `__init__.py in the _snippet_ directory
    sh$ cat snippet/__init__.py
    cat: snippet/__init__.py: No such file or directory
    

    Now using importlib.util you can load demo.py even if it is not part of a module:

    >>> import importlib.util
    
    # Bypass the standard import machinery to manually load a Python script from
    # a filepath
    >>> spec = importlib.util.spec_from_file_location('demo','snippet/demo.py')
    >>> spec
    ModuleSpec(name='demo', loader=<_frozen_importlib_external.SourceFileLoader object at 0x7fa549344eb8>, origin='snippet/demo.py')
    >>> module = importlib.util.module_from_spec(spec)
    >>> module
    
    
    # The next command will run the module:
    >>> spec.loader.exec_module(module)
    Hello, here is the demo snippet!
    
    # Module variables are accessible just like if it was a
    # _normally_ imported module:
    >>> module.SOME_MODULE_GLOBAL
    True
    

提交回复
热议问题