2

I'm working on a small script. The script should open 3 terminals and interact with this terminals independently.

I am pretty understand that subprocess is the best way to do that. What I've done so far:

# /usr/bin/env python
import subprocess

term1 = subprocess.Popen(["open", "-a", "Terminal"], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
term1.communicate(input="pwd")

My problem is I cannot interact with a new terminal. this part term1.communicate(input="pwd") is not working. I cannot send a command to a new Terminal. I also tried term1.communicate(input="pwd\n") but nothing happens

Do you any ideas how can I do that?

P.S. I am using Mac OS.

4
  • 1
    Do you really need to open a new terminal for what you are trying to accomplish, or do you just need to run pwd and capture the output? Commented Sep 12, 2014 at 19:15
  • 1
    Also, communicate waits until the process has completed, Terminals generally don't exit until closed, so it makes sense that it does nothing. Commented Sep 12, 2014 at 19:23
  • @user2085282 in my case I have to run 2 commands: "sudo tcprelay telnet" and "tcprelay --portoffset [arg1] [arg2]" but problem is if I run one of the command without opening a new Terminal I will not be able to run the second until the first one is done/terminated. That's why I use this solution Commented Sep 12, 2014 at 20:38
  • Just a head's up, you don't want to be using sudo inside of your script. instead, check if you have elevated privileges using os.getuid() == 0 and run the command as normal Commented Sep 12, 2014 at 21:41

1 Answer 1

4

You can run both commands concurrently without opening terminals.

import subprocess
process1 = subprocess.Popen(["ls", "-l"])
process2 = subprocess.Popen(["ls", "-l"])

If you run that code you will see that the directory is listed twice, interleaved together. You can expand this for your specific needs:

tcprelay1 = subprocess.Popen(["tcprelay", "telnet"])
tcprelay2 = subprocess.Popen(["tcprelay", "--portoffset [arg1] [arg2]")
Sign up to request clarification or add additional context in comments.

2 Comments

problem is I have to use "sudo" commannd in tcprealy1 and have to communicate with this.
You're going to have to run your python script with sudo then, and be careful... You can still communicate with the processes, I just left that part out.

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.