How to Direct Commands to Linux Terminal with Python

6

I need to create a script in Phyton that when run either by mouse click or 'enter' the keyboard, it opens the Linux terminal itself and executes any command inside it. I've already been able to get it to run the command, but as long as the script runs inside the terminal.

I have tried everything I was able to do with google, I tried to use os.system (), subprocess (), but none solved.  My code at the moment is the following:

#!/usr/bin/env python3
# -*- coding; utf-8 -*-


import subprocess

processo = subprocess.Popen(args = ['pantheon-terminal'],
                     stdin = subprocess.PIPE,
                     stderr = subprocess.PIPE,
                     shell = True)

processo.communicate('ls') # Aqui um erro 

It should open the terminal and run the ls command, but only open the terminal.

Edit:  As you can see above, I was using process.communicate ('ls'), ie I was passing the command wrongly, but I still do not know where to put the command for it to run inside the terminal that was opened by the script. / p>     

asked by anonymous 17.08.2014 / 21:42

2 answers

2

Try:

#!/usr/bin/env python3
# -*- coding; utf-8 -*-

import subprocess

processo = subprocess.call(["ls", "-la"], shell=True)
#seria o mesmo que ls -la no seu terminal.

See details in:

link

    
20.08.2014 / 03:14
1

In parts:

  • What will happen if you click on your script depends on what it is
    setting up to be done in the window manager.
  • Assuming the script runs: the python interpreter does not has a graphical interface, so it will always open in a terminal, but the environment inside python may be different from environment of your terminal emulator, for example: If, when opening a terminal it will be in the / home / user directory and the xyz command works, inside python is another story. It may be necessary to enter the directory in question and add the xyz command path to the PATH.
  • If a terminal is opened only to run a program without graphical interface, it will be closed as soon as the program finish. To avoid this, using python, you can add a pause at the end of your script [example1] or wait for the user to type enter [example2].

  • Here I left a small class to help in executing commands, I find it very useful!

  • [example1]

    from time import sleep
    sleep(5)
    

    [example2]

    raw_input('Presione enter para sair')
    

    Note: Items 1 and 2 do not seem to be your problem right now, I quoted them because I believe they might come to be.

        
    29.08.2014 / 00:52