darrickc
darrickc

Reputation: 1932

Is it possible to communicate with a sub subprocess with subprocess.Popen?

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

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')

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?

Upvotes: 5

Views: 3105

Answers (4)

miya
miya

Reputation: 1069

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')

Upvotes: 4

Ali Afshar
Ali Afshar

Reputation: 41633

We need more information.

  1. Is sudo asking you for a password?
  2. What kind of interface does the mod script have for asking questions?

Because these kind of things are not handled as normal over the pipe.

A solution for both of these might be Pexpect, which is rather expert at handling funny scripts that ask for passwords, and various other input issues.

Upvotes: 0

Rômulo Ceccon
Rômulo Ceccon

Reputation: 10337

I think you should remove the sudo in your Popen call and require the user of your script to type sudo.

This additionally makes more explicit the need for elevated privileges in your script, instead of hiding it inside Popen.

Upvotes: 4

mipadi
mipadi

Reputation: 410542

The simplest thing to do would be the run the controlling script (the Python script) via sudo. Are you able to do that, or is that not an option?

Upvotes: 1

Related Questions