1

I am writing a Python code which calls a command line (e.g. python itself) and the command will open its own shell. How can Python take control of this shell?

import subprocess
subprocess.call(['./testprg'])

# testprg will open its own shell 
# so the code below will not work
subprocess.call(['i 2'])

testprg is another program which open a shell prompt. Enter "i 2" will trigger a "insert" command with the value 2.

2 Answers 2

2

It can't. subprocess does not interact with interactive shells.

You need to use stdin=PIPE in the first subprocess an write 'i 2\n' to that pipe.

Consider using pexpect though if you want to interact with interactive programs. It might make your life much easier.

Sign up to request clarification or add additional context in comments.

Comments

0

Have a look at subprocess.Popen.communicate(). If it's just about receiving some lines and sending commands to the other process, it should be what you're looking for.

Some example:

pout, perr = Popen([tools['PASSWD'], username], stdin=PIPE, stdout=PIPE,
        stderr=PIPE).communicate("%s\n%s\n" % (password, password))

4 Comments

I have amended my code and there is an error. %1 is not a valid win32 application. I am running a Linux command instead.
Don't talk in riddles. Tell us your exact command, that you used, and copy the error as it is. My example is also from Linux.
Pout,perr = Popen(['./cmdl'], stdin=PIPE, stdout=PIPE, stderr=PIPE).communicate('i 2\n') Is this correct? Sorry I am quite new in python.
This will start ./cmd and type in i 2, and return, as if you would type in from keyboard. So then you get the error? You're running linux and it tells you something about win32?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.