如何使用python使用子进程[duplicate]将输入发送到另一个程序

问题描述 投票:0回答:2

我想使用python向基于cmd的程序发送一些输入。该程序通常从键盘输入类型。

我试过:

P1=subprocess.Popen("my_program",stdin=subprocess.PIPE,stdout=subprocess.PIPE,sterr=subprocess.PIPE)
p1out,p1err=P1.communicate(input="my_input")

但是给出了错误,因为“它需要像对象一样的字节而不是str”。我也尝试过P1.stdin.write()方法并再次给出同样的错误。我的输入dtype应该是什么?

python subprocess
2个回答
2
投票

看起来所有你必须改变的是你的字符串到'字节'类型。

type("my_input")
>>>> str
type(b'my_input')
>>>> bytes

0
投票

我解决了使用

my_input=my_input.encode("utf-8")
© www.soinside.com 2019 - 2024. All rights reserved.