在另一个内部运行python文件

时间:2017-06-01 09:03:10

标签: python

我正在使用python 3.5

我想从另一个python脚本运行一个python脚本调用。

特别是,我说我有脚本A(特别是,这是我想要运行的确切文件:script A file):

脚本A如下。

if __name__ == '__main__':
    args = argparser.parse_args()
    _main(args)

我在脚本B中运行脚本B,它调用脚本A. 如何通过在运行脚本B时调用脚本A的main函数来执行此操作?

请不要os.system('python scriptA.py 1'),这不是我想要的。感谢

4 个答案:

答案 0 :(得分:2)

通常你可以导入它并调用main函数 像

import script_a
...
script_a._main()

当然可能是script_a不在你的src结构中,所以你不能简单导入,或者script_a完全在别的地方。 假设script_a的路径是path_a 你可以

import sys
sys.path.append(path_a)
import script_a
script_a._main()

如果你想在你的script_b中将args传递给script_a

import script_a
...
if __name__ == '__main__':
    args = argparser.parse_args()
    script_a._main(args)

答案 1 :(得分:1)

在脚本B中只需导入脚本A,

import script_A

from script_A import *

现在您可以在脚本B中访问脚本A

答案 2 :(得分:1)

将文件视为模块,并将<html> <body> <table style="width:35pt;height:24pt;table-layout:fixed"> <thead> <tr> <td style="width:35pt;height:12pt">Good</td> </tr> </thead> <tbody> <tr> <td style="width:35pt;height:12pt;word-wrap:break-word">Costingly Cost Cost</td> </tr> </tbody> </table> <div style="height:50pt"></div> <table style="width:35pt;height:24pt;"> <thead> <tr> <td style="width:35pt;height:12pt">Bad</td> </tr> </thead> <tbody> <tr> <td style="width:35pt;height:12pt" nowrap>Costingly Cost Cost</td> </tr> </tbody> </table> </body> </html>放在文件的顶部。

然后,您可以使用import scriptA,其中scriptA.main(1)是您传递给它的参数。

N.B 导入时不要将1放在最后。

答案 3 :(得分:0)

如果您的代码没有在脚本A中缩进,并且如果您在脚本B中导入脚本A,它将自动首先运行脚本A,然后继续执行脚本B的__main__()。如果您希望在脚本A的执行开始时进行控制,然后在脚本A中缩进代码或在正常函数(例如def start())中对其进行编码。

现在,将脚本A导入脚本B,如下所示

import ScriptA

将脚本A作为

运行
ScriptA.start()

注意:确保脚本A和脚本B位于同一目录中,以使其正常工作。希望这能解决你的目的。干杯!