【问题标题】:executing a python script from another python script从另一个 python 脚本执行 python 脚本
【发布时间】:2011-10-14 03:15:05
【问题描述】:

我有一个脚本 a.py:

#!/usr/bin/env python

def foo(arg1, arg2):
    return int(arg1) + int(arg2)

if __name__ == "__main__":
   import sys
   print foo(sys.argv[1], sys.argv[2])`

我现在想制作一个脚本,它可以运行第一个脚本并将 a.py 的输出写入带有一些参数的文件。我想让automation_output(src,arglist)生成某种我可以写入outfile的输出:

import sys

def automate_output(src,  arglist):
    return ""


def print_to_file (src, outfile, arglist):
    print "printing to file %s" %(outfile)
    out = open(outfile, 'w')
    s = open(src, 'r')

    for line in s:
        out.write(line)
    s.close()

    out.write(" \"\"\"\n Run time example: \n") 
    out.write(automate(src, arglist))
    out.write(" \"\"\"\n")
    out.close()


try: 
    src = sys.argv[1]
    outfile = sys.argv[2]
    arglist = sys.argv[3:]
    automate(src, arglist)
    print_to_file(src,outfile,arglist)  
except:
    print "error"
    #print "usage : python automate_runtime.py scriptname outfile args"

我尝试过四处搜索,但到目前为止我不明白如何通过使用带有参数的 os.system 来传递参数。我也尝试过:

import a
a.main()

我得到一个 NameError: name 'main' is not defined

更新: 我进行了更多研究,发现了 subprocess ,现在看来我已经非常接近破解它了。 以下代码确实有效,但我想传递 args 而不是手动传递 '2' 和 '3' src = 'bar.py' args = ('2' , '3')
proc = subprocess.Popen(['python', src, '2' , '3'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) 打印 proc.communicate()[0]

【问题讨论】:

  • 实际上,鉴于您在那里所做的事情,由于执行import a.py 而不是import a,您将获得ImportError: No module named py。获得NameError 的原因是模块a 中未定义名称“main”。
  • 但是,我不明白为什么 main 没有定义?我确实有 if name == "main":
  • 如果看不出问题,请阅读 Python 教程;如果你理解它,你就会明白这里有什么问题。
  • 使用参数解包Popen(['python', 'bar.py', *args])
  • @sdolan:元组解包在这种情况下不起作用,而是使用['a', 'b'] + list(args)

标签: python


【解决方案1】:

这不是一个函数,它是一个if 语句:

if __name__ == "__main__":
    ...

如果你想要一个主函数,定义一个:

import sys

def main():
   print foo(sys.argv[1], sys.argv[2])`

然后,如果需要,只需调用它:

if __name__ == "__main__":
    main()

【讨论】:

    【解决方案2】:

    a.main()if __name__=="__main__" 块无关。前者从a 模块调用名为main() 的函数,后者在当前模块名称为__main__ 时执行其块,即当模块作为脚本调用时。

    #!/usr/bin/env python
    # a.py
    def func():
        print repr(__name__)
    
    if __name__=="__main__":
        print "as a script",
        func()
    

    比较作为脚本执行的模块和从导入的模块调用的函数:

    $ python a.py
    as a script '__main__'
    
    $ python -c "import a; print 'via import',; a.func()"
    via import 'a'
    

    section Modules in the Python tutorial

    要从子进程获取输出,您可以使用subprocess.check_output() 函数:

    import sys
    from subprocess import check_output as qx
    
    args = ['2', '3']
    output = qx([sys.executable, 'bar.py'] + args)
    print output
    

    【讨论】:

    • ImportError: cannot import name check_output
    • @Arnab Datta:check_output() 是 Python 2.7 中的新功能。在旧版本上,您可以使用 cmd_output()
    猜你喜欢
    • 2016-09-03
    • 1970-01-01
    • 1970-01-01
    • 2017-03-30
    • 1970-01-01
    • 2011-03-04
    • 1970-01-01
    • 2023-03-20
    • 1970-01-01
    相关资源
    最近更新 更多