为什么我无法在Python中通过PS gui运行Shell命令?

如何解决为什么我无法在Python中通过PS gui运行Shell命令?

我正在尝试通过python的gui(PySimple)在终端中运行avrdude命令...它不会给我返回任何错误,但是,它也不起作用。所以这是问题:

  1. 为什么它不起作用?如果我要运行脚本-txt文件或简单的shell命令(例如“ ls”),请查看代码
  2. 如何查看python内部的shell终端?可以帮助我了解发生了什么...

最初的想法。

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()

经过几天的评论(例如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')],#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()

GUI在那里,用户可以轻松浏览并选择文件(脚本)并进行处理,但是,脚本被卡住了。例如,这是我在GUI中获得的输出

/Users/mu234/Desktop/myScript_am-ir.txt:第3行:-:找不到命令

/Users/mu234/Desktop/myScript_am-ir.txt:第5行:avrdude:命令不存在 找到

/Users/mu234/Desktop/myScript_am-ir.txt:第9行:-:找不到命令

/Users/mu234/Desktop/myScript_am-ir.txt:第11行:avrdude:命令不存在 找到

/Users/mu234/Desktop/myScript_am-ir.txt:第14行:-:命令不 找到

/Users/mu234/Desktop/myScript_am-ir.txt:第16行:avrdude:命令不存在 找到

有效吗?

简而言之,它不起作用。我以为权限有问题吗?我在OSX上。 ,我想问题出在访问文件的权限...脚本和在脚本中执行命令吗?通常,该脚本只有几行代码(请查看此处的可能命令:https://www.cs.ou.edu/~fagg/classes/general/atmel/avrdude.pdf)。

例如,如果仅使用“ echo ...”,则可以正常工作,如您在上图中所看到的...无论如何,请看看代码并注释可能出问题的地方。

解决方法

当您使用subprocess.run(command)时,它将把输出写入sys.stdout(在Linux上是/ dev / stdout),基本上是终端/控制台的输出。

您可能正在寻找更多类似的东西

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

我还在您的注释行中看到您正在尝试使用.txt文件生成一个进程吗?如果这是一个脚本,您将要更改文件扩展名(在Windows上要求,对于Windows来说shebangs就足够了)

P.S。无需使用子过程模块来运行脚本,您只需从脚本中导入函数并从其他脚本/文件中调用这些函数即可。

Google和文档是您的朋友

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?
Java在半透明框架/面板/组件上重新绘画。
Java“ Class.forName()”和“ Class.forName()。newInstance()”之间有什么区别?
在此环境中不提供编译器。也许是在JRE而不是JDK上运行?
Java用相同的方法在一个类中实现两个接口。哪种接口方法被覆盖?
Java 什么是Runtime.getRuntime()。totalMemory()和freeMemory()?
java.library.path中的java.lang.UnsatisfiedLinkError否*****。dll
JavaFX“位置是必需的。” 即使在同一包装中
Java 导入两个具有相同名称的类。怎么处理?
Java 是否应该在HttpServletResponse.getOutputStream()/。getWriter()上调用.close()?
Java RegEx元字符(。)和普通点?