【问题标题】:python string iterpolation on files with % as comment [duplicate]python字符串插值以%作为注释的文件[重复]
【发布时间】:2013-08-27 00:30:28
【问题描述】:

我想使用fabric 生成一个自定义的ejabberd 配置文件并上传到服务器。 fabric 在fabric.contrib.files.upload_template 中使用python 字符串插值。不幸的是,ejabberd 配置文件使用了

%%%

对于cmets

使用 python 字符串插值会在以下简化示例中引发错误:

%%% 这是一条评论

{resurl, %(resturl)s}

ValueError: unsupported format character 't' (0x74) at index 4

我可以用偶数替换 % > 1 的每个非不均匀出现。 或者做

val = re.sub("%", "??", open("ejabberd.cfg").read())
val = val % {"resturl": "http://localhost:500/"}    
val.replace("??", "%")

可能有更好的解决方案来处理文件具有 %,也许是通过告诉 python 使用另一个字符来标记说明符的开始。

感谢您的帮助

【问题讨论】:

    标签: python fabric


    【解决方案1】:

    你需要加倍每个%

    %%%%%% this is a comment
    
    {resurl, %(resturl)s}
    

    这转义了%;输出将每个%% 转换回%

    演示:

    >>> val = '''\
    ... %%%%%% this is a comment
    ... 
    ... {resurl, %(resturl)s}
    ... '''
    >>> print val % {"resturl": "http://localhost:500/"}    
    %%% this is a comment
    
    {resurl, http://localhost:500/}
    

    【讨论】:

      猜你喜欢
      • 2021-11-07
      • 1970-01-01
      • 2019-04-17
      • 2022-07-06
      • 2016-06-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-04
      相关资源
      最近更新 更多