在Python中,subprocess.Popen 可以实现执行命令行输入。通过创建 Popen 对象并传入需要执行的命令以及 stdin=subprocess.PIPE 参数,可以实现对命令行的输入。以下是一个示例代码:
import subprocess# 执行命令行输入command = 'grep hello'proc = subprocess.Popen(command, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)# 输入数据到命令行input_data = "hello world\n"proc.stdin.write(input_data.encode())proc.stdin.close()# 读取命令行输出output = proc.stdout.read().decode()print(output)在上面的示例中,使用 subprocess.Popen 执行了 grep hello 命令,然后通过 proc.stdin.write 输入了 “hello world\n” 数据,并通过 proc.stdout.read() 读取了命令行的输出。最后打印输出结果。


