2011-10-14 175 views
0

我有一个脚本a.py执行python脚本:从另一个python脚本

#!/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的输出写入到文件的脚本也有一些论点。我想使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" 

我试图摸索,但到目前为止,我不明白如何来传递参数使用带有参数的os.system。我也试着这样做:

import a 
a.main() 

在那里,我得到一个NameError:名字“主”是没有定义

更新: 我研究多一些,发现子和我很接近现在咔吧它似乎。 以下代码确实有效,但我想通过参数而不是手动传递'2'和'3' src ='bar.py' args =('2','3')
proc = subprocess .Popen([ '蟒',SRC, '2', '3'],标准输出= subprocess.PIPE,标准错误= subprocess.STDOUT) 打印proc.communicate()[0]

+0

其实,给你做了什么,在那里,你会得到一个'导入错误:没有模块名为py'由于做'进口a.py'而不是'进口了'。你得到'NameError'的原因是因为名称'main'没有在模块'a'中定义。 –

+0

是的,我的意思是: import a –

+0

但是,我不明白为什么main没有定义?如果__name__ ==“__main__”: –

回答

1

这是不是一个功能,它是一个if声明:

if __name__ == "__main__": 
    ... 

如果你想有一个主要功能,定义一个:

import sys 

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

然后只要打电话给你,如果你需要:

if __name__ == "__main__": 
    main() 
1

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 
+0

ImportError:无法导入名称check_output –

+0

@Arnab Datta:'check_output()'在Python 2.7中是新的。在旧版本中,您可以使用['cmd_output()'](http://stackoverflow.com/questions/236737/making-a-system-call-that-returns-the-stdout-output-as-a-string/ 236909#236909) – jfs

相关问题