2014-01-18 60 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')