2016-03-19 7 views
0

Ich benutze Python 3.4 und bin verwirrt über einen Fehler, der für einen Benutzer ärgerlich ist. Hier ist der Code:subprocess.Popen() Eröffnung spät, Programm zu unterbrechen

# @Author: Aanand Kainth 
# @Date C: XX-XX-XXXX 
# @Purpos: A more feature-rich command line for Windows Machines 

# The following is a list of modules required for the program to run properly. 
import getpass   # GetPass is a module that serves as a backbone for user accounts 
import os    # OS is a module that allows usage of operating system dependent functionality 
import signal   # Signal is a module that allows helps with sending commands to the hardware  
import socket   # Socket is a module that allows access to the BSD socket interface 
import subprocess  # Subprocess is a module that allows the program to run system commands 
import sys    # Sys is a module that allows access to some variables used or maintained by the interpreter 
import time    # Time is a module that allows access to variables that have to with time. 
import urllib.request # UrlLib is a module that allows access to online servers and files 

# The following is a list of variables that are required for the program to run properly 
CommandToExecute = input('[' + getpass.getuser().upper().replace(' ', '-') + '@' + socket.gethostname().upper() + ']: ') 
ContinueWithInst = False 
# The following are functions required for the program to run properly 
def EvaluateInstallation(CommandToEvaluate): 
    CommandToEvaluate = CommandToEvaluate[8:] 
    if CommandToEvaluate.upper() == 'FIREFOX': 
     try: 
      try: 
       FirefoxInstaller = urllib.request.urlopen('https://ftp.mozilla.org/pub/firefox/releases/46.0b1/win64/en-US/Firefox%20Setup%2046.0b1.exe') 
       ContinueWithInst = input('The Firefox Installer Is ' + FirefoxInstaller.info()['Content-Length'].split('L')[0] + ' Bytes Big. Proceed with installation [Y|N]: ') 
       if ContinueWithInst.upper() == 'YES' or ContinueWithInst.upper() == 'Y' or ContinueWithInst.upper() == '': 
        urllib.request.urlretrieve('https://ftp.mozilla.org/pub/firefox/releases/46.0b1/win64/en-US/Firefox%20Setup%2046.0b1.exe', 'C:\\Users\\' + getpass.getuser() + '\Application Installation Programs\Firefox 46.0 Installer [64 Bit].exe') 
        print('Operation completed. File is @ C:\\Users\ ' + '\b' + getpass.getuser() + '\Application Installation Programs\Firefox 46.0 Installer [64 Bit]') 
        ContinueWithInst = input('Do you want MyCMD to run this program now [Y|N]: ') 
        if ContinueWithInst.upper() == 'YES' or ContinueWithInst.upper() == 'Y' or ContinueWithInst.upper() == '': 
         subprocess.call('C:\\Users\\' + getpass.getuser() + '\Application Installation Programs\Firefox 46.0 Installer [64 Bit].exe') 
       elif CommandToEvaluate.upper() == 'NO' or CommandToEvaluate.upper() == 'N': 
        print('Operation canceled successfully. Returning to MyCMD.') 
       else: 
        print('Invalid Answer: Operation canceled. Returning to MyCMD.') 
      except EOFError: 
       time.sleep(0.1) 
     except KeyboardInterrupt: 
      print('\nOperation canceled successfully. Returning to MyCMD.') 
    elif CommandToEvaluate.upper() == 'NOTEPAD++': 
     try: 
      try: 
       NotepadInstaller = urllib.request.urlopen('https://notepad-plus-plus.org/repository/6.x/6.9/npp.6.9.Installer.exe') 
       ContinueWithInst = input('The Notepad++ Installer Is ' + NotepadInstaller.info()['Content-Length'].split('L')[0] + ' Bytes Big. Proceed with installation [Y|N]: ') 
       if ContinueWithInst.upper() == 'YES' or ContinueWithInst.upper() == 'Y' or ContinueWithInst.upper() == '': 
        urllib.request.urlretrieve('https://notepad-plus-plus.org/repository/6.x/6.9/npp.6.9.Installer.exe', 'C:\\\\Users\\' + getpass.getuser() + '\\Application Installation Programs\\Notepad++ Installer [32 Bit].exe') 
        print('Operation completed. File is @ C:\\\\Users\\' + getpass.getuser() + 'Application Installation Programs\\Notepad++ Installer [32 Bit].exe') 
        ContinueWithInst = input('Do you want MyCMD to run this program now [Y|N]: ') 
        if ContinueWithInst.upper() == 'YES' or ContinueWithInst.upper() == 'Y' or ContinueWithInst.upper() == '': 
         try: 
          subprocess.call('C:\\Users\\' + getpass.getuser() + r'\Application Installation Programs\Notepad++ Installer [32 Bit].exe') 
         except OSError: 
          print('Fatal Error: MyCMD does not have sufficient priveleges to run the requested operation.') 
       elif CommandToEvaluate.upper() == 'NO' or CommandToEvaluate.upper() == 'N': 
        print('Operation canceled successfully. Returning to MyCMD.') 
       else: 
        print('Invalid Answer: Operation canceled. Returning to MyCMD.') 
      except EOFError: 
       time.sleep(0.1) 
     except KeyboardInterrupt: 
       print('\nOperation canceled successfully. Returning to MyCMD.') 
    else: 
     print('User Error: MyCMD was unable to find and install the requested program.') 
def EvaluateProgramReque(CommandToEvaluate): 
    if CommandToEvaluate.rstrip().upper() == 'CD': 
     print(os.getcwd()) 
    elif CommandToEvaluate.upper().startswith('CD ') == True: 
     try: 
      os.chdir(CommandToEvaluate.rstrip().lstrip()[3:]) 
      print('MyCMD has successfully navigated into ' + CommandToEvaluate.rstrip().lstrip()[3:] + '.') 
     except FileNotFoundError: 
      print('MyCMD was unable to locate the directory ' + CommandToEvaluate.rstrip().lstrip()[3:] + '!') 
    elif CommandToEvaluate.rstrip().upper() == 'LS' or CommandToEvaluate.rstrip().upper() == 'DIR': 
     print(subprocess.check_output('DIR', shell = True).decode('utf-8')) 
    elif CommandToEvaluate.upper().startswith('LS ') == True or CommandToEvaluate.upper().startswith('DIR ') == True: 
     try: 
      print(subprocess.check_output(['DIR', CommandToEvaluate[3:].replace('\\\\', '\\')], shell = True).decode('utf-8')) 
     except FileNotFoundError: 
      print('MyCMD was unable to locate the specified folder!') 
    elif CommandToEvaluate.upper().rstrip() == 'CLEAR': 
     subprocess.call('CLS', shell = True) 
    elif CommandToEvaluate.upper().rstrip() == 'CLS': 
     subprocess.call('CLS', shell = True) 
    elif CommandToEvaluate.upper().rstrip() == 'RESTART': 
     subprocess.call('CLS', shell = True) 
     subprocess.call('C:\\Users\Aanand Kainth\Python Projects\MyCMD Source Code\MyCMD Graphical Interface.py', shell = True) 
     sys.exit() 
    elif CommandToEvaluate.upper().startswith('PING ') == True: 
     print('This may take a while to display, depending on your internet connection, and various other variables.') 
     if CommandToEvaluate.lstrip().rstrip()[5:].upper() == 'CNN.COM': 
      print('Fatal Error: The server at CNN.COM is set up to deny PING requests. Pinging GOOGLE.COM instead.') 
      subprocess.Popen(['PING', 'GOOGLE.COM']) 
     else: 
      try: 
       subprocess.Popen(['PING', CommandToEvaluate.lstrip().rstrip()[5:]]) 
      except subprocess.CalledProcessError: 
       print('Fatal Error: The server @ ' + CommandToEvaluate.lstrip().rstrip()[5:].upper() + ' was not able to be contacted. This may be a result of IPv6 incompatibility.') 
    elif CommandToEvaluate.upper().startswith('INSTALL ') == True: 
     EvaluateInstallation(CommandToEvaluate) 
    elif CommandToEvaluate.upper() == '': 
     pass 
    else: 
     try: 
      print(subprocess.check_output(CommandToEvaluate.replace('\\\\', '\\').split(' '), shell = True).decode('utf-8')) 
     except FileNotFoundError: 
      print('User Error: MyCMD was unable to find the file you requested.') 
     except PermissionError: 
      print('Fatal Error: Windows has denied access to this folder or file for your account.') 
     except subprocess.CalledProcessError: 
      print('An error occured while the process you called was executing.') 
# The following is the actual program in which the above arguments are run 
os.chdir('C:\\Users\\' + getpass.getuser()) 
while CommandToExecute.upper() != 'EXIT' and CommandToExecute.upper() != 'QUIT': 
    EvaluateProgramReque(CommandToExecute) 
    CommandToExecute = input('[' + getpass.getuser().upper().replace(' ', '-') + '@' + socket.gethostname().upper() + ']: ') 

Wenn Sie jedoch tun, um die ping google.com commmand oder jede ping, zeigt sie die Eingabe, dann läuft die subprocess.Popen() Befehl. Wenn der Benutzer also während der Ausführung des Programms eine Taste drückt, wird er versuchen, diese auszuführen. Es zu versuchen, ist der beste Weg zu verstehen.

Hinweis: Drücken Sie nach der Ausführung des Befehls ping auf ENTER.

Antwort

0

ich testen keinen Windows-Host auf, aber ich bin hier, Ihr Problem zu erraten:

elif CommandToEvaluate.upper() == '': 
    pass 

Da Sie keine rstrip() haben, es passt so nicht '' weil es hat den Return-Charakter noch am Ende. Sie erhalten also einen falschen Versuch, einen Befehl auszuführen.

Dieser Fehler wäre nicht aufgetreten, wenn Sie dem DRY-Prinzip folgen (Do not Repeat Yourself). Ich würde a:

CommandToEvaluate = CommandToEvaluate.strip() 

am Anfang Ihrer Funktion tun. Dann können Sie alle durchgehend gespickten Fremdstreifen entfernen.

+1

's.lstrip(). Rstrip()' ist äquivalent zu 's.strip()', aber letzteres ist kürzer und imho klarer;) – marcelm

+0

Einverstanden. Ich replizierte seine Logik und vergaß zu vereinfachen. Vielen Dank. Antwort bearbeitet. –

+0

Das behebt das Problem nicht, was ich am Ende getan habe, war das Hinzufügen eines 'time.sleep (5)' zum 'ping' Befehl. Es funktioniert gut. –