我正在创建一个要求从命令行输入的 Python 脚本。用户将能够编辑文件的一部分。我可以请求新信息并在文件中覆盖它,没问题。但我宁愿将文件的待编辑部分放在命令行中,这样就不必完全输入。这可能吗?
文件:
1|This file
2|is not empty
例子:
>>>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
然后可以更改为
>>>is not full either
Edited file
之后文件变成了:
1|This file
2|is not full either
我希望大家清楚我要完成的任务。
This问题已经说到回答我的问题了,确实在一定程度上。当我使用 readline
运行 Linux 时会发生这种情况。然而,我不是。我正在使用 Windows 而不是使用 readline
。我只想使用标准库。
该问题还提供了 Windows 的答案。但是,我在 win32console
中得到了一个 ImportError
,这可能是因为提到的问题不是关于 Python3.4,但我的是。
另外,我想知道这是否可能使用标准库,而不是外部库。
最佳答案
不幸的是,我不知道标准库中是否提供具有默认值的input()
。
有一个外部解决方案 - 使用 win32console
,如 this answer 中所述.但是,据我所知,它有两个缺陷。 首先,导入被捆绑在一个包中 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)
这适用于我的 Windows 机器...如果这不适用于您的机器,您能提供错误消息吗?
关于python - 如何将文本放入输入行 : how to ask for user input on the command line while providing a 'default' answer that the user can edit or delete?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30193945/