我有一个脚本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]
其实,给你做了什么,在那里,你会得到一个'导入错误:没有模块名为py'由于做'进口a.py'而不是'进口了'。你得到'NameError'的原因是因为名称'main'没有在模块'a'中定义。 –
是的,我的意思是: import a –
但是,我不明白为什么main没有定义?如果__name__ ==“__main__”: –