[Tutor] Asking about Opening Teminal on Python

Alan Gauld alan.gauld at yahoo.co.uk
Fri Feb 24 04:28:02 EST 2017


On 24/02/17 02:04, Quang nguyen wrote:
> Right now, I have school project for sending signal from Pi2 to
> mutilple devices. And I am using 433Utils library for sending
> and receiving signal. They provided file for do that but it only
> execute on terminal, and i also have an UI.
>
> So I have an idea that will execute the sending command
> by terminal behind my UI.

That's probably the wrong approach.
What you really want to do is execute the command you
would normally type at the terminal, directly from your GUI.
You only need to start a terminal if your user needs to
enter the commands manually.

For example, here is some code to execute the 'ls'
command and print only files that have a name shorter
than 6 characters:

#!/usr/bin/python3
import subprocess as sub

ls_out = sub.Popen(['ls'], stdout=sub.PIPE).stdout
for name in ls_out:
    if len(name) < 6:
        print(name)
###############

You can substitute any command for 'ls' and you
can add arguments too.

You can also assign stdin as a pipe in the same way
as stdout and use that to inject data into the
command.

You can even make stdin/stdout use files too. Here is
the above example saving the output to a text file:

sub.Popen(['ls'], stdout=open('ls_out.txt','w'))

You can then read and manipulate the data
from ls_out.txt as desired.

The subprocess module documentation contains
many examples.

So unless you really need your user to type
the commands by hand you don't need a
terminal window.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



More information about the Tutor mailing list