【问题标题】:How to implement a key check definition如何实现密钥检查定义
【发布时间】:2020-11-21 20:05:46
【问题描述】:

所以基本上我正在尝试编写一个在您提供正确密钥后执行某些操作的程序。

所以,首先我在从输入中获取 Key 后调用 Keycheck(Key),然后它会通过带有键的文件(每个键都在一个新行 ("\n") 中)进行刺激。

def Keycheck(Key):

    KeyFile = open("keys.key","r", encoding='utf-8')

    for line in KeyFile:
        line1 = line.strip()
        fields = line1.split("\n")
        linekey = fields[0]
  
   
        if Key in linekey:
            
            Keypass = "true"
            
    
        elif Key != linekey:

            continue

这很好,但我遇到的问题是将 Keypass 变量传递给主程序,我尝试阅读有关 Kwargs 但我无法理解它。

所以我的问题是如何将关键字变量从“def Keycheck(Key)”传递到“主程序”,如果这不可能,是否有任何其他方法可以从已存储的密钥中实现密钥检查在文件中?

编辑: 我的意思是主程序

def func():
def func2():
Keycheck(Key):

main program:
Key = input("")
Keycheck(Key)
if Keypass == "true": 
   func()
   func2()
else:
break

只是关于我希望程序如何工作的提示:

  1. 它从输入中获取密钥
  2. 它调用 Keycheck(Key)(或检查密钥是否有效)
  3. 如果密钥在来自 Keycheck(key) 的文件中,它会继续程序 如果它不包含密钥文件中的密钥,则只需 print("wrong key try again") 或类似的内容,然后重试所有内容

【问题讨论】:

  • "我遇到的问题是将 Keypass 变量传递给主程序" 什么主程序?请显示与您的问题相关的所有相关代码,包括与您用英语描述的 3 个步骤相关的代码。
  • 我猜你只需要了解我们所说的从函数中“返回”一个值。此外,您应该了解布尔值。使用布尔值True,而不是字符串"true"
  • stackoverflow.com/questions/37088457/… 也许这个问题可以作为你需要做的一个例子。

标签: python python-3.x


【解决方案1】:

正如@Code-Apprentice 提到的,如果您找到密钥,只需返回 True。否则,return False 循环结束。

def Keycheck(Key):

    KeyFile = open("keys.key","r", encoding='utf-8')

    for line in KeyFile:
        line1 = line.strip()
        fields = line1.split("\n")
        linekey = fields[0]
  
        if Key in linekey:            
            return True    # found key, return True
        
    return False    # loop is done, key not found  


# main program
if Keycheck('Key123'):
    print('Found Key')
else:
    print('Key Not Found')

【讨论】:

  • 您好,感谢您的回答,我在“返回真”时遇到无效的语法,有什么我遗漏的吗?我可能需要导入一些东西吗?编辑:啊应该是return而不是return hehe,
  • 对不起-我的错字:(
  • 哈哈,无论如何谢谢你,顺便说一句,它没有遍历整个文件,只检查了第一行,所以我添加了这个` if Key in linekey: return True # found key, return True elif Key not in linekey: continue else: return False # loop is done, key not found ` 现在一切正常!!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-25
  • 2015-08-07
  • 2018-06-09
  • 2011-05-02
  • 1970-01-01
相关资源
最近更新 更多