新Python'er有一个问题“手举”。
我有两个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>
我哭了。
答案 0 :(得分:3)
导入文件时,__name__
不会== "__main__"
。
事实上,声明if __name__ == "__main__":
专门用于说“我是正在运行的程序,还是我正在导入的程序(在这种情况下不执行此操作)”
你需要在myfirstpython.py中编写一个函数,并从mysecondpython.py中调用它
答案 1 :(得分:0)
尝试将myfirstpython.py的__main__
中的内容移动到函数中:
def run(file):
allmytrees(file)
inserter()
printer()
然后你可以从mysecondpython.py中调用它:
myfirstpython.run('data.xml')