Python 2.6中调用bash脚本g2p并传递标准输入的实现问题
嘿,我来帮你搞定Python 2.6里调用g2p脚本并传递标准输入的问题~
首先咱们先对齐你的需求:你要在Python里模拟这条bash命令的效果:
echo "teststring" | ./g2p @g2pumap=./map.txt
你的现有代码有两个关键问题:
- 给g2p传的参数不对!原来的bash命令里是
@g2pumap=./map.txt,但你写的是直接传./map.txt,这会导致g2p识别不到参数配置 - 没处理标准输入的传递,
check_call默认不会帮你把字符串通过管道传给子进程
针对Python 2.6,这里有两种好用的实现方式:
方式一:用
subprocess.Popen(灵活处理输入输出) 如果需要获取g2p的输出或者错误信息,用这个方法最合适:
import subprocess # 准备要传给g2p的输入文本 input_text = "teststring" # 注意命令参数要和bash里的一致,保留@g2pumap=的格式 cmd = ["./eng_GBR/g2p", "@g2pumap=./map.txt"] # 创建子进程,指定stdin为管道,同时捕获stdout和stderr proc = subprocess.Popen( cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE ) # 把输入文本传给g2p,同时获取输出和错误信息 output, error = proc.communicate(input=input_text) # 检查命令是否执行成功 if proc.returncode != 0: print(f"g2p执行出错啦:{error}") else: print(f"g2p输出结果:{output}")
方式二:用
subprocess.check_call(仅确保执行成功) 如果只需要确认g2p能正常运行,不需要捕获输出,可以这么写:
import subprocess import StringIO input_text = "teststring" cmd = ["./eng_GBR/g2p", "@g2pumap=./map.txt"] # 用StringIO把字符串包装成类文件对象,传给stdin参数 subprocess.check_call(cmd, stdin=StringIO.StringIO(input_text))
小提醒
- 尽量别用
shell=True,除非你真的需要shell的特殊功能(比如多命令管道)。用列表形式传参数更安全,能避免潜在的shell注入风险。 - 如果你的输入是非ASCII字符,在Python 2.6里直接传字符串就行,不用额外编码;要是从文件读的内容,直接把文件对象传给
stdin也可以。
内容的提问来源于stack exchange,提问作者Mahsa
相关产品推荐
相关产品推荐

