在bash(按Python启动)中,我想打印此字符串 \ 033 [31M
,以便我可以使用管道 |
操作员,然后是命令将该字符串复制到剪贴板。这意味着在实践中,我正在尝试运行类似的操作:
os.system('echo \\033[31m | xsel -ib')
...但是 XSEL -IB
部分工作正常,因此该问题专门针对 echo /代码>。
我的大多数尝试都与:
echo -e \\033[31m
我尝试过单语引号,双引号,无引号,删除 -e
flag等。我得到的最接近的是:
echo -n "\\ 033[31m"
它打印此字符串> \ \ 033 [31M
我不希望 \
和 0
-n
flag在印刷字符串之后的新行
我使用Ubuntu 20.04, XSEL
是X11窗口系统的选择和剪贴板操纵工具(Ubuntu 20.04使用)。
In bash (as started by Python), I want to print this string \033[31m
so that I can use a pipe |
operator after it, followed by a command to copy that string to the clipboard. This means that in practice, I'm trying to run something like:
os.system('echo \\033[31m | xsel -ib')
...but the xsel -ib
part is working fine, so this question is focused specifically on the behavior of echo
.
Most of my attempts have been similar to:
echo -e \\033[31m
I have tried it with single quotes, double quotes, no quotes, removing the -e
flag, etc. The closest I got was:
echo -n "\\ 033[31m"
which prints this string \ 033[31m
I don't want that space between \
and 0
-n
flag is used to not append a new line after the printed string
I use Ubuntu 20.04, and xsel
is a selection and clipboard manipulation tool for the X11 Window System (which Ubuntu 20.04 uses).
发布评论
评论(1)
Echo
是工作的错误工具。这是一个内置的外壳,并且在其上,明确的POSIX SH标准不能保证在逃生序列(例如\ 033
)时的便携式行为。System()
启动/bin/sh
而不是bash,因此Posix行为 - 不是您的常规交互式外壳的行为。使用
subprocess.run()
而不是os.system()
,并且首先不需要echo
。如果要将逃生序列放入剪贴板中(因此不是
\ 033
,而是将其转换为echo echo
的ESC键,并将其XSI扩展到POSIX):如果您想在不解释的情况下将文字文字放置(因此有一个实际的后斜线和实际的零),请使用原始的bytestring:
对于为什么要详细说明为什么
echo
在此上下文中引起问题,请参阅Stephane的出色答案。 Linux堆栈交换问题为什么是printf
printf 比echo
?更好。如果由于某种原因 do 想要继续使用Shell管道,请切换到
printf
:echo
is the wrong tool for the job. It's a shell builtin, and one for which the POSIX sh standard explicitly does not guarantee portable behavior for when escape sequences (such as\033
) are present.system()
starts/bin/sh
instead of bash, so POSIX behavior -- not that of your regular interactive shell -- is expected.Use
subprocess.run()
instead ofos.system()
, and you don't needecho
in the first place.If you want to put an escape sequence into the clipboard (so not
\033
but instead the ESC key that this gets converted to by anecho
with XSI extensions to POSIX):If you want to put the literal text without being interpreted (so there's an actual backslash and an actual zero), use a raw bytestring instead:
For a more detailed description of why
echo
causes problems in this context, see the excellent answer by Stephane to the Unix & Linux Stack Exchange question Why isprintf
better thanecho
?.If you for some reason do want to keep using a shell pipeline, switch to
printf
instead: