Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.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 2.7_Readline_Sys - Fatal编程技术网

将python中读取器的输入读入字符串

将python中读取器的输入读入字符串,python,python-2.7,readline,sys,Python,Python 2.7,Readline,Sys,我在Python中有一个函数,它包含一个“阅读器”(我希望这是正确的术语)。基本上,函数应该能够使用文件、sys.stdin等。然后它必须读取所有行并将它们存储到字符串中 当前,我的函数调用类似于: read_data (sys.stdin, sys.stdout) read_data ("file.txt", "fileout.txt") 函数本身看起来像: def read_data (reader, s) : str = "" str = r.readlin

我在Python中有一个函数,它包含一个“阅读器”(我希望这是正确的术语)。基本上,函数应该能够使用文件、sys.stdin等。然后它必须读取所有行并将它们存储到字符串中

当前,我的函数调用类似于:

   read_data (sys.stdin, sys.stdout)

   read_data ("file.txt", "fileout.txt")
函数本身看起来像:

def read_data (reader, s) :

   str = ""

   str = r.readline()
   line = str
   while line != "" and line != None and line != '\n':
       line = r.readline()
       str = str + line

当我运行代码并将输入粘贴到控制台中进行测试时,它实际上能够读取包括最后一行在内的所有行,但在这之后它会被卡在“line=readline()”中。我不确定我做错了什么,任何帮助都将不胜感激。谢谢

阅读前需要先打开文件,例如:

f = open(reader, "r")
text = f.readline()

^另外,在传递打开的文件描述符时,尽量不要使用保留关键字,如“str”

。在另一个例子中,您传递的是一个字符串。后者与具有
readline
方法的接口不匹配。您可以通过以下几种方法之一解决此问题。测试对象是否有
读线
方法:

if not hasattr(reader, "readline"): # and is callable, etc, etc
    reader = open(reader, 'r')
尝试/除外

try:
    result = reader.readline()
except AttributeError:
    with open(reader,'r') as realreader:
        result = realreader.readline()

还有其他方法。如果是这样的话,您应该记录函数本身需要一个函数。

我建议您像这样重新构造程序:

def read_data(in_stream=sys.stdin, out_stream=sys.stdout):
    """
    in_srteam: stream open for reading (defaults to stdin)
    out_stream: stream open for writing (defaults to stdout)
    """

    s = ''.join([line for line in in_stream])
    out_stream.write(s)

您将字符串视为文件对象(或具有
readline
方法的任何对象)。如果希望能够同时传递字符串和文件对象,那么可以先测试参数是否为字符串

def read_data (reader, s) :
   if isinstance(reader,str):
       reader = open(reader,"r")   
   if isinstance(s,str):
       s = open(s,"w+")

   str = "" #avoid using str for a variable name

   str = r.readline()
   line = str
   while line != "" and line != None and line != '\n':
       line = r.readline()
       str = str + line

在选择是否尝试将其作为文件打开之前,您还可以使用
hasattr
测试传递的对象是否具有
readline
方法。

如果我正确理解您的问题,您需要将EndOfFile放入流中。要在Unix/Linux中进行交互式输入,请在Windows中使用
Ctrl-d
(即^d)

如果没有这个
readline,则不会像您期望的那样返回空字符串

readline(...)
    readline([size]) -> next line from the file, as a string.

    Retain newline.  A non-negative size argument limits the maximum
    number of bytes to return (an incomplete line may be returned then).
    Return an empty string at EOF.

FWIW我想你要找的术语是
IO
object,如果您在windows上,您基本上是在寻找实现的任何对象,您可能需要添加
和line!='\r\n'
。为了使事情更简单,您可能希望将if改为[“”,…]中的
if not行:
@LaurIvan我建议将文件结尾的检测留给操作系统,即python库。当遇到空行时,上述解决方案也会停止读取输入文件,即不在EOF。猜猜这是否是OP的本意。问题的一部分是有时候fd已经打开了。感谢关于str的提示(我实际上使用的是s,只是把str放在问题中)。是的,由于我也使用sys.stdin调用函数,所以问题就出现了。join([line for line in_stream])
''不同。join(in_stream.readlines())
?(我的观点是,据我所知,所有实现
readline
的对象也实现
readlines
)@kojiro:''.join(in_stream.readlines())基本上是in_stream.read()。有了理解力,我可以去掉新行或者对新行做些什么。