Указание типов текста из стандартного вывода в подпроцессе.Popen в Python

#python #batch-file #tkinter #subprocess

#python #пакетный файл #tkinter #подпроцесс

Вопрос:

Прежде всего, извините, если заголовок не настолько описательный, насколько это возможно, это трудно объяснить.

Я выполнил вызов подпроцесса для пакета и перенаправил все содержимое на консоль python с помощью print() , выполняемый пакет печатает информационные сообщения, и мне нужно распечатать пользовательское сообщение, только если пакетное сообщение является определенным. Но каким-то образом python обнаруживает, что это не та же строка.

Я не знаю, проблема ли это с кодировкой (я кодирую readline в iso-8859-1 , чтобы избежать ошибок кодирования utf-8 ).

Вот мой код.

 from tkinter import *
    from tkinter import ttk
    from subprocess import Popen, PIPE
    import os


    gui = Tk()

    text = Text(gui)
    lb = ttk.Label(text="My bat")

    cmd = 'C:\Users\User\Desktop\BAT1.bat'

    def runbat():
        proc = Popen(cmd,shell=False,stdout=PIPE)
        while True:
            line = proc.stdout.readline().decode('iso-8859-1').rstrip('n')

            if line != '':
                myline = 'INFO Starting: Initialize communication activity (InitializeCommunication).'
                if line == myline:
                    print("That's the line!")
                print(line)
            else:
                break

    bt = ttk.Button(text="Run bat", command=runbat).grid(row=4, column=5)

    text.grid(row=6, column= 5)
    lb.grid(row=3, column=5)
    prog.grid(row=7,column=5)
    mainloop()
  

И это результат:

 C:Python34python.exe "C:/Users/User/Documents/Desarrollo/Boos Production Manager/preferences/multioneproof.py"

C:UsersUserDocumentsDesarrolloBoos Production Managerpreferences>cd /D C: 

C:UsersUserDocumentsDesarrolloBoos Production Managerpreferences>cd C:Program FilesPhilips MultiOne Workflow 

C:Program FilesPhilips MultiOne Workflow>MultiOneWorkflow.exe /f "C:/Users/User/Desktop/A.xml" /w "Z:Spain Factorymultione configurationverify.txt" /p S /lu true /v info /c Halt 
WARN Parameter IncludeUniqueIdOfDeviceInLabelData is provided without the GenerateAndExportLabelData parameter.
INFO Philips MultiOne Workflow version 3.11.91.28
INFO OS: Microsoft Windows 10 Home. Computer name: PC-DAVID. Application path: C:Program FilesPhilips MultiOne WorkflowMultiOneWorkflow.exe. Running as administrator: no. Format: Espa¤ol (Espa¤a) [es-ES], date format: dd/MM/yyyy, right to left: no, decimal separator: [,].
INFO Key: N/A. Profile: Debug. TwelveNc: N/A. 
INFO Privileges: 0-10V / 1-10V: All. 0-10V / 1-10V (LED Driver): All. ActiLume: All. ActiLume wired: All. ActiLume wireless: All. Active Cooling: All. Adjustable Light Output: All. Adjustable Light Output Minimum: All. Adjustable Output Current: All. Adjustable Output Current Multi-Channel: All. Adjustable Startup Time: All. AmpDim: All. Coded Light: All. Coded Light Pwm: All. Coded Light Randomize: All. Coded Mains Scene Settings: All. Coded Mains Standalone Receiver: All. ComBox: All. Constant Light Output: All. Constant Light Output LITE: All. Constant Light Output Multi-Channel: All. Correlated Color Temperature Dual Channel: All. Correlated color temperature: All. Corridor Mode: All. DALI 102 variables: All. DALI Power Supply: All. DC Emergency: All. Dali 202 variables: All. Daylight override / Daylight switching: All. Device Info: All. Diagnostics: All. Diagnostics Emergency: All. Diagnostics Motor Controller: All. Dimming Interface: All. Driver Addressing: All. Driver Temperature Limit: All. Dwell Time: All. Dynadimmer: All. Emergency: All. End Of Life indication: All. Energy Meter: All. FCC Test Mode Settings: All. Factory link: All. Field Task Tuning: All. Field Task Tuning/Occupancy Sensing/Daylight Harvesting: All. Lamp Burn-in: All. Lamp selection: All. Late Stage Configuration: All. Light Source Age: All. LineSwitch: All. Load Fault Indicator Thresholds: All. Logical Signal Input: All. Lumen Level: All. LumiStep: All. Luminaire (Fixture) Information: All. Luminaire Production Test: All. Min dim level: All. Module Temperature Protection: All. Motor Control: All. NTC on LedSet: All. OEM Write Protection: All. Occupancy / Daylight: All. Occupancy sharing / Group light behavior: All. PowerBox: All. Push Button Unit LCU2070: All. Push Button Unit LCU2071: All. Quick Lamp Start: All. Relay Switched Output: All. SR Power Supply: All. Set Lamp uptime: All. Step Dimming: All. Touch and Dim: All. 
INFO On warnings: halt
INFO Using Writeamp;Verify.
INFO Multiple device configuring: Disabled
INFO Commission all: Disabled
INFO Check device model: Enabled
INFO DALI factory new: Disabled
INFO Starting: Prepare system activity (PrepareSystem).
INFO Success: Prepare system activity (PrepareSystem).
INFO Starting: Select feature file activity (OpenFile).
INFO Opening features file
INFO Provided file: c:/users/user/desktop/a.xml
INFO Success: Select feature file activity (OpenFile).
INFO Starting: Initialize communication activity (InitializeCommunication).
INFO Success: Initialize communication activity (InitializeCommunication).
INFO Starting: Identify device activity (IdentifyDevice).
INFO Devices identified: 0
ERROR No connected devices were found
ERROR Failure: Identify device activity (IdentifyDevice).
INFO Starting: Stop activity (Stop).
INFO Success: Stop activity (Stop).
INFO End

C:Program FilesPhilips MultiOne Workflow>echo 500  1>"Z:Spain Factorymultione configurationlog.txt" 

Process finished with exit code 0
  

Поэтому я думаю, что он должен напечатать мое пользовательское предложение, когда дело доходит до правильной строки, но по какой-то причине он этого не делает.

Ответ №1:

 if line != '' :
    myline = 'INFO Starting: Initialize communication activity (InitializeCommunication).'
    if str(myline) in str(line) :
        print("That's the line!")
    print(line)
else :
    break
  

В этом значении вашей переменной ‘line’ есть дополнительные пробелы в конце, которых нет в переменной ‘myline’, поэтому ваше условие равно if не выполняется, если вы используете in condition, это решит эту проблему.

Комментарии:

1. Вот и все. Я опубликовал ответ ранее, но я неправильно прочитал ваш ответ. Я не думаю об in инструкции. Спасибо.

2. @double-beep Спасибо за ваше предложение, это был мой первый ответ, поэтому я не знал об этом.