首页 > 解决方案 > 在我的用户在我的输入提示上按下回车后,我如何重复要求输入

问题描述

您好,所以我无法保持我的应用程序打开并重复我的输入功能并从用户本身获取输入。这是我的代码

import socket
import time
import sys

HOSTNAME = socket.gethostname()
CREDITS = "Developed by SnoDev"

print("Welcome " + HOSTNAME + "!")
time.sleep(1)
def cmd():
   input("Command Bar: ")
cmd()

我想从函数 cmd() 获取输入,但我不知道怎么做,有人可以帮忙吗?

标签: pythonpycharm

解决方案


这里有一些东西。我添加了一些命令,例如DIRor ping。此外,递归也不好。虽然循环更好。

import socket
import time
import os
import platform    # For getting the operating system name
import subprocess  # For executing a shell command

def ping(host,num="4"):
    """
    Returns True if host (str) responds to a ping request.
    Remember that a host may not respond to a ping (ICMP) request even if the host name is valid.
    """

    # Option for the number of packets as a function of
    param = '-n' if platform.system().lower()=='windows' else '-c'

    # Building the command. Ex: "ping -c 1 google.com"
    command = ['ping', param, num, host]

    return subprocess.call(command) == 0

HOSTNAME = socket.gethostname()
CREDITS = "Developed by SnoDev"

print("Welcome " + HOSTNAME + "!")
time.sleep(1)
while True:
    var1=input("Command Bar: ")
    if "ping" in var1.lower():
        var2=var1.lower().split()
        
        if len(var2)==1:
            print("Usage: ping [-number]\n\nOptions:\n\t-number\t\tPing the host for specified number of times.\n")
        elif len(var2)==3:
            print(ping(var2[1],var2[2][1:]))
            #print(ping(var2[1],var2[2]))
        else:
            print(ping(var2[1]))
        
    elif var1.lower()=="exit":
        break
    elif "dir" in var1.lower():
        var3=var1.lower().split()
        if len(var3)==1:
            print("Usage: DIR [-path]\n\nOptions:\n\t-path\t\tList all folders and files inside the specified directory.\n")
        else:
            x=os.listdir(var3[1])
            print("\nDirectories and files found: \n")

            for i in x:
                print(i)
            print("\n")
        
    elif var1=="":
        pass
    
    else:
        print(f"Error: {var1} is not recognized as a command.\n")
        


推荐阅读