2014-01-18 61 views
1

新Python'er有一个问题“举手”将文件作为参数传递给两个Python脚本

我有两个Python脚本和一个XML文件。 “mysecondpython.py”需要用“data.xml”参数调用“myfirstpython.py”,以便它可以写入一些内容,然后返回一个文件。

从命令行,我应该输入python mysecondpython.py,它应该是中提琴!但我没有雪茄。这个新python'er做错了什么?

myfirstpython.py

import xml.etreeElementTree as et 

def allmytrees(file): 
    dest_tree = et.parse(file) 
    dest_root = dest_tree.getroot() 

def inserter(): 
    dest_root.insert(0, "hello world") 

def printer(): 
    dest_tree.write('out.xml', xml_declaration=True, encoding='utf-8') 

if __name__ == "__main__": 
    allmytrees(file) 
    inserter() 
    printer() 

mysecondpython.py

import myfirstpython 

def callingscripts(file) 
    callpython = myfirstpython(file) 

if __name__ == "__main__": 
    file = "data.xml" 
    callingscripts(file) 

data.xml中

<root> 
    <nothing-here>123</nothing-here> 
</root> 

我流泪了。

回答

3

当你输入一个文件,它的__name__不是== "__main__"

事实上,语句if __name__ == "__main__":是专为说:“我是正在运行,还是我要导入的程序(在这种情况下不这样做的东西)”

你需要写一个函数在myfirstpython.py中,并从mysecondpython.py调用它

+0

我还不确定你的意思。我被告知我需要在myfirstpython.py中有'if __name__ =='__main __“:'。假设mysecondpython.py是将文件传递给myfirstpython.py的“main”程序。 – misterbear

+0

如果你打算从命令行运行myfirstpython,只需在myfirstpython中使用该语句。该声明的主体是当你这样做时将会运行的内容。这是身体运行的唯一时间。但是,在这里描述的情况下,您正在从命令行运行mysecondpython。因此,您在myfirstpython中放入该块的内容不会运行。 – GreenAsJade

0

尝试在myfirstpython.py的__main__东西搬进功能:

def run(file): 
    allmytrees(file) 
    inserter() 
    printer() 

然后,你可以把它形成mysecondpython.py:

myfirstpython.run('data.xml')