codeheadache
codeheadache

Reputation: 164

How to perform a cd command and execute additional command in a new terminal from a python script?

I am trying to run a python script on ubuntu18, which simply will open a new terminal/tab,navigate to a specific folder and then execute a command. But this simple task is looking very daunting due to my lack of knowledge. Expected:

In the python script
$cd /home/metabase
$java -jar metabase.jar 

My code:

try1:
cmd = "gnome-terminal --tab 'cd /home/metabase/java -jar metabase.jar; read'"
os.system(cmd)
New tab opens but nothing happens

try2:
subprocess.call(['cd /home/metabase/', 'java -jar metabase.jar'])
Error:No such file or directory

I tried many other combinations. But results in either new tab not opening or new tab opens but in the same directory and does nothing. I did some reading on the problem. It seems like i am creating these subprocess and therefore when i do the CD, it does nothing. Anyways,i looked into many similar stackoverflow threads but i am still lost. Any direction would be appreciated. Thank you

Upvotes: 2

Views: 1372

Answers (2)

dejanualex
dejanualex

Reputation: 4348

Why do you want to change the directory ? If you want you can do it directly :

os.system('java -jar /home/metabase/metabase.jar') which will return the process exit value , 0 means success.

Keep in mind that os.system will execute the command passed as a string in a sub-shell.

If you do not want to spawn a new shell, you can use:

subprocess.call(['java', '-jar', '/home/metabase/metabase.jar']) in this way there is no system shell started up, so the first argument must be a path to an executable file.

Upvotes: 0

that other guy
that other guy

Reputation: 123570

The command to open a new gnome-terminal window with a bash command is:

gnome-terminal -- bash -c 'your command'

In your case:

gnome-terminal -- bash -c 'cd /home/metabase; java -jar metabase.jar; read'

Make sure this works from a shell first. Then you can invoke it from Python:

subprocess.call(["gnome-terminal", "--", "bash", "-c", "cd /home/metabase; java -jar metabase.jar; read"])

Upvotes: 2

Related Questions