我有这段代码:
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'
>>>
如何处理包含换行符的输入?
答案 0 :(得分:0)
在用户输入数字之前,您可以继续询问输入。这允许用户在多行中输入数据库名称,如果他们选择:
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_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']
答案 1 :(得分:0)
当你调用input()时,它会读取一行数据并将其返回给你的程序。第二行仍然位于低级libc输入缓冲区中。 Strip(&#39; \ n&#39;)没有用,因为python还没有看到第二行数据。不幸的是,很难看出stdin中是否有更多数据。您无法查看,如果您阅读,它只会等待其他99%正确剪切/粘贴的用户的输入。
处理这个用例的选项相当混乱,并且可能搞乱其他用例(例如,真正希望第二行成为对第二个问题的响应的剪切和贴片的情况)。就个人而言,我会做几乎所有命令行程序所做的事情:将其视为垃圾进/出垃圾并失败。