如何在输入行中输入文本:如何在命令行上询问用户输入,同时提供用户可以编辑或删除的"默认"答案?

ikh*_*unt 16 python python-3.x

我正在创建一个Python脚本,要求从命令行输入.用户可以编辑文件的一部分.我可以要求提供新信息并在文件中覆盖它,没问题.但我宁愿将文件的编辑部分放在命令行中,因此不必完全输入.这可能吗?

文件:

1|This file
2|is not empty
Run Code Online (Sandbox Code Playgroud)

例:

>>>edit line 2
Fetching line 2
Edit the line then hit enter
>>>is not empty                  #This is written here by the script, not by the user
Run Code Online (Sandbox Code Playgroud)

然后可以改为

>>>is not full either
Edited file
Run Code Online (Sandbox Code Playgroud)

该文件已更改为:

1|This file
2|is not full either
Run Code Online (Sandbox Code Playgroud)

我希望我很清楚我想要完成什么.

据说这个问题在一定程度上回答了我的问题.当我运行Linux时,它会这样做readline.但是,我不是.我正在使用Windows而我没有使用readline.我想只使用标准库.
该问题还提供了Windows的答案.但是,我得到一个 ImportErrorwin32console,这可能是因为提到的问题不是Python3.4,但我是.另外,我想知道这是否可以使用标准库,而不是外部库.

mbd*_*vpl 6

不幸的是,我不知道input()标准库中是否有默认值。

有一个外部解决方案 -win32console本答案所述使用。但是,据我所知,它有两个陷阱。首先,导入捆绑在一个包pywin32 中。所以你会使用pip install pywin32,除非它不起作用,因为第二个陷阱:关于 pypi 包的信息已经过时,它说包与 Python 3.4 不兼容......

但事实上,它可以工作!您应该遵循 pypi 项目页面(即https://sourceforge.net/projects/pywin32/files/pywin32/)上可见的“下载 URL”并安装最新版本。我刚刚为 Py3.4 安装了 build 219,因为我自己也使用这个 Python 版本。在页面上为 32 位和 64 位 Windows 的多个 Python 版本提供了安装程序。

另外,我已经调整了上面链接的 SO 答案中的代码以在 Python 3 中工作:

import win32console

_stdin = win32console.GetStdHandle(win32console.STD_INPUT_HANDLE)

def input_def(prompt, default=''):
    keys = []
    for c in str(default):
        evt = win32console.PyINPUT_RECORDType(win32console.KEY_EVENT)
        evt.Char = c
        evt.RepeatCount = 1
        evt.KeyDown = True
        keys.append(evt)

    _stdin.WriteConsoleInput(keys)
    return input(prompt)

if __name__ == '__main__':
    name = input_def('Folder name: ', 'it works!!!')
    print()
    print(name)
Run Code Online (Sandbox Code Playgroud)

这适用于我的 Windows 机器......如果这不适用于你的机器,你能提供错误信息吗?


Ign*_*ela -1

您应该只有 2 个变量:一个用于标准字符串,一个用于用户自行更改的字符串。喜欢:

str1 = 'String that is standard'
str2 = str1 #it usually will be standard string
usr = input('your text goes here')
if len(usr) != 0:
    str2 = usr
#and here goes code for writing string into file
Run Code Online (Sandbox Code Playgroud)