我正在尝试用Python编写一个具有特殊性的开关。
OperativeSystems = {"nt": os.system("cls"), "posix": os.system("clear")}
try:
OperativeSystems[os.name]
except:
print("Can not clean the screen in the current operating system")
我想执行命令清除控制台,但我的程序执行“cls”和“clear”。这是我的问题。
谢谢。
答案 0 :(得分:4)
OperativeSystems = {"nt": os.system("cls"), "posix": os.system("clear")}
在运行时声明字典时,您正在调用os.system。你可能想要这样做
OperativeSystems = {"nt": lambda: os.system("cls"), "posix": lambda: os.system("clear")}
OperativeSystems["nt"]()
现在进行查找会返回一个lambda(快捷方式函数),调用时会调用os.system
答案 1 :(得分:1)
您正在第一行执行两个os.system()
调用,实际存储在字典中的是os.system()
调用的返回值。要么只将参数存储到字典中的os.system()
并在os.system(OperativeSystems[os.name])
内调用try
,要么将字典值变为lambdas。
答案 2 :(得分:-1)
## First solution
class OperatingSystem:
OSDict = {
"nt" : NTOs,
"posix" : PosixOs
}
@staticmethod
def create_os(self,name):
return self.OSDict[name]()
class NTos:
def clear_screen(self):
os.system("cls")
class PosixOs:
def clear_screen(self):
os.system("clear")
OperatingSystem.create_os("nt").clear_screen()
OperatingSystem.create_os("posix").clear_screen()
## Second solution
def clear(os_name):
if os_name == "nt":
command = "cls"
if os_name == "posix":
command = "clear"
os.system(command)
clear("nt")
clear("posix")
## Third solution
OperatingSystems = {
"nt" : "cls",
"posix" : "clear"
}
os.system(OpeartingSystems("nt"))
os.system(OpeartingSystems("posix"))
## Fourth solution
# This is screaming for polymorphisme (solution #1)
OperatingSystems = {
"nt" : {"clear_screen":lambda : os.system("cls")}
"posix" : {"clear_screen":lambda : os.system("clear")}
}
OperatingSystems["nt"].clear_screen()