0

I need to program in py 2.7 a function that
when active, it closes all connections to the internet of a client (It is a server-client socket connection)

Because I cannot just make the client turn off the internet (Because then we won't be able to communicate with him)
I thought to run a thread. That when active (When the server sends to the client "close_internet") the thread runs a while true function that closes all the browsers (and thus "closing" its internet connection). I will have a list of known browsers (not all) that the thread will actively close. This line of code closes any process by name:

import os
import threading


def close_internet():
    while 1:
        try:
            os.system('taskkill /f /im MicrosoftEdge.exe')
        except:
            pass

threading.Thread(target=close_internet, args=()).start()

When I run this code, it does work, closing explorer when I open it (Explorer just for testing, you can change to chrome.exe or firefox.exe)
However, in the console it prints some scary errors, all the time:

ERROR: The process "MicrosoftEdge.exe" not found.
ERROR: The process "MicrosoftEdge.exe" not found.
ERROR: The process "MicrosoftEdge.exe" not found.
ERROR: The process "MicrosoftEdge.exe" not found.
ERROR: The process "MicrosoftEdge.exe" not found.
ERROR: The process "MicrosoftEdge.exe" not found.

What can I do? I only need this program to work in the background, without the user noticing with those errors. The errors appear (not surprisingly) when I don't have explorer open.
When I do have it open, it works fine and prints:

ERROR: The process "MicrosoftEdge.exe" not found.
ERROR: The process "MicrosoftEdge.exe" not found.
SUCCESS: The process "MicrosoftEdge.exe" with PID 10808 has been terminated. # <-- this line
ERROR: The process "MicrosoftEdge.exe" not found.

The function is programmed on the client-side!

How can I fix it?
And secondly, is this the right way to close a process by its name? is it efficient? or is there a more efficient way to close a process (Maybe using its PID makes it faster...) I'd like to hear your advice.

Thanks!

CodeCop
  • 1
  • 2
  • 15
  • 37

1 Answers1

0

Try using the subprocess module. I don't think you need Threading for this task.

Here is the code i use to open windows explorer and highlight a file.

subprocess.Popen(r'explorer /select, %s%s'%(self.cwd, ofile))

It should be easy to modify for your task. Also that code is assuming that Edge is open and the name is MicrosoftEdge.exe is the process name. Assume nothing and see if you can get a list of running processes using python, scan through that list and check if the application you want to close is already open. Here is a link with some information on getting the list of processes running on windows.

Scott Paterson
  • 392
  • 2
  • 17