【问题标题】:Taking a user input in python using batch file使用批处理文件在 python 中获取用户输入
【发布时间】:2020-08-07 05:15:37
【问题描述】:

我有一个 new.py 文件,我用它来自动化一个过程。我想在脚本中添加一个用户输入,它将被保存为一个变量。

username = input("Please enter username:")

while username not in users:
    print("Incorrect Username")
    username = input("Please enter username:")

print("Username Accepted")

但是当我使用如下批处理文件执行我的 new.py 文件时:

cmd /c C:\ProgramData\Anaconda3\condabin\conda.bat run "C:\ProgramData\Anaconda3\python.exe" 
"C:\Users\mbeig\Downloads\new.py"
pause

我收到一条错误消息:

Please enter username:
Traceback (most recent call last):
  File "C:\Users\mbeig\Downloads\new.py", line 39, in <module>
    username = input("Please enter username:")
EOFError: EOF when reading a line

我希望用户在命令行中输入可用作脚本中的变量的输入。 谢谢!

【问题讨论】:

  • 您的问题与批处理文件无关,因此我删除了 [batch-file] 标签。如果它与您的批处理文件有关,请在您提供的单行命令中说明您认为问题出在哪里。如果您的问题是关于如何在批处理文件中请求用户输入并将该输入保存在变量中,那么 [python] 和 [automation] 标记将无关紧要,应该与python 代码和错误消息文本。但是我们可以清楚地看到您的错误是 python 生成的,而不是批处理文件或 [cmd] 相关的。

标签: python cmd automation user-input


【解决方案1】:

将程序的逻辑重新安排为:

users = ['batman', 'robin', 'superman']

while True:
    username = input("Please enter username:")
    if username in users:
        break
    else:
        print("Incorrect username")

【讨论】:

  • 您好 Jan,感谢您的回复。问题不在于 python 代码,我需要在命令行中找到用户输入的方法。我希望这是有道理的。
【解决方案2】:

如果你使用的是 python 3.8,你可以使用 walrus operator 来缩短你的代码

users = ['indianajones', 'wonderwoman', 'flash']

while (username := input("Please enter username:")) not in users:
    print("Incorrect username")
    
print(username)
# Other statements

【讨论】:

  • 您好 bigbounty,感谢您的回复。我需要在命令行中找到一种用户输入方式。在这里缩短代码不会有什么不同,但感谢您的建议。
  • @M.SameerBeig 代码从命令行获取输入。请在 python 3.8 中运行一次
  • 嗨 bigbounty,我尝试使用您建议的代码,但这会为用户名创建一个布尔值。我正在尝试使用用户的输入向用户名添加一个字符串。
猜你喜欢
  • 2015-04-14
  • 1970-01-01
  • 1970-01-01
  • 2015-10-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多