python - 在我的用户在我的输入提示上按下回车后,我如何重复要求输入
问题描述
您好,所以我无法保持我的应用程序打开并重复我的输入功能并从用户本身获取输入。这是我的代码
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() 获取输入,但我不知道怎么做,有人可以帮忙吗?
解决方案
这里有一些东西。我添加了一些命令,例如DIR
or 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")
推荐阅读
- reactjs - Gatsby.js (React) - gatsby-browser.js 中的 graphql 查询
- python-3.x - Python3:shap 树解释器:在“array_dealloc”中忽略了异常
- swiftui - SwiftUI iOS 14 | 在 HStack 中自动展开文本框和内容
- typescript - 打字稿回调联合参数重载错误“此重载签名与其实现签名不兼容。”
- c# - 获取 ConcurrentDictionary 中的 ConcurrentBag 项数
- node.js - date-fns-tz 在 IE11 上工作,是否有任何替代 date-time-format-timezone polyfill 的方法?
- apache-beam - 是否可以使用 Apache Beam JdbcIO.Write 获取生成的密钥?
- python - Python - 如何将所有行分组为一,保留所有列
- r - 混淆矩阵中的“具有相同水平的因素”
- c# - 如何使用 HttpClient 处理自定义令牌身份验证