Python从python脚本运行另一个脚本

时间:2016-05-09 04:45:16

标签: python python-2.7 command os.system

def run_cmd(self, cmd):
    print cmd 

    status = os.system(cmd)
    print 'Command ran with Status: %s' % status

    if status:
        s = 'Command Failed: Status: %s for %s' % (status, cmd)
        print s
        sys.exit(status)
    else:
        s = 'Command Success: %s' % cmd 

    return status

我正在使用此函数从另一个脚本运行python脚本。

前:

command_to_exec = 'python script_b.py'
run_cmd(command_to_exec)

现在,如果script_b.py失败,则script_a.py会以状态退出。

没关系。

案例2

command_to_exec = 'python script_a.py --options'
rum_cmd(command_to_exec)

这种情况是自己运行'python script_a.py'的script_a.py。 在这种情况下,如果新生成的script_a.py失败,则外部script_a.py仍然成功,因为它无法捕获内部script_a.py的失败(因为sys.exit(status))

现在,我该如何处理这种情况? (如果内部script_a失败,则外部script_a应退出)

1 个答案:

答案 0 :(得分:0)

您可以将其他脚本作为模块运行。假设您有文件夹:
DIR
| --- main.py
| --- imported.py
你想从第一个开始运行第二个。只需使用import,就像那样:

import imported #the file name without the extension

它将运行该文件,您将能够在主脚本中使用它的变量和函数。