gpt4 book ai didi

Python 子进程 - 将输出保存在新文件中

转载 作者:行者123 更新时间:2023-11-30 22:24:09 25 4
gpt4 key购买 nike

我使用以下命令重新格式化文件并创建一个新文件:

sed -e '1s/^/[/' -e 's/$/,/' -e '$s/,$/]/' toto> toto.json

它在命令行上运行良好。

我尝试通过 python 脚本使用它,但它不会创建新文件。

我尝试:

subprocess.call(["sed", "-e","1s/^/[/","-e", "s/$/,/","-e","$s/,$/]/ ",sys.argv[1], " > ",sys.argv[2]]) 

问题是:它在标准输出中给我输出并引发错误:

sed: can't read >: No such file or directory
Traceback (most recent call last):
File "test.py", line 14, in <module>
subprocess.call(["sed", "-e","1s/^/[/","-e", "s/$/,/","-e","$s/,$/]/",
sys.argv[1], ">",sys.argv[2])
File "C:\Users\Anaconda3\lib\subprocess.py", line 291, in
check_call raise CalledProcessError(retcode, cmd)
subprocess.CalledProcessError: Command '['sed', '-e', '1s/^/[/', '-e',
's/$/,/', '-e', '$s/,$/]/', 'toto.txt, '>', 'toto.json']' returned non-zero
exit status 2.

我阅读了子进程的其他问题,并尝试使用选项 shell=True 的其他命令,但是它也不起作用。我使用Python 3.6

有关信息,该命令在第一行和最后一行中添加一个括号,并在除最后一行之外的每行末尾添加一个逗号。所以,确实如此:

from
a
b
c

至:

[a,
b,
c]

最佳答案

在 Linux 和其他 Unix 系统上,重定向字符不是命令的一部分,而是由 shell 解释,因此将其作为参数传递给子进程是没有意义的。 p>

希望 subprocess.call 允许 stdout 参数是一个文件对象。所以你应该这样做:

subprocess.call(["sed", "-e","1s/^/[/","-e", "s/$/,/","-e","$s/,$/]/ ",sys.argv[1]],
stdout=open(sys.argv[2], "w"))

关于Python 子进程 - 将输出保存在新文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47904028/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com