为什么询问者问两次?
我编写了一个小程序,该程序允许用户(使用询问者)编辑或添加新的线路,然后
import inquirer
def edit_line(file):
a_file = open(file, 'r')
print('Your file: \n' + open(file).read())
list_of_lines = a_file.readlines()
index = int(input('What line would you like to edit?: ')) - 1
list_of_lines[index] = input('Write your text here: ') + '\n'
a_file = open(file, 'w')
a_file.writelines(list_of_lines)
a_file.close()
print(('\nYour new file:\n' + open(file).read()))
def add_line(file):
a_file = open(file, 'a')
print('Your file: \n' + open(file).read())
a_file.write('\n' + input('Enter text to add: '))
a_file.close()
print(('Your new file:\n' + open(file).read()))
def op_cselector():
questions = [
inquirer.List('operation',
message='What would you like to do?: ',
choices=['Add line', 'Edit line']
)
]
answers = inquirer.prompt(questions)
return answers['operation']
if op_cselector() is 'Add line':
add_line('sample.txt')
elif op_cselector() is 'Edit line':
edit_line('sample.txt')
在我选择第一个选项时可以正常工作,但是当我选择第二个选项时,它会再次提出问题。这次,如果我选择了第二个选项,则该程序按预期工作,但是如果我更改决定,则不会终止任何错误。
我该如何解决?也许我应该使用另一个模块?
我喜欢查询者,因为它看起来很棒,并且在终端中效果很好,但是我擅长使用它:/
I wrote a little program that allows the user (using inquirer) to either edit or add a new line to a file
import inquirer
def edit_line(file):
a_file = open(file, 'r')
print('Your file: \n' + open(file).read())
list_of_lines = a_file.readlines()
index = int(input('What line would you like to edit?: ')) - 1
list_of_lines[index] = input('Write your text here: ') + '\n'
a_file = open(file, 'w')
a_file.writelines(list_of_lines)
a_file.close()
print(('\nYour new file:\n' + open(file).read()))
def add_line(file):
a_file = open(file, 'a')
print('Your file: \n' + open(file).read())
a_file.write('\n' + input('Enter text to add: '))
a_file.close()
print(('Your new file:\n' + open(file).read()))
def op_cselector():
questions = [
inquirer.List('operation',
message='What would you like to do?: ',
choices=['Add line', 'Edit line']
)
]
answers = inquirer.prompt(questions)
return answers['operation']
if op_cselector() is 'Add line':
add_line('sample.txt')
elif op_cselector() is 'Edit line':
edit_line('sample.txt')
It works fine when I choose the first option, but when i choose the second one it asks the question again. This time if I choose the second option the program works as intended, but if i change my decision it terminates without errors.
How do I fix this? Maybe there is a different module I should use?
I like inquirer, because it looks great and works great in a terminal, but I'm not that great at using it :/
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您正在调用
OP_CSELECTOR
两次,因此显示了两次输入...您应该调用一次并将结果保存在变量中。另外,应将字符串与
==
进行比较,而不是是
。You are calling
op_cselector
twice so the input is shown twice... You should call it once and save the result in a variable.Also, strings should be compared with
==
, notis
.