我想将命令中带有新行的一些字符串传递到文件中,但是
argparse
没有处理\n
,如文件aaa
在以下脚本中使用命令python test.py -t "aa\nbb\ncc\n"
所示。
test.py
在这里:
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
import argparse
def wwrite():
# parser
parser = argparse.ArgumentParser(
description='Atest.')
parser.add_argument('-t', '--tail',
help='Add some lines to file')
args = parser.parse_args()
# check
if args.tail is not None:
zz_tail = str(args.tail)
else:
zz_tail = ''
# write
with open("aaa", 'w', encoding='utf-8') as fw:
fw.write(zz_tail)
with open("bbb", 'w', encoding='utf-8') as fw:
fw.write("aa\nbb\ncc")
# 主文件
if __name__ == "__main__":
wwrite()
如何获得与此相同的文件:
aa
bb
cc
不是:
aa\nbb\ncc\n
并且不更改命令
python test.py -t "aa\nbb\ncc\n"
。
有一个类似的问答,但它将命令更改为
python test.py -t $'aa\nbb\ncc\n'
。 (使用 argparse 解析带有换行符的文本)
你可以使用
zz_tail = args.tail.replace('\\n', '\n')