Skip to main content
 首页 » 编程设计

python之如何在从 input() 获取输入时保留输入的换行符

2024年11月01日15zhenyulu

我目前正在编写一个简单的脚本,我想在其中获取来自控制台的输入。此输入是一个 Python 代码片段。在文件中写入输入时,整体对齐不正确。

举个例子:

model_def = str(input("Paste the defination of the classifier used :")) 
f = open("classifier.py","w+") 
f.write(model_def) 
f.close() 

输入是这样的:

class classifier(nn.Module): 
    def __init__(self): 
        super().__init__() 
        self.fc1 = nn.Linear(2208, 500) 
        self.fc2 = nn.Linear(500, 256) 
        self.fc3 = nn.Linear(256, 3) 
        self.dropout = nn.Dropout(0.5) 
        self.logsoftmax = nn.LogSoftmax(dim=1) 
        self.acivation = relu 
    def forward(self,x): 
        x = x.view(x.size(0), -1) 
        x = self.dropout(self.acivation(self.fc1(x))) 
        x = self.dropout(self.acivation(self.fc2(x))) 
 
        x = self.logsoftmax(self.fc3(x)) 
        return x 
 

保存它会导致对齐不正确。

class classifier(nn.Module):     def __init__(self):         super().__init__()         self.fc1 = nn.Linear(2208, 500)         self.fc2 = nn.Linear(500, 256)         self.fc3 = nn.Linear(256, 3)         self.dropout = nn.Dropout(0.5)         self.logsoftmax = nn.LogSoftmax(dim=1)         self.acivation = relu     def forward(self,x):         x = x.view(x.size(0), -1)         x = self.dropout(self.acivation(self.fc1(x)))         x = self.dropout(self.acivation(self.fc2(x)))          x = self.logsoftmax(self.fc3(x))         return x 

请您参考如下方法:

您必须从输入开始读取直到 EOF。您可以使用 Ctrl-D 或 Ctrl-Z (windows) 提高 EOF:

python 3

print("Paste the defination of the classifier used. Ctrl-D or Ctrl-Z ( windows ) to save it.") 
contents = [] 
while True: 
    try: 
        line = input() 
    except EOFError: 
        break 
    contents.append(line) 
 
f = open("classifier.py","w+") 
for line in contents: 
    f.write("%s\n" % line) 
f.close()