在版本3.1.2中,这引发了一个异常:

>>> print(jinja2.Template("{{ '%04d' | format(0777 - '0022' | int) }}").render())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/root/.virtualenvs/ansible-playbooks/lib/python3.8/site-packages/jinja2/environment.py", line 1208, in __new__
    return env.from_string(source, template_class=cls)
  File "/root/.virtualenvs/ansible-playbooks/lib/python3.8/site-packages/jinja2/environment.py", line 1105, in from_string
    return cls.from_code(self, self.compile(source), gs, None)
  File "/root/.virtualenvs/ansible-playbooks/lib/python3.8/site-packages/jinja2/environment.py", line 768, in compile
    self.handle_exception(source=source_hint)
  File "/root/.virtualenvs/ansible-playbooks/lib/python3.8/site-packages/jinja2/environment.py", line 936, in handle_exception
    raise rewrite_traceback_stack(source=source)
  File "<unknown>", line 1, in template
jinja2.exceptions.TemplateSyntaxError: expected token ',', got 'integer'

虽然这在版本2.11.3中曾经运行得很好:

>>> print(jinja2.Template("{{ '%04d' | format(0777 - '0022' | int) }}").render())
0755

我认为这种行为在this PR年内发生了变化.我需要做些什么才能修复它?

它上面的代码片段来自这个可分析的角色配置:

deploy_cakephp_default_umask: '0022'
deploy_cakephp_default_owner: root
deploy_cakephp_default_group: root
deploy_cakephp_default_directory_mode: "{{ '%04d' | format(0777 - deploy_cakephp_default_umask | int) }}"
deploy_cakephp_default_file_mode: "{{ '%04d' | format(0666 - deploy_cakephp_default_umask | int) }}"

推荐答案

我认为你的问题出在JJJA和你正在使用的PYTHON版本上.在python3.0中删除了C样式的八进制文字(参见https://docs.python.org/3/reference/lexical_analysis.html#integer-literals)

同时,我能够使用这个利用八进制整数文字记数法和format()函数的JJIA2表达式来满足您的要求:

{{ '0{0:o}'.format(0o777 - 0o22) }}

请参阅以下测试会话:

$ pip list | grep Jinja2
Jinja2                 3.1.2

$ python --version
Python 3.10.6
# same result with 3.8.16

$ python
Python 3.10.6 (main, May 29 2023, 11:10:38) [GCC 11.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import jinja2
>>> print(jinja2.Template("{{ '0{0:o}'.format(0o777 - 0o22) }}").render())
0755

Linux相关问答推荐

是否有例外情况需要在.gitconfig中使用?

pci_user_write_config_word在哪里实现?

匹配模式和提取

在 Linux 中屏蔽文件中的位 - 按位运算

无法在嵌入式 Linux 中使用 libjpeg 以 RGB888 在 LCD(黑色)上显示 JPEG

什么命令用于在linux中创建或修改具有指定文件大小的多个文件

从 bash shell 等效项在fish shell 上设置 $ANDROID_SDK_ROOT

根据文件名对目录中的文件进行 chgrp

在android上使用lldb-server进行lldb调试?

给定两个目录树如何找到相同的文件?

如何在 Linux 中设置目录大小限制?

如何在 shell 脚本中动态生成新的变量名?

从 shell 将多个 .sql 转储文件导入 mysql 数据库

打印当前一周的星期一的日期(在 bash 中)

如何 grep 精确的文字字符串(无正则表达式)

在 Linux / Mono 上运行 ServiceStack 的最佳方式是什么?

当将信号量减为零的进程崩溃时,如何恢复信号量?

UNIX `time` 命令对于基准测试是否足够准确?

如何通过进程名获取PID?

Bash 将 awk 的输出捕获到数组中