Noamaan Mulla
Noamaan Mulla

Reputation: 77

Python: Shell error gets saved in text file during error handling

I am new to python and I don't have much experience in programming. I am trying to create a script in python using the subprocess and os modules which, when executed, will open the command prompt and ask the user for the name of the WiFi and then the script will create a text file in which it will save the profile output. It is working perfectly by saving the profile output in a text file but the problem is, when the user enters invalid data, it saves the error itself in the text file which I want to display in the command prompt.

import subprocess
import os


def get_wifi_name():
    os.system('color A')
    os.system('cls')
    profile = input("\n[-]Enter name of previously connected WiFi: ")
    output = subprocess.getoutput('netsh wlan show profile ' + profile + ' key=clear')
    return profile, output


profile_name, output_content = get_wifi_name()

if output_content == "Profile " + profile_name + " is not found on the system.":
    os.system("\nPlease enter valid WiFi Network")
else:
    f = open('WiFi.txt', 'w')
    f.write(output_content)
    f.close()

Upvotes: 2

Views: 96

Answers (1)

Maamoun
Maamoun

Reputation: 81

You forgot to add double quotes here:

if output_content == 'Profile "' + profile_name + '" is not found on the system.':

This should work:

import subprocess
import os

def get_wifi_name():
    os.system('color A')
    os.system('cls')
    profile = input("\n[-]Enter name of previously connected WiFi: ")
    output = subprocess.getoutput('netsh wlan show profile ' + profile + ' key=clear')
    return profile, output


profile_name, output_content = get_wifi_name()

if output_content == 'Profile "' + profile_name + '" is not found on the system.':
    print("\nPlease a enter valid WiFi Network")
    input("\npress <enter> to exit")
else:
    f = open('WiFi.txt', 'w')
    f.write(output_content)
    f.close()
    print("\nFile saved successfully")
    input("\npress <enter> to exit")

Upvotes: 1

Related Questions