如何在 xonsh 中将命令很好地拆分为多行?

如何在 xonsh 中将命令很好地拆分为多行?

考虑一下 bash 中的这个命令:

docker run -d \
    --rm \
    --name postgres-prod \
    --env TZ="Europe/Budapest" \
    --mount type=bind,src=/secure/postgres/prod/data,dst=/var/lib/postgresql/data \
    --mount type=bind,src=/secure/postgres/prod/backup,dst=/backup \
    --mount type=bind,src=/secure/postgres/secrets/postgres_pwd.txt,dst=/etc/postgres_pwd.txt \
    --env POSTGRES_PASSWORD_FILE="/etc/postgres_pwd.txt" \
    -p 0.0.0.0:5432:5432 \
    postgres_hun:11

我想在 xonsh 脚本中拆分像上面这样的非常长的命令。如果我简单地将上面的脚本与 xonsh 一起使用,则会出现此错误:

./test.xsh                                                                                                                                              
/usr/lib/python3/dist-packages/apport/report.py:13: DeprecationWarning: the imp module is deprecated in favour of importlib; see the module's documentation for alternative uses
  import fnmatch, glob, traceback, errno, sys, atexit, locale, imp, stat
Traceback (most recent call last):
  File "/usr/bin/xonsh", line 4, in <module>
    main()
  File "/usr/lib/python3/dist-packages/xonsh/__amalgam__.py", line 24019, in main
    _failback_to_other_shells(args, err)
  File "/usr/lib/python3/dist-packages/xonsh/__amalgam__.py", line 23983, in _failback_to_other_shells
    raise err
  File "/usr/lib/python3/dist-packages/xonsh/__amalgam__.py", line 24017, in main
    return main_xonsh(args)
  File "/usr/lib/python3/dist-packages/xonsh/__amalgam__.py", line 24060, in main_xonsh
    run_script_with_cache(
  File "/usr/lib/python3/dist-packages/xonsh/__amalgam__.py", line 3041, in run_script_with_cache
    ccode = compile_code(filename, code, execer, glb, loc, mode)
  File "/usr/lib/python3/dist-packages/xonsh/__amalgam__.py", line 3000, in compile_code
    ccode = execer.compile(code, glbs=glb, locs=loc, mode=mode, filename=filename)
  File "/usr/lib/python3/dist-packages/xonsh/__amalgam__.py", line 23105, in compile
    code = compile(tree, filename, mode)
TypeError: expected Module node, got Expression

我不确定问题是什么。反斜杠也可以用于 Python 中的行延续,我认为这应该可以,但实际上不行。还尝试将整个内容放在括号内,也将其放在括号内,$()但这些都不起作用。

我想出了这个“解决方案”:

#!/usr/bin/xonsh

import subprocess

cmd = [
    "docker", "run", "-d", "--rm",
    "--name", "postgres-prod",
    "--env", 'TZ="Europe/Budapest',
    "--mount", "type=bind,src=/secure/postgres/prod/data,dst=/var/lib/postgresql/data",
    "--mount", "type=bind,src=/secure/postgres/prod/backup,dst=/backup",
    "--mount", "type=bind,src=/secure/postgres/secrets/postgres_pwd.txt,dst=/etc/postgres_pwd.txt",
    "--env", "POSTGRES_PASSWORD_FILE=/etc/postgres_pwd.txt",
    "-p", "0.0.0.0:5432:5432",
    "postgres_hun:11"
]
subprocess.run(cmd, shell=False)

但这看起来很丑,难以阅读,容易输入错误,笨拙等等。

我已经阅读了 xonsh 教程,也阅读了“bash 到 xonsh 的转换”部分,但没有关于将长命令分成多行的内容。

我怎样才能做到这一点而不增加太多语法噪音? 有没有一些易于编写和阅读且易于使用的东西?

答案1

用 拆分的多行语句\(如问题中的语句)与 一起使用xonsh v0.11

相关内容