7

I am trying to open a terminal and run a command in it. I am using

os.system("gnome-terminal -e 'bash -c \"exec bash; MY_COMMAND; exec bash\" '")

This opens up a new terminal, but the command is not executed.

5
  • 4
    Why do you surround your command with exec bash? Commented Apr 10, 2017 at 20:59
  • 2
    Do you need to run this in a terminal? What about subprocess python module? Commented Apr 10, 2017 at 21:04
  • @zondo it keeps the terminal open after execution Commented Apr 10, 2017 at 21:15
  • @RaydelMiranda it needs to run in a terminal Commented Apr 10, 2017 at 21:16
  • Well, you don't need that beforehand. What I do is: MY_COMMAND; echo Hit ^C to close this terminal; while true; do sleep 2; done Commented Apr 10, 2017 at 21:17

3 Answers 3

8

The exec command replaces the currently running process with a new one, so if you have an exec in a list of commands to run, as soon as exec is run, nothing else will run. So you're replacing 'bash -c \"exec bash; MY_COMMAND; exec bash\" ' with bash, and then nothing after the exec bash is running. Try this instead:

os.system("gnome-terminal -e 'bash -c \"MY_COMMAND\" '")

or if you need a terminal to stay open, try this:

os.system("gnome-terminal -e 'bash -c \"MY_COMMAND; sleep 1000000\" '")

of if you want the terminal to stay open and be in a bash shell, try this:

os.system("gnome-terminal -e 'bash -c \"MY_COMMAND; bash\" '")
Sign up to request clarification or add additional context in comments.

3 Comments

Can you tell me how to open a tab and run "MY_COMMAND" instead of new terminal every time?
how to close that terminal?
@sutirtha that would depend on the terminal and whether the terminal supports opening a new tab from within a session. See this answer for a way that may work.
7

Here we go...

command="python3 --version"
os.system("gnome-terminal -e 'bash -c \""+command+";bash\"'")

That should do it...

Output:Python 3.6.4

And the output came into a new terminal....

Comments

1

How to open and close that terminal after running the command

You can run this command in python file

os.system("gnome-terminal -e 'bash -c \"sudo -S <<< Notadmin apt-get update && exit; exec bash\"'")

In this command, we have multiple parameters

  1. It will open a terminal first.
  2. it will run simple and sudo commands as well.
  3. after installing it will close automatically.

I m using Ubuntu 20.04 and using this command in my API. and it works fine.

**sudo -S <<< Notadmin apt-get update**
  • -S this parameter to read password 'Notadmin' is my system password

This will work without sudo

os.system("gnome-terminal -e 'bash -c \"pip install python && exit; exec bash\"'")

Comments

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.