Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在两个Python脚本中将文件作为参数传递_Python_Xml_Parameters - Fatal编程技术网

在两个Python脚本中将文件作为参数传递

在两个Python脚本中将文件作为参数传递,python,xml,parameters,Python,Xml,Parameters,新的Python'er提出了一个“手提”的问题 我有两个Python脚本和一个XML文件。“mysecondpython.py”需要使用参数“data.xml”调用“myfirstpython.py”,这样它就可以写入一些内容,然后返回一个文件 在命令行中,我应该键入python mysecondpython.py,它应该是viola!但是我没有雪茄。这个新python'er做错了什么 myfirstpython.py import xml.etreeElementTree as et def

新的Python'er提出了一个“手提”的问题

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

在命令行中,我应该键入
python mysecondpython.py
,它应该是viola!但是我没有雪茄。这个新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()
import myfirstpython

def callingscripts(file)
    callpython = myfirstpython(file)

if __name__ == "__main__":
    file = "data.xml"
    callingscripts(file)
mysecondpython.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()
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>

123

我哭了。

尝试将myfirstpython.py的
\uuu main\uuu
中的内容移动到函数中:

def run(file):
    allmytrees(file)
    inserter()
    printer()
然后您可以从mysecondpyton.py中调用它:


myfirstpython.run('data.xml')
当您导入一个文件时,它是
\uuuuu name\uuuuuu
==“\uuuu main\uuuuu”

事实上,如果uuu name uuu==“uuuu main uuuu”:语句是专门设计用来说“我是正在运行的程序还是正在导入的程序(在这种情况下,不要做这些事情)”


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

我仍然不确定您的意思。有人告诉我,我需要在myfirstpython.py中使用
if\uuuu name\uuuu==“\uuuu main\uuuuu”:
。假定mysecondpython.py是将文件传递到myfirstpython.py的“主”程序。只有在打算从命令行运行myfirstpython时,才需要myfirstpython中的该语句。该语句的主体是当您这样做时将运行的内容。这是身体唯一一次奔跑。但是,在这里描述的示例中,您正在从命令行运行mysecondpython。因此,您在myfirstpython中放入该块的内容无法运行。