如何在命令行上运行python代码并传递打印值?
问题描述:
所以,我想解析XML并通过python获取命令行上的值。以下是自行解释的代码。如何在命令行上运行python代码并传递打印值?
APPLY_DIR=$(python -c 'from xml.dom import minidom;xmldoc=minidom.parse("args.xml");itemlist=xmldoc.getElementsByTagName("item");print str(itemlist[6].attributes["patchApplyDir"])')
REVERT_DIR=$(python -c 'from xml.dom import minidom;xmldoc=minidom.parse("args.xml");itemlist=xmldoc.getElementsByTagName("item");print str(itemlist[7].attributes["patchRevertDir"])')
echo $APPLY_DIR
echo $REVERT_DIR
的问题是,它返回以下输出:
<xml.dom.minidom.Attr instance at 0x7fba97db07e8>
<xml.dom.minidom.Attr instance at 0x7fb820e80998>
这里是我的xml文件args.xml
<data>
<args>
<item svn_repo = "https://ntil-svn-u1:18080/svn/HSAN_SW_DEVELOPMENT/HSAN-SW-DEV/Project/Engineering/Code/HSAN_INTEGRATION/HSAN_MERGE/Tags/HSAN_ST_RELEASE_16_12_2016_"></item>
<item svn_revision = "991/"></item>
<item checkout_path = "/root/Neeraj/GGG"></item>
<item pre_build = "Default1"></item>
<item build_script = "Default1"></item>
<item svnCheckoutPath = "/root/Neeraj/GGG"></item>
<item patchApplyDir = "./GGG/Apply"></item>
<item patchRevertDir = "./GGG/Revert"></item>
<item APPLY_DIR="./Apply"></item>
<item REVERT_DIR="./Revert"></item>
<item VERSION_MINOR="100"></item>
<item VERSION_INTERNAL="200"></item>
<item INPUT="300"></item>
</args>
</data>
请让我知道我究竟错在这里做什么?另外,我不想制作一个单独的文件来编写Python代码,我只能在命令中执行它。谢谢。
答
如果你需要的值,那么,尝试做attributes['attribute'].value
像:
APPLY_DIR=$(python -c 'from xml.dom import minidom;xmldoc=minidom.parse("args.xml");itemlist=xmldoc.getElementsByTagName("item");print str(itemlist[6].attributes["patchApplyDir"].value)')
在手机,无法测试它。尝试并回复。
答
如果你想选择的项目的价值,使用.value
:
APPLY_DIR=$(python -c 'from xml.dom import minidom;xmldoc=minidom.parse("args.xml");itemlist=xmldoc.getElementsByTagName("item");print itemlist[6].attributes["patchApplyDir"].value')
REVERT_DIR=$(python -c 'from xml.dom import minidom;xmldoc=minidom.parse("args.xml");itemlist=xmldoc.getElementsByTagName("item");print itemlist[7].attributes["patchRevertDir"].value')
echo $APPLY_DIR
# ./GGG/Apply
echo $REVERT_DIR
# ./GGG/Revert
您的预期产量是多少? – Inian
[我认为答案是在这篇文章中](http://stackoverflow.com/questions/4760215/running-shell-command-from-python-and-capturing-the-output) –