[Tutor] How can I open and use gnome-terminal from a Python script?

Cameron Simpson cs at zip.com.au
Wed Jul 9 02:25:58 CEST 2014


On 08Jul2014 15:45, Jim Byrnes <jf_byrnes at comcast.net> wrote:
>I would like to automate running virtualenv with a python script by:
>
>opening gnome-terminal
>cd to proper directory
>run source /bin/activate
>
>I found some examples of using os.system() to get gnome-terminal to 
>open but I can't figure out how then cd to the proper directory in the 
>new terminal.

You basicly can't do that, in that specific order, easily via system(); it runs 
a shell command.  It also waits for it to complete; you don't say if that is 
required.

But like Alan, I think you're doing it in the wrong order. I would do the cd 
and source activate, then start the gnome-terminal.

You can do that as one shell command like this:

   cd /the/proper/directory; . /path/to/bin/activate; gnome-terminal

Such a string you can hand to os.system().

There are some obvious things to consider here:

   - proper quoting of the directory path and the path to activate; they may have almost anything in them and care is needed

   - do you intent to wait for the terminal to exit before proceeding?

Regarding the former item: for this reason it would be more robust and safer to 
do the cd (os.chdir) and activation in python. But please get the shell version 
working first to ensure it does what you want it to do.

>My biggest frustration right now is that I can't find any documentation on how 
to use os.system().  Looking at the docs on the Python site I don't see 
system() under the os module.  Googling hasn't helped.

os.system should be documented in the "os" module.

But it just takes a shell command, so aside for handling the fork/exec-of-"sh 
-c your_command"-wait, there is little to document.

Cheers,
Cameron Simpson <cs at zip.com.au>


More information about the Tutor mailing list