h0ch5tr4355
h0ch5tr4355

Reputation: 2192

How can I open a shell with a command in python?

The following command opens a new shell and opens nano in it, when I type it into bash:

gnome-terminal -e "bash -c 'nano test; bash'"

So I tried the same in my python code with subprocess:

import subprocess
command = "gnome-terminal"
args = " -e \"bash -c 'nano test; bash'\""
subprocess.call([command, args])

I have tried already many combinations. Basically I just want to open a shell with a specific file in nano.

First I thought this would be one the easiest steps, but it turned out to be very difficult. Don't know if the problem exists due to the masking or if it's a common problem with passing variables like I am used to in shells. So it might be rather a question for AskUbuntu or the Unix section ... not sure ...

Upvotes: 0

Views: 93

Answers (1)

chepner
chepner

Reputation: 530980

The args should be the same set of individual strings you use on the command line. It's easier to think about if you construct the list all at once. gnome-terminal is the command, and it takes two arguments. (The second argument is more commonly thought of as the argument to the -e option, but from the caller's perspective, it's just two arguments. gnome-terminal itself is the one that groups them together as an option/argument pair.)

command = ["gnome-terminal", "-e", "bash -c 'nano test; bash'"]
subprocess.call(command)

(Note that you could just pass a single string and let the shell sort it out, but the explicit argument list is superior.

subprocess.call('''gnome-terminal -e "bash -c 'nano test; bash'"''', shell=True)

)

Upvotes: 1

Related Questions