2017-07-17 65 views
0

我調試代碼,裏面有這樣一行:用SYS運行import.py參數

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 

回答

3

無法導入導入,因爲導入是關鍵字。此外,導入一個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))