感谢这个问题/答案,我能够将命名空间属性添加到根元素中。所以现在我有这个:
代码
from lxml.builder import ElementMaker
foo = 'http://www.foo.org/XMLSchema/bar'
xsi = 'http://www.w3.org/2001/XMLSchema-instance'
E = ElementMaker(namespace=foo, nsmap={'foo': foo, 'xsi': xsi})
fooroot = E.component()
fooroot.attrib['{{{pre}}}schemaLocation'.format(pre=xsi)] = 'http://www.foo.org/XMLSchema/bar http://www.foo.org/XMLSchema/barindex.xsd'
bars = E.bars(label='why?', validates='required')
fooroot.append(bars)
bars.append(E.bar(label='Image1'))
bars.append(E.bar(label='Image2'))
etree.dump(fooroot)
Run Code Online (Sandbox Code Playgroud)
这给了我想要的输出:
输出
<foo:component xmlns:foo="http://www.foo.org/XMLSchema/bar" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.foo.org/XMLSchema/bar http://www.foo.org/XMLSchema/barindex.xsd">
<foo:bars label="why?" validates="required">
<foo:bar label="Image1"/>
<foo:bar label="Image2"/>
</foo:bars>
</foo:component>
Run Code Online (Sandbox Code Playgroud)
问题
为什么fooroot.attrib['{{{pre}}}schemaLocation'.format(pre=xsi)]pre 周围需要 3 个大括号?
1 个大括号:{pre}导致 ValueError BAD
2 个大括号:在输出上{{pre}}产生BAD
3 个大括号:在输出上产生GOODns0:schemaLocation{{{pre}}}xsi:schemaLocation
我了解.format该字符串的用法,但我想了解为什么需要 3 …
我试图在virtualenv中使用python 3.4.3开始使用xlwings,但是其中一个示例程序出错,因为它看不到numpy,而numpy已安装在virtualenv中。pip freeze在virtualenv节目中运行(清除了一些明显不重要的内容):
appscript==1.0.1
lxml==3.4.4
numpy==1.9.2
pandas==0.16.1
psutil==3.0.1
ptyprocess==0.5
pyparsing==2.0.3
python-dateutil==2.4.2
virtualenv==13.0.3
virtualenv-clone==0.2.5
virtualenvwrapper==4.6.0
xlrd==0.9.3
XlsxWriter==0.7.3
xlwings==0.3.5
Run Code Online (Sandbox Code Playgroud)
我不确定将PYTHON_MAC3.4.3安装的位置(通过Homebrew完成)设置会解决此问题,因为站点包的位置在其他位置。
是否可以从virtualenv运行xlwings,或者是否还需要在系统范围的站点程序包中安装所需的程序包?