简体   繁体   English

Python:Shell 错误在错误处理期间保存在文本文件中

[英]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.我是 python 的新手,我没有太多编程经验。 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.我正在尝试使用 subprocess 和 os 模块在 python 中创建一个脚本,这些模块在执行时将打开命令提示符并询问用户 WiFi 的名称,然后脚本将创建一个文本文件,它将在其中保存配置文件 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.通过将配置文件 output 保存在文本文件中,它可以完美地工作,但问题是,当用户输入无效数据时,它会将错误本身保存在我想在命令提示符中显示的文本文件中。

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()

You forgot to add double quotes here:您忘记在此处添加双引号

if output_content == 'Profile "' + profile_name + '" is not found on the system.':如果 output_content == 'Profile "' + profile_name + '"在系统上找不到。':

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")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM