新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>
我流泪了。
我还不确定你的意思。我被告知我需要在myfirstpython.py中有'if __name__ =='__main __“:'。假设mysecondpython.py是将文件传递给myfirstpython.py的“main”程序。 – misterbear
如果你打算从命令行运行myfirstpython,只需在myfirstpython中使用该语句。该声明的主体是当你这样做时将会运行的内容。这是身体运行的唯一时间。但是,在这里描述的情况下,您正在从命令行运行mysecondpython。因此,您在myfirstpython中放入该块的内容不会运行。 – GreenAsJade