我正在调试代码,其中有以下行:
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
无法导入导入,因为导入是一个关键字。此外,导入 python 文件与运行脚本不同,因为大多数脚本都有一个部分
if __name__ == '__main__':
....
当程序作为脚本运行时,变量__name__
的值__main__
。
如果已准备好调用子进程,则可以使用
`subprocess.call(...)`
编辑:实际上,您可以像这样导入导入
from importlib import import_module
mod = import_module('import')
但是,它不会具有与调用脚本相同的效果。请注意,脚本可能使用sys.argv
,这也必须解决。
编辑:这是一个仿制品,如果你真的不想要子进程,你可以尝试一下。我不保证它会起作用
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))