【问题标题】:How to use tr command in subprocess如何在子进程中使用 tr 命令
【发布时间】:2020-06-08 08:17:05
【问题描述】:

我是 tr 命令的新手,想知道它是如何工作的?命令如何知道要操作哪个文件?我的理解是语法是tr [options] [change from] [change to]。没有说明要操作的文件。我正在尝试创建一个 csv 文件并希望将“/”更改为“,”

我的文件开头为:

3251/pid/3256/
245/pid/09732/
234541/pid/92/
1/4918,

我想得到:

3251,pid,3256,
245,pid,09732,
234541,pid,92,
1,4918,

我有:

subprocess.run(['tr', '/', ',']), stdout = open('outfile.txt.tmp','w'))

它开始运行,但它永远不会完成,我每次都必须退出。不知道错误是什么,但如果我想在名为 infile.txt

的文件上运行 tr,我想知道我的语法应该是什么

【问题讨论】:

  • 你正在执行tr / ,所以tr正在等待输入。

标签: python csv subprocess tr


【解决方案1】:

没有任何输入 tr 将永远等待。您需要将文件内容传递给标准输入:

subprocess.run(['tr', '/', ','], stdout = open('outfile.txt.tmp','w'), input=open('foo.txt').read().encode('utf-8'))
print(open('outfile.txt.tmp').read())

输出:

CompletedProcess(args=['tr', '/', ','], returncode=0)
3251,pid,3256,
245,pid,09732,
234541,pid,92,
1,4918,

【讨论】:

    猜你喜欢
    • 2018-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-20
    • 1970-01-01
    • 1970-01-01
    • 2018-07-03
    相关资源
    最近更新 更多