How to Direct Commands to the Linux Python Terminal

Asked

Viewed 5,650 times

7

I need to create a script in Phyton that when executed is via mouse click or keyboard 'enter', it opens the linux terminal itself and execute any command inside it. I have already managed to get him to execute the command, but as long as the script is executed inside the terminal.

I tried everything I could via google, tried using.system(), subprocess(), but none solved. My code at this point is this:

#!/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 execute the ls command, but only open the terminal.

Edit: As you can see above, I was using process.communicate('ls'), that is, I was passing the command wrong way, but I still don’t know where to put the command to run inside the terminal that was opened by the script.

2 answers

3


1

Split:

  1. What will happen when you click on your script depends on what is
    configuring to be done in the window manager.
  2. Assuming script runs: 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 pure and simple environment of your terminal emulator, for example: If, when opening a terminal it will be in the directory /home/user and Xyz command works, inside python is another story. You may need to enter the directory in question and add the Xyz command path to the PATH.
  3. 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].

  4. Here I left a small class to help in the execution of commands, I find it very useful!

[exemplo1]

from time import sleep
sleep(5)

[exemplo2]

raw_input('Presione enter para sair')

Note: Items 1 and 2 do not seem to be your current problem, I cited them because I believe they might be.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.