首页 > 解决方案 > 使用 Python,一个新行被截断的命令

问题描述

我有一个 FIO 配置,它有很多行,我正在使用“echo”将配置的内容写入一个新文件。

config='''[global]
ioengine=libaio   ; async I/O engine for Linux
direct=1
randrepeat=0      ; use same seed for random io for better prediction
thread            ; use thread rather than process
group_reporting
; 
readwrite=randrw
percentage_random=100
iodepth=30
rwmixread=0
blocksize=3434
randrepeat=0
blockalign=3434
runtime=45454
time_based=1

[job 1]
filename=/dev/sdb
filesize=2934m
'''

我正在尝试以下操作:

cmd = '''echo "%s" > /tmp/fio.cfg''' % config

print(cmd)

但我不断回来:

echo "[global]"

global 之后的行被截断。任何想法都非常感谢!

标签: python-3.x

解决方案


Bash 并且echo不支持多行字符串。格式化echo命令时,运行命令时不会正确表示多行。

echo "[global]"

echo仅使用您构造的字符串的第一行%s ... % config,因此 config 必须只保留"[global]".

解决方案很简单。你甚至不必使用 bash|shell 来完成这项工作,你可以在 python 中完成所有这些工作。


myconfig='''[global]
ioengine=libaio   ; async I/O engine for Linux
direct=1
randrepeat=0      ; use same seed for random io for better prediction
thread            ; use thread rather than process
group_reporting
; 
readwrite=randrw
percentage_random=100
iodepth=30
rwmixread=0
blocksize=3434
randrepeat=0
blockalign=3434
runtime=45454
time_based=1

[job 1]
filename=/dev/sdb
filesize=2934m"
'''

with open('/tmp/fio.cfg','w') as fo
    fo.write(myconfig)

Python 确实支持多行字符串。

\或者,在 bash 中,您可以在换行符所在的位置用字符编写字符串,这将告诉 bash 将下一行视为前一行的一部分。

echo "This is a multi line string.\
 It it keeps going on and on."

你会回来:

This is a multi line string. It it keeps going on and on.

通常,在 bash 脚本中,返回(新行)表示插入行的结尾,因此当您进入下一个 bash 时,假定您想要 a;否则会给您的行为。

添加\n新行并添加-e到 echo 会将输出放在单独的行上。

-e 启用反斜杠转义的解释

echo -e "This is a multi line string\
\nIt it keeps going on and on."

然后你会回来:

This is a multi line string.
It it keeps going on and on.

推荐阅读