简体   繁体   中英

Why I cannot run shell commands via PS gui in Python?

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.

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)

PS 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM