繁体   English   中英

使用 Tkinter 的“pip install Module”程序

[英]'pip install Module' Program with Tkinter

如何在程序中显示控制台错误信息?

我用tkinter制作了一个程序,通过简单地编写模块的名称来安装带有 Pip 的 python 模块。 但问题是我只能在有人不写任何东西时显示错误消息,例如,当模块已经安装或不存在时。 我想要这些错误消息,以便每次在普通控制台上出现错误时,它都会出现在我的程序中。

from tkinter import *
import os

window = Tk()
window.geometry('500x360')
window.title('Pip Module Installer')
window.configure(bg='Light Grey')
window.columnconfigure(0, weight=1)
# TITLE: PIP MODULE INSTALLER
welcome = Label(window, text='Pip Module Installer', fg='Dark Blue', bg='Light Grey', font=('Calibri', 15))
welcome.grid(row=0, column=0)
# TEXT: INTRODUCTION
introduction = Label(window,
                     text='This program allows you to install any Pip Module in an easy way!\n',
                     fg='Black', bg='Light Grey', font=('Calibri', 13))
introduction.grid(row=1, column=0, padx=20)

# FRAME: INSTRUCTIONS
group = LabelFrame(window, bg='Light Grey', bd=0,
                   highlightcolor='Dark Blue', highlightthickness=1.25)
group.grid(row=2, column=0, sticky='WE', padx=15, pady=10)
# TITLE: INSTRUCTIONS
label_title = Label(group, text='Instructions',
                    fg='Dark Blue', bg='Light Grey', font=('Calibri', 14))
label_title.grid(row=2, column=0, sticky='W', padx=10)
# TEXT: INSTRUCTIONS
instructions = Label(group, text='1. Type the name of the module, below:',
                     bg='Light Grey', font=('Calibri', 13))
instructions.grid(row=3, column=0, padx=10, pady=(0, 10))


def module_installer():
    if module_input.get():
        user_input = module_input.get()
        os.system('pip install ' + user_input)
        response = 'Installation done'
    else:
        response = 'ERROR: Please type the name of the module'

    response_label = Label(window, text='', bg='Light Grey', font=('Calibri', 13))
    response_label.grid(row=7, column=0, sticky='WE', padx=15, pady=(6, 0))
    response_label.config(text=response)
    module_input.delete(0, END)


# INPUT
module_input = Entry(group)
module_input.focus()
module_input.grid(row=4, column=0, sticky='WE', padx=25)
# TEXT: INSTRUCTIONS
instructions = Label(group, text='2. Click ',
                     bg='Light Grey', font=('Calibri', 13))
instructions.grid(row=5, column=0, sticky='W', padx=10, pady=(30, 15))
# INSTALL BUTTON
install_button = Button(group, text='Install', font=('Calibri', 13), command=module_installer)
install_button.grid(row=5, column=0, sticky='W', padx=(69, 0), pady=(30, 15))
# TEXT: INSTRUCTIONS
instructions = Label(group,
                     text='3. The program will do the rest',
                     bg='Light Grey', font=('Calibri', 13))
instructions.grid(row=6, column=0, sticky='NW', padx=10, pady=(0, 8))

#
if __name__ == '__main__':
    window.mainloop()

另外,如果您还有其他需要改进的地方,请提前感谢! 这是我的第一个 Tkinter GUI 程序!

在这种情况下, os.system()可能不是您想要的。 它在前台终端中运行特定命令,如果给定命令失败,您的程序将输出 stderr 内容。 例如:

import os
os.system("rm /my/nice/folder")
print("Folder deleted") # this gets executed, no matter if the folder exists or if the user lacks permissions etc.

这将打印

rm: cannot remove '/my/nice/folder': No such file or directory
256
Folder deleted

和“看起来不太好看”

我强烈建议使用pexpect,因为您可以只要求返回代码(如果命令运行成功或没有错误)并单独处理错误。 另外:您甚至可以处理诸如passwd类的交互式命令,其中该命令会提示您输入特定参数(但出于安全原因,请勿使用passwd执行此操作!)

在您的程序中:如果用户拼错了模块名称会怎样? 例如说numppy而不是numpy 您的程序将执行命令,控制台将填充错误消息,程序将继续运行,就好像模块已成功安装一样。

通过使用像 pexpect 这样的模块,您可以处理如下情况:

from pexpect import spawn

module = "numpyyy"

cmd = spawn(f"pip install {module}")
print(f"Installing {module}...") # show waiting screen here
cmd.wait()  # wait for the process to finish

rc = cmd.exitstatus  # check for the command's return-code
if rc == 0:
    print(f"{module} sucessfully installed")
else:
    # display your error message here
    print(f"There was an error while installing {module}:")
    cmd.read()  # print the whole output of your command

如果您发现我的建议有帮助,请给我一个 UP,如果您还有其他问题,请在下面发表评论:)

您可以使用os.system subprocess.Popen()而不是os.system并使用Text小部件来显示控制台输出。

首先在groupLabelFrame )下面创建Text框:

# output log
output_log = Text(window, width=60, height=10, state='disabled')
output_log.grid(row=3, column=0, pady=(0,10))

然后更新module_installer()函数如下:

import sys
import subprocess as subp

...

def module_installer():
    user_input = module_input.get().strip()
    if user_input:
        # better use the same Python that runs this script, so use sys.executable
        proc = subp.Popen([sys.executable, '-m', 'pip', 'install', user_input], stdout=subp.PIPE, stderr=subp.PIPE)
        # get the console output and errors
        stdout, stderr = proc.communicate()
        if proc.returncode == 0:
            # pip returns 0
            response = stdout.decode()
        else:
            # there are errors
            response = stderr.decode()
    else:
        response = 'ERROR: Please type the name of the module'

    # show the response in the output box
    output_log['state'] = 'normal'
    output_log.replace('1.0', 'end', response)
    output_log['state'] = 'disabled'
    # clear user input
    module_input.delete(0, END)

请注意,您需要删除window.geometry('500x360')或调整窗口大小以显示所有Text框。

暂无
暂无

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

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