ATN
ATN

Reputation: 123

Is there a way to end a process or program halfway through a python script?

I am trying to autonomously connect to several RealVNC Connections using the script below. The only issue I have is when the VNC client is ran via the following line:

subprocess.run(r'C:\Program Files\RealVNC\VNC Viewer\vncviewer.exe -useaddressbook ' + '"' + name_of_host + '"')

It waits for the user to close the newly opened VNC window before moving onto the next step in the code.

Is there a way for me to make it so it doesn't wait for the window to close before it continues the code?

Or is there a way I could close the VNC connection after a set amount of time within the code so the code continues?

test.py

import subprocess
import time

# Arrays
hosts = []
log = []
phrases = ["No such host is known", "VNC Server is not currently listening for Cloud connections", "Authentication successful", "Too many security failures"]


# Reading Hosts File
hosts_file = open('hostnames.txt', 'r')
read_hosts_file = hosts_file.readlines()
hosts_file.close()
hosts_count = 0


# Adding Hosts From File Into Array
for line in read_hosts_file:
    hosts_count += 1
    hosts.append(line.strip())


# Prints Amount Of Hosts Found From File
print("------------------------------------------------------")
print(hosts_count, "hosts found in file!")
print("------------------------------------------------------")
print('\n')


# Attempts To Connect To Each Host
for name_of_host in hosts:
    print("------------------------------------------------------")
    print("Attempting to connect to", name_of_host)
    time.sleep(1)
    subprocess.run(r'C:\Program Files\RealVNC\VNC Viewer\vncviewer.exe -useaddressbook ' + '"' + name_of_host + '"')
    time.sleep(3)
    print("Attempting to read log file...")
    log_file = open(r'C:\Users\613243931\AppData\Local\RealVNC\vncviewer.log', 'r')
    read_log_file = log_file.readlines()
    log_file.close()
    for line in read_log_file:
        for phrase in phrases:
            if phrase in line:
                log.insert(0, line)
                break
    print("Phrases found in log file:")
    time.sleep(1)
    print(log)
    print("------------------------------------------------------")
    print('\n')
    log = []
    time.sleep(3)


# Lets User Know Script Has Finished
print("------------------------------------------------------")
print("--------------END OF CONNECTION ATTEMPTS--------------")
print("------------------------------------------------------")

Upvotes: 0

Views: 158

Answers (1)

Almog-at-Nailo
Almog-at-Nailo

Reputation: 1182

You can use timeout=<seconds to timeout after> in your subprocess.run call. This would raise a TimeoutExpired Exception so you should also use try and except

Upvotes: 2

Related Questions