如何在python的命令行参数中跳过空格和空格?

时间:2018-06-25 19:28:34

标签: python

我尝试使用以下代码作为参数。 a.py:-

import sys
try:
import xml.etree.cElementTree as ET
except ImportError:
import xml.etree.ElementTree as ET

#location for the xml file where parsing is required
param1 = sys.argv[1]
#parent tag of new tag
param2 = sys.argv[2]
param3 = sys.argv[3]
param4 = sys.argv[4]
print(param3)
#parse the config file
tree = ET.parse(param1)
#get the root of config file
root = tree.getroot()
#add element exactly at particular point
tar = param2
#this will find the root tag
target = tree.find(tar)
#new tag required to be inserted
seq = param3
#taking new tag element in element tree
temp = ET.Element(seq)
#insert the position where you want to enter
i = int(param4)
target.insert(i,temp)
temp.tail = '\n'
tree.write(param1,encoding='utf-8')

和另一个文件以b.py的形式获取参数:-

#!/usr/bin/python
import socket
import xmlparser.py
host1 = socket.getfqdn()
print(host1)
param1 = 'config.xml'
param2 = 'Target'
param3 = 'Attribute NAME="A" VALUE="((host={0},ip=123.0.0.0,port=22),(host= 
{0}, port=11),(host={0}, port=162))"'.format(host1)
param4 = 3

python xmlparser.py param1 param2 param3 param4

当我运行“ python b.py”时,由于语法无效而出现错误,有人可以建议出什么错误吗?

2 个答案:

答案 0 :(得分:0)

What you need to do is make the first file's code as a function and call in in the next file like this-

import xml.etree.cElementTree as ET
import xml.etree.ElementTree as ET

def parser(p1,p2,p3,p4):
    param1 = p1
    param2 = p2
    param3 = p3
    param4 = p4
    print(param3)
    tree = ET.parse(param1)
    root = tree.getroot()
    tar = param2
    target = tree.find(tar)
    seq = param3
    temp = ET.Element(seq)
    i = int(param4)
    target.insert(i,temp)
    temp.tail = '\n'
    tree.write(param1,encoding='utf-8')

and then call this in your second file like this

import socket
import xmlparser
host1 = socket.getfqdn()
print(host1)
param1 = 'config.xml'
param2 = 'Target'
param3 = 'Attribute NAME="A" VALUE="((host={0},ip=123.0.0.0,port=22),(host= {0}, port=11),(host={0}, port=162))"'.format(host1)
param4 = 3

xmlparser.parser(param1,param2,param3,param4)

This should work.

Also, avoid using try for imports, it will lead to a problem if the import isn't successful anyway thus loosing the purpose.

答案 1 :(得分:0)

您的问题是您的最后一部分是shell命令,而不是python,因此语法无效。

如果您想提供一个shell命令,那么执行它的测试功能最好放在bash中:

#!/usr/bin/bash

host1="$(hostname -A)"
echo $host1
param1='config.xml'
param2='Target'
param3='Attribute NAME="A" VALUE="((host={0},ip=123.0.0.0,port=22),(host= 
'"$host1"', port=11),(host={0}, port=162))"'
param4=3

python xmlparser.py "$param1" "$param2" "$param3" "$param4"

您还可以在python代码中使用subprocess.popen。