Reputation: 1
In my Python project, there is a main.py which is the entrance of the application and uses Tkinter to design UI. There are some other .py files which will be called and run from main.py. One of the .py files is process_pcap.py which imports Pyshark API to call tshark to process a .pcap log. For convenience to distribute the application, I use Pyinstaller to convert the main.py to main.exe.
When I run main.exe to open the application UI and then select to execute process_pcap (via calling class PCAP defined in the process_pcap.py), it pops up a 'tshark' console window. This is not what I want. I want to prevent the tshark console window from popping up.
But when I directly run python main.py
to execute process_pcap, the tshark console window will not pop up.
I have tried some ways to suppress the tshark console window, but none of them works.
pyinstaller --onefile --windowed main.py
pyinstaller --onefile --noconsole main.py
import pyshark
import subprocess
import sys
class PCAP:
def __init__(self, pcap_file, redirector_stdout):
self.pcap_file = pcap_file
self.redirector_stdout = redirector_stdout
self.suppress_console_window()
def suppress_console_window(self):
if sys.platform.startswith('win'):
# Save the original subprocess.Popen and subprocess.check_output
original_popen = subprocess.Popen
original_check_output = subprocess.check_output
# Define a new Popen that suppresses the console window
def new_popen(*args, **kwargs):
if 'startupinfo' not in kwargs:
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
kwargs['startupinfo'] = startupinfo
# Add CREATE_NO_WINDOW as well for extra suppression
if 'creationflags' not in kwargs:
kwargs['creationflags'] = subprocess.CREATE_NO_WINDOW
kwargs['shell'] = True # Ensure shell execution
return original_popen(*args, **kwargs)
# Define a new check_output that suppresses the console window
def new_check_output(*args, **kwargs):
if 'startupinfo' not in kwargs:
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
kwargs['startupinfo'] = startupinfo
if 'creationflags' not in kwargs:
kwargs['creationflags'] = subprocess.CREATE_NO_WINDOW
kwargs['shell'] = True
return original_check_output(*args, **kwargs)
# Override subprocess.Popen and subprocess.check_output with the new versions
subprocess.Popen = new_popen
subprocess.check_output = new_check_output
def execute_code(self):
# Process the pcap file using Pyshark without showing the tshark console
cap = pyshark.FileCapture(self.pcap_file, display_filter='sip')
for packet in cap:
self.redirector_stdout.write(f"packet = {packet}\n")
if 'sip' in packet:
sip_layer = packet['sip']
self.redirector_stdout.write(f"sip_layer = {sip_layer}\n")
if __name__ == "__main__":
# Example usage when running this script directly
pcap = PCAP('sample.pcap', sys.stdout)
pcap.execute_code()
How to suppress the tshark console window for my case above?
Upvotes: 0
Views: 38