Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/327.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何将行从文件传递到输入()?_Python_Python 3.x_Input - Fatal编程技术网

Python 如何将行从文件传递到输入()?

Python 如何将行从文件传递到输入()?,python,python-3.x,input,Python,Python 3.x,Input,如果我想测试一个简单的程序: for _ in range(int(input())): a = int(input()) print(a+2) 使用输入文件 3 1 9 4 如何启动python并指出在不修改解决方案程序的情况下读取输入文件中的行?这取决于您的shell,但标准Linux/macOS的常见解决方案是: python program.py < file python program.py

如果我想测试一个简单的程序:

for _ in range(int(input())):
    a = int(input())
    print(a+2)
使用输入文件

3
1
9
4

如何启动python并指出在不修改解决方案程序的情况下读取输入文件中的行?

这取决于您的shell,但标准Linux/macOS的常见解决方案是:

python program.py < file
python program.py
注意:这段代码在Python 3上根本不起作用<在Python3上,code>input总是返回一个
str
,您假设它将是一个
int
。您需要将
input()。在Python2上它会起作用(但更危险),因为Python2上的
input()
的行为等同于Python3上的
eval(input())
。感谢您指出,这只是一个简单的示例,现在应该修复实际程序中的用例是什么?