python-3.x - 使用 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 之后的行被截断。任何想法都非常感谢!
解决方案
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 会将输出放在单独的行上。
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.
推荐阅读
- python - 来自 open ai 安装的 Atary 示例
- c# - 如何使用 HotChocolate 和 EFCore 创建 GraphQL 部分更新
- c - 如何使用 c 中的指针解决此问题?
- c - 如何计算C中结构数组的总内存需求?
- python - 使用给定的参数化
- python - 使用 CSV 文件访问 Python 3 中的数据?
- forms - 通过函数在powershell中更改变量值的问题
- node.js - 我可以将 MERN 应用程序上传到 bluehost 服务器并运行吗?
- macos - 通过 LAN 从 Linux 到 Mac 的 X11 远程(无 ssh 转发)加速
- android - Retrofit2 不使用完整的基本网址