subprocess.Popen()打开很晚,破坏了程序

时间:2016-03-19 15:44:43

标签: python python-3.x python-3.4

我正在使用Python 3.4,并且对于一个令用户烦恼的错误感到困惑。这是代码:

# @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() + ']: ')

但是,如果您执行ping google.com命令或任何ping,它会显示输入,然后运行subprocess.Popen()命令。因此,如果用户在执行程序期间点击某个键,它将尝试运行该键。尝试它是理解的最佳方式。

注意:运行ping命令后按 ENTER

1 个答案:

答案 0 :(得分:0)

我没有要测试的Windows主机,但我猜你的问题就在这里:

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

由于您没有rstrip(),因此它与''不匹配,因为它的返回字符仍然在最后。所以你得到一个虚假的尝试来运行一个命令。

如果您遵循DRY原则(不要重复自己),则不会发生此错误。我会做一个:

CommandToEvaluate = CommandToEvaluate.strip()

在你的功能开始。然后你可以删除所有无花果条带。