使用sys参数运行import.py

时间:2017-07-17 07:33:57

标签: python

我正在调试代码,其中包含以下行:

run('python /home/some_user/some_repo/pyflights/usertools/import.py /home/some_user/some_repo/pyflights/config/index_import.conf flights.map --import')

run - 类似于os.system

所以,我想在不使用run函数的情况下运行此代码。我需要导入我的import.py文件并使用sys.args运行它。但是我怎么能这样做呢?

from some_repo.pyflights.usertools import import

1 个答案:

答案 0 :(得分:3)

无法导入导入,因为import是关键字。此外,导入python文件与运行脚本不同,因为大多数脚本都有一个部分

if __name__ == '__main__':
    ....

当程序作为脚本运行时,变量__name__的值为__main__

如果您准备调用子进程,则可以使用

`subprocess.call(...)`

编辑:实际上,您可以像这样导入导入

from importlib import import_module
mod = import_module('import')

但是它与调用脚本的效果不同。请注意,该脚本可能使用sys.argv,这也必须解决。

编辑:这是一个你可以尝试的ersatz,如果你真的不想要一个子进程。我不保证它会起作用

import shlex
import sys
import types

def run(args):
    """Runs a python program with arguments within the current process.

    Arguments:
        @args: a sequence of arguments, the first one must be the file path to the python program

    This is not guaranteed to work because the current process and the
    executed script could modify the python running environment in incompatible ways.
    """
    old_main, sys.modules['__main__'] = sys.modules['__main__'], types.ModuleType('__main__')
    old_argv, sys.argv = sys.argv, list(args)
    try:
        with open(sys.argv[0]) as infile:
            source = infile.read()
        exec(source, sys.modules['__main__'].__dict__)
    except SystemExit as exc:
        if exc.code:
            raise RuntimeError('run() failed with code %d' % exc.code)
    finally:
        sys.argv, sys.modules['__main__'] = old_argv, old_main

command = '/home/some_user/some_repo/pyflights/usertools/import.py /home/some_user/some_repo/pyflights/config/index_import.conf flights.map --import'
run(shlex.split(command))