简体   繁体   English

从另一个python脚本执行python脚本

[英]executing a python script from another python script

I have a script a.py : 我有一个脚本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])`

I now want to make a script that can run the first script and write the output of a.py to a file with some arguments as well. 我现在想制作一个可以运行第一个脚本并将a.py的输出写入带有一些参数的文件的脚本。 I want to make the automate_output(src,arglist) generate some kind of an output that I can write to the outfile : 我想让automate_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"

I have tried searching around, but so far I do not understand how to pass arguments by using os.system with arguments. 我试过四处搜索,但到目前为止我还不明白如何通过使用带参数的os.system来传递参数。 I have also tried doing : 我也尝试过:

import a
a.main()

There I get a NameError: name 'main' is not defined 我得到一个NameError:名称'main'未定义

Update : I researched some more and found subprocess and I'm quite close to cracking it now it seems. 更新:我研究了一些,发现了子进程,我现在看起来非常接近破解它。 The following code does work, but I would like to pass args instead of manually passing '2' and '3' src = 'bar.py' args = ('2' , '3') 以下代码确实有效,但我想传递args而不是手动传递'2'和'3'src ='bar.py'args =('2','3')
proc = subprocess.Popen(['python', src, '2' , '3'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) print proc.communicate()[0] proc = subprocess.Popen(['python',src,'2','3'],stdout = subprocess.PIPE,stderr = subprocess.STDOUT)print proc.communicate()[0]

a.main() has nothing to do with if __name__=="__main__" block. a.main()if __name__=="__main__"if __name__=="__main__" The former calls a function named main() from a module, the latter executes its block if current module name is __main__ ie, when a module is called as a script. 前者调用一个函数main()a模块,后者如果目前的模块名称是执行其块__main__即,当一个模块被称为一个脚本。

#!/usr/bin/env python
# a.py
def func():
    print repr(__name__)

if __name__=="__main__":
    print "as a script",
    func()

Compare a module executed as a script and a function called from the imported module: 比较作为脚本执行的模块和从导入的模块调用的函数:

$ python a.py
as a script '__main__'

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

See section Modules in the Python tutorial . 请参阅Python教程中的模块一节

To get output from the subprocess you could use subprocess.check_output() function: 要从子进程获取输出,可以使用subprocess.check_output()函数:

import sys
from subprocess import check_output as qx

args = ['2', '3']
output = qx([sys.executable, 'bar.py'] + args)
print output

This is not a function, it's an if statement: 这不是一个函数,它是一个if语句:

if __name__ == "__main__":
    ...

If you want a main function, define one: 如果需要main函数,请定义一个:

import sys

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

Then just call it if you need to: 如果您需要,请调用它:

if __name__ == "__main__":
    main()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM