简体   繁体   English

为什么我不能在 Python 中通过 PS gui 运行 shell 命令?

[英]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.我正在尝试通过 python 的 gui (PySimple) 在终端中运行 avrdude 命令......它没有返回任何错误,但是,它也不起作用。 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.要么,如果我想运行脚本——txt 文件或简单的 shell 命令,比如 'ls' 看看代码。
  2. how can I see the shell terminal inside the python?我怎样才能看到python里面的shell终端? 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...经过几天的评论(例如 MikeyB 等)和我的几次讨论,谷歌搜索,我已经移动了一点,并将在此处发布尝试如何解决这个问题,但是,当文件被处理时,不知何故整个程序不起作用...

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. GUI 在那里,用户可以轻松浏览和选择文件(脚本)并对其进行处理,但是,脚本以某种方式卡住了。 For example, this is the output I get in the GUI:例如,这是我在 GUI 中得到的输出:

/Users/mu234/Desktop/myScript_am-ir.txt: line 3: --: command not found /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:第 5 行:avrdude:未找到命令

/Users/mu234/Desktop/myScript_am-ir.txt: line 9: --: 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:第 11 行:avrdude:找不到命令

/Users/mu234/Desktop/myScript_am-ir.txt: line 14: --: 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 /Users/mu234/Desktop/myScript_am-ir.txt:第 16 行:avrdude:找不到命令

it works?有用?

In short, it does not do the job.简而言之,它不起作用。 I was thinking there is something wrong with the permissions?我在想权限有问题吗? I am on OSX.我在 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 ).一般来说,该脚本只有几行代码(查看这里可能的命令: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.例如,如果只使用“echo ...”,它就可以正常工作,正如您在上面的打印中看到的那样...无论如何,请查看代码并评论可能出错的地方。

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.当您使用subprocess.run(command)它会将输出写入 sys.stdout(Linux 上的 /dev/stdout),这基本上是终端/控制台的输出。

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?另外我在您注释掉的行中看到,您正在尝试使用 .txt 文件生成一个进程? if that's a script, you're going to want to change the file extension (required on windows, shebangs are sufficient for linux)如果这是一个脚本,您将需要更改文件扩展名(在 Windows 上需要,shebangs 对 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. PS 而不是使用 subprocess 模块来运行你的脚本,你可以简单地从你的脚本中导入函数并从不同的脚本/文件中调用这些函数。

Google and documentation are your friend谷歌和文档是你的朋友

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在IPython中运行shell命令? (Python分析GUI工具) - How to run shell-commands in IPython? (Python Profiling GUI tools) 为什么我的 Keysight PS 上没有设置电压? 通过 python 中的 SCPI 发送的命令 - Why is the voltage not set on my Keysight PS? Commands sended via SCPI in python 如何从 Python 运行云 shell 命令? - How can I run cloud shell commands from Python? 如何通过Python运行两个adb shell命令,但仅存储一个输出? - How to run two adb shell commands via Python, but store output of only one? 为什么得到用户警告:Matplotlib当前正在使用ps,这是非GUI后端,因此无法显示该图 - Why am I getting UserWarning: Matplotlib is currently using ps, which is a non-GUI backend, so cannot show the figure 从Python GUI运行Shell脚本 - run a shell script from Python GUI 在 Python-Subprocess 中连续运行 Shell 命令 - Run consecutive Shell commands in Python-Subprocess 如何在 python 中运行 shell 命令 - How to run shell commands inside python 无法从 windows ps1 文件运行 python 文件 - Cannot run a python file from a windows ps1 file 如何通过python套接字运行多个命令 - How to run multiple commands via python socket
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM