【问题标题】:Avoid escaping dollar sign in a subcommand?避免在子命令中转义美元符号?
【发布时间】:2019-10-17 11:00:54
【问题描述】:

我需要处理一个文件并立即将其上传到某个地方。考虑这个例子,想象我们正在做aws s3 cp - s3://some-path/$FILE而不是dd调用:

from plumbum.cmd import split, seq, rev, dd
my_filter = (rev | dd['of=$FILE'])
cmd = seq['1', '10'] | split['--filter', str(my_filter)]

鉴于 $FILE 不是直接传递而是转义的,split 中的子命令会创建一个名为 $FILE 的文件。我怎样才能让它不逃避美元表达式,而是逐字逐句?

【问题讨论】:

  • 为什么不在 Python 代码中插入值?
  • @KarlKnechtel 那我不会遇到同样的问题吗?

标签: python plumbum


【解决方案1】:

作为一个临时解决方案,我决定猴子补丁plumbumshquote

from plumbum.cmd import split, seq, rev, dd

import plumbum
import unittest.mock as mock
# HACK: disable quoting of every argument in shquote
# otherwise we'd get --filter="dd 'of=$FILE'"
# which would create a file named $FILE anyway
with mock.patch('plumbum.commands.base.shquote', lambda x: x):
    my_filter = str(rev | dd['of=$FILE'])

funnychars_new = plumbum.commands.base._funnychars.replace('$', '')
# HACK: don't treat dollar sign as an escapeable character
with mock.patch('plumbum.commands.base._funnychars', funnychars_new):
    cmd = seq['1', '10'] | split['--filter', my_filter]
    print(cmd)
    cmd & plumbum.FG

将它放在命令执行之前解决了我的问题,但我欢迎其他解决方案。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-03-25
    • 2020-01-19
    • 2015-06-17
    • 2021-07-01
    • 1970-01-01
    • 2022-11-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多