1

I am trying to run the avrdude commands in the terminal via the python's gui (PySimple)... it does not return me any error, however, it does not work either. So here are the questions:

  1. why does it not work? Either, if I want to run the script-the txt file or a simple shell command such as 'ls' Have a look at the code.
  2. how can I see the shell terminal inside the python? that would help me to see what is going on...

The original idea.

import PySimpleGUI as sg
import subprocess
    
layout = [
    [sg.Text('Filename')],
    [sg.Input('', key='filename'), sg.FileBrowse()],
    [sg.Button('Ok'), sg.Button('Cancel')],
]
    
window = sg.Window('Test', layout)
    
while True:
    event, values = window.read()
    if event in ('Exit', None): break
    
    #print(event, values)
    
    if event == 'Ok':
        print(event, values)
        #run the terimanl code???
        #subprocess.run('/Users/mu234/Desktop/myScript_sm-ir.txt')
        subprocess.run('ls') 
    
window.close()

After few days of your comments (eg. the MikeyB, etc ) and several of my discussions, googling, I have moved a bit, and will post here the attempt how this could be approached, however, when the file is processed, somehow the whole program does not work...

import subprocess
import sys
import PySimpleGUI as sg

sg.theme('Dark Blue 4')

def main():
    layout = [
                [sg.Output(size=(110,40), background_color='black', text_color='white')],
                ##[sg.T('Prompt> '), sg.Input(key='-IN-', do_not_clear=False)], #type in prompt
                                [sg.Text('Choose the script you want to process')],
                                [sg.Input('', key='filename'), sg.FileBrowse()], #choose a file you want to process with the script
                                #[sg.Button('Process'), sg.Button('Cancel'), sg.Button('Exit')]], #process the chosen file, else exit
                [sg.Button('Process', bind_return_key=True), sg.Button('Exit')] ]

    window = sg.Window('Realtime Shell Command Output', layout)

    while True:             # Event Loop
        event, values = window.read()
        # print(event, values)
        if event in (sg.WIN_CLOSED, 'Exit'):
            break
        elif event == 'Process':
            #print(event, values)
                      
            runCommand(cmd=values['filename'], window=window)          
    window.close()


def runCommand(cmd, timeout=None, window=None):
    nop = None
    
    """ run shell command
    @param cmd: command to execute
    @param timeout: timeout for command execution
    @param window: the PySimpleGUI window that the output is going to (needed to do refresh on)
    @return: (return code from command, command output)
    """
    
    p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    output = ''
    for line in p.stdout:
        line = line.decode(errors='replace' if (sys.version_info) < (3, 5) else 'backslashreplace').rstrip()
        output += line
        print(line)
        window.refresh() if window else nop        # yes, a 1-line if, so shoot me
    retval = p.wait(timeout)
    return (retval, output)

main()

The GUI is there, the user can easily browse and select the file (the script) and process it, however, somehow the script is stuck. For example, this is the output I get in the GUI:

/Users/mu234/Desktop/myScript_am-ir.txt: line 3: --: command not found

/Users/mu234/Desktop/myScript_am-ir.txt: line 5: avrdude: command not found

/Users/mu234/Desktop/myScript_am-ir.txt: line 9: --: command not found

/Users/mu234/Desktop/myScript_am-ir.txt: line 11: avrdude: command not found

/Users/mu234/Desktop/myScript_am-ir.txt: line 14: --: command not found

/Users/mu234/Desktop/myScript_am-ir.txt: line 16: avrdude: command not found

it works?

In short, it does not do the job. I was thinking there is something wrong with the permissions? I am on OSX. , I guess the problem is with the permissions to access the file... the script and execute the commands within the scrip? In general, the script has few lines of code (have a look at here for possible commands: https://www.cs.ou.edu/~fagg/classes/general/atmel/avrdude.pdf).

For example, if only "echo ..." is used it works ok, as you can see in above print... Anyway, please, have a look at the code and comment what could be wrong.

  • There are a number of demo programs located in the PySimpleGUI GitHub that show how you can launch scripts from within a PySimpleGUI program, get the output, and then optionally display in your window. A good one to examine is Demo_Script_Launcher_Realtime_Output which uses Popen rather than run. – Mike from PSG Nov 01 '20 at 20:52
  • Thanks, this is valuable input, got the script you are referring to, and it works, however, I will need more time to study this and put the two together :) – Somene From EU Nov 02 '20 at 09:21
  • Please don't post addendums or extra questions in answers. If you have more information about *this* question, please [edit] it in. Otherwise, please ask a new question instead – Machavity Nov 02 '20 at 13:21

1 Answers1

0

when you use subprocess.run(command) it will write the output to sys.stdout (/dev/stdout on linux) which is basically the output for the terminal/console.

You're probably looking to do something more like this

from subprocess import Popen, PIPE

proc = Popen(command.split(' '), stdin=PIPE, stdout=PIPE, stderr=PIPE) # spawns the process, but redirects stdin, stdout, and stderr from the terminal/console
proc_output = proc.communicate()[0].decode('utf-8') # reads stdout output and stores string into a variable
# Do something with proc_output in your GUI

Also I see in your commented out line, that you're trying to spawn a process with a .txt file? if that's a script, you're going to want to change the file extension (required on windows, shebangs are sufficient for linux)

P.S. Instead of using the subprocess module to run your script, you can simply import the functions from your script and call those functions from a different script/file.

Google and documentation are your friend

JackofSpades
  • 113
  • 1
  • 8
  • Cheers for quick reply and information. Not really sure what do you mean by the "Instead of using... " ? The idea behind the script is to have all the functions within as a one file that can be quickly executed, especially with GUI, just one press with a mouse... – Somene From EU Oct 30 '20 at 11:46
  • If your program is just a simple file launcher, no need to pay attention to that, which it does appear to be the case when I look a little bit closer. Since my solution answered your question, perhaps you could mark it as the correct answer? (You can always change this later) – JackofSpades Oct 30 '20 at 12:57
  • Thanks, somehow it does not work, the error I get, probably my fault how I how put the Code, sorry new to this...: Ok {'filename': '/Users/mu234/Desktop/myScript_sm-ir_copy.sh', 'Browse': '/Users/mu234/Desktop/myScript_sm-ir_copy.sh'} Traceback (most recent call last): File "/Users/mu234/Desktop/Python delam/run file.py", line 28, in proc = Popen(command.split(' '), stdin=PIPE, stdout=PIPE, stderr=PIPE) NameError: name 'command' is not defined – Somene From EU Nov 02 '20 at 09:09
  • You are reinventing `subprocess.run()`, poorly. – tripleee Nov 02 '20 at 13:11