子流程.Popen()开盘晚,打乱了节目

2024-10-03 21:34:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用的是python3.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。你知道吗


Tags: orthetotrueisuppersubprocessprint
1条回答
网友
1楼 · 发布于 2024-10-03 21:34:17

我没有要测试的windows主机,但我猜您的问题在于:

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

因为没有rstrip(),所以它与''不匹配,因为它的返回字符仍然在末尾。所以你得到了运行命令的虚假尝试。你知道吗

如果你遵循干燥原则(不要重复你自己),这个错误就不会发生。我会做一个:

CommandToEvaluate = CommandToEvaluate.strip()

在你的功能开始的时候。然后你可以去掉所有的多余的胡椒条。你知道吗

相关问题 更多 >