【问题标题】:How do I detect when a user hits enter as input()如何检测用户何时按输入作为输入()
【发布时间】:2017-08-01 16:21:10
【问题描述】:

我正在编写的脚本的一部分处理获取一个文件以传递到我的终端应用程序的其他方面。这是我的代码:

def get_file():

custom_data_folder = input("Name of custom data directory - " +
                           "Hit ENTER to use default: ")
file_name = input("File name: ")
default_path = os.path.abspath(os.path.join('data', file_name))
custom_path = os.path.abspath(os.path.join(custom_data_folder, file_name))

if custom_data_folder == '\n':
    return(default_path if os.path.exists(default_path) is True 
                     else "The file or path does not exist.")
else:
    return(custom_path if os.path.exists(custom_path) is True 
                       else "The file or path does not exist.")

我的脚本假定文件位于名为“data”的目录中,但我想提供一个选项,即输入文件可能所在的自定义目录。

当我尝试使用“/n”换行符来检测用户是否按回车时,问题就出现了。它似乎只是返回工作目录及其中的文件,而不是我想要的“数据”目录及其文件。

如何检测用户是否按下回车键?

我在 linux/ubuntu 中工作。仅针对该平台的解决方案很好,但如果可能的话,我更喜欢多平台解决方案。

【问题讨论】:

    标签: python python-3.x terminal


    【解决方案1】:

    如果用户在没有输入任何内容的情况下按下回车,它将返回一个空字符串。您可以将 if 语句更改为以下内容。

    if custom_data_folder == '':
    

    【讨论】:

      猜你喜欢
      • 2020-12-21
      • 1970-01-01
      • 2012-07-07
      • 2013-12-13
      • 2017-09-12
      • 2019-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多