剪贴板包含换行符,Python认为用户按en

2024-06-02 08:57:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这个密码:

print("Welcome to the NetBackup Symbolic Link Generator.\n")
print("Log into a server and run the command 'ls $ORACLE_BASE/admin'. Copy the list of folders (database names), but omit filenames and/or +ASM, then paste below.\n")

databases=input("Enter databases: ")
numNodes=input("Enter the number of nodes (1, 2, or 3): ")

print("\nCopy the output below and paste into the SSH session as \"orainst\".\n")

if int(numNodes) == 1:
    streams="1a 1b 1c"
elif int(numNodes) == 2:
    streams="1a 2a 1b 2b 1c 2c"
else:
    streams="1a 2a 3a 1b 2b 3b 1c 2c 3c"

db_list = databases.split()
streams_list= streams.split()

for db in db_list:
    print(db)

input("Press \"Enter\" to exit.")

一切正常,除非用户粘贴包含换行符的内容,如:

dbone dbtwo tbtree
dbfour dbfive

最后我得出这样的结论:

Welcome to the NetBackup Symbolic Link Generator.

Log into a server and run the command 'ls $ORACLE_BASE/admin'. Copy the list of folders (database names), but omit filenames and/or +ASM, then paste below.

Enter databases: dbone dbtwo tbtree
dbfour dbfive
Enter the number of nodes (1, 2, or 3): 
Copy the output below and paste into the SSH session as "orainst".

Traceback (most recent call last):
  File "C:\Users\en195d\Documents\Personal\Project\Python\NetBackupSymLinkGen.py", line 12, in <module>
    if int(numNodes) == 1:
ValueError: invalid literal for int() with base 10: 'dbfour dbfive'
>>> 

如何处理包含换行符的输入?你知道吗


Tags: orandofthedbdatabaseliststreams
2条回答

调用input()时,它读取一行数据并将其返回给程序。第二行仍然位于低级libc输入缓冲区中。Strip('\n')不起作用,因为python还没有看到第二行数据。不幸的是,很难看出stdin中是否有更多的数据。你不能偷看,如果你阅读,它将挂起等待输入的其他99%的用户谁剪切/粘贴正确。你知道吗

处理这个用例的选项非常混乱,可能会弄乱其他用例(例如,一个真正希望第二行是对第二个问题的响应的剪切粘贴者怎么办)。就我个人而言,我会做几乎所有命令行程序都会做的事情:将其视为垃圾输入/垃圾输出,然后失败。你知道吗

你可以一直要求输入,直到用户输入一个数字。如果用户选择以下选项,则可以在多行中输入数据库名称:

user_input = []
while len(user_input) == 0 or user_input[-1] not in ["1", "2", "3"]:
    response = input("Enter databases, followed by number of nodes (1, 2, or 3): ")
    user_input.extend(response.split())

numNodes = user_input.pop()
db_list = user_input

print(numNodes)
print(db_list)

结果:

Enter databases, followed by number of nodes (1, 2, or 3): dbone dbtwo tbtree
Enter databases, followed by number of nodes (1, 2, or 3): dbfour dbfive
Enter databases, followed by number of nodes (1, 2, or 3): 1
1
['dbone', 'dbtwo', 'tbtree', 'dbfour', 'dbfive']

这种方法的一个缺点是,用户可能有一个名为“1”的数据库,并且无法输入它,因为它将被解释为numNodes。另一种选择是在收到空行之前一直接受db名称:

db_list = []
while True:
    response = input("Enter databases (press Enter when finished): ")
    if not response: break
    db_list.extend(response.split())

numNodes = input("Enter the number of nodes (1, 2, or 3):")

print(numNodes)
print(db_list)

结果:

Enter databases (press Enter when finished): dbone dbtwo tbtree
Enter databases (press Enter when finished): dbfour dbfive
Enter databases (press Enter when finished):
Enter the number of nodes (1, 2, or 3):1
1
['dbone', 'dbtwo', 'tbtree', 'dbfour', 'dbfive']

相关问题 更多 >