是否可以使用 subprocess.Popen 与子子进程通信? [英] Is it possible to communicate with a sub subprocess with subprocess.Popen?

查看:39
本文介绍了是否可以使用 subprocess.Popen 与子子进程通信?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个 Python 脚本来打包我们的软件.这个脚本需要构建我们的产品,并打包它.目前我们有其他脚本可以单独执行每个部分,包括 csh 和 perl 脚本.一个这样的脚本运行如下:

I'm trying to write a python script that packages our software. This script needs to build our product, and package it. Currently we have other scripts that do each piece individually which include csh, and perl scripts. One such script is run like:

sudo mod args

其中 mod 是一个 perl 脚本;所以在python中我会做

where mod is a perl script; so in python I would do

proc = Popen(['sudo', 'mod', '-p', '-c', 'noresource', '-u', 'dtt', '-Q'], stderr=PIPE, stdout=PIPE, stdin=PIPE)

问题是这个模组脚本需要回答几个问题.为此,我认为传统的

The problem is that this mod script needs a few questions answered. For this I thought that the traditional

(stdout, stderr) = proc.communicate(input='y')

会起作用.我认为它不起作用,因为 Popen 控制的过程是 sudo,而不是提出问题的 mod 脚本.有什么方法可以与 mod 脚本通信并仍然通过 sudo 运行它?

would work. I don't think it's working because the process that Popen is controlling is sudo, not the mod script that is asking the question. Is there any way to communicate with the mod script and still run it through sudo?

推荐答案

我会选择 Pexpect.

I would choose to go with Pexpect.

import pexpect
child = pexpect.spawn ('sudo mod -p -c noresource -u dtt -Q')
child.expect ('First question:')
child.sendline ('Y')
child.expect ('Second question:')
child.sendline ('Yup')

这篇关于是否可以使用 subprocess.Popen 与子子进程通信?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆