{"record":{"id":"db705d8bd5a3b6df","repo":"hankcs/HanLP","slug":"expected-a-file-fileno-or-a-file-descriptor","errorCode":null,"errorMessage":"Expected a file (`.fileno()`) or a file descriptor","messagePattern":"Expected a file \\(`\\.fileno\\(\\)`\\) or a file descriptor","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"hanlp/utils/io_util.py","lineNumber":539,"sourceCode":"            if r[2 * sid] <= ratio < r[2 * sid + 1]:\n                if isinstance(sample, list):\n                    sample = '\\n'.join('\\t'.join(x) for x in sample) + '\\n\\n'\n                out.write(sample)\n                break\n    if not filepath.endswith('.tsv'):\n        src.close()\n    for out in outs:\n        out.close()\n    return filenames\n\n\ndef fileno(file_or_fd):\n    try:\n        fd = getattr(file_or_fd, 'fileno', lambda: file_or_fd)()\n    except:\n        return None\n    if not isinstance(fd, int):\n        raise ValueError(\"Expected a file (`.fileno()`) or a file descriptor\")\n    return fd\n\n\n@contextmanager\ndef stdout_redirected(to=os.devnull, stdout=None):\n    \"\"\"Redirect stdout to else where.\n    Copied from https://stackoverflow.com/questions/4675728/redirect-stdout-to-a-file-in-python/22434262#22434262\n\n    Args:\n      to:  Target device.\n      stdout:  Source device.\n\n    \"\"\"\n    if windows():  # This doesn't play well with windows\n        yield None\n        return\n    if stdout is None:\n        stdout = sys.stdout","sourceCodeStart":521,"sourceCodeEnd":557,"githubUrl":"https://github.com/hankcs/HanLP/blob/ddb1299bddff079e447af52ec12549c50636bfa8/hanlp/utils/io_util.py#L521-L557","documentation":"fileno() normalizes files and file descriptors for stdout redirection; after calling .fileno() on the object, the result must be an int fd. If the object exposes a fileno() that returns something else (or a non-file, non-int object sneaks through), it raises ValueError.","triggerScenarios":"Passing an object to fileno()/stdout_redirected/_get_file_size whose fileno() returns a non-int (e.g. a mock, io.StringIO in some wrappers returning None, or an object whose __getattr__ yields junk).","commonSituations":"Redirecting stdout to a StringIO/captured buffer in tests; substituting fake file objects; Python 2/3 differences in file-like wrappers.","solutions":["Pass a real file object or an integer fd to stdout_redirected.","For in-memory capture, create a real temp file (open(tempfile.mkstemp()[1])) or use contextlib.redirect_stdout instead.","If wrapping, ensure your wrapper's fileno() delegates to the underlying file's fileno."],"exampleFix":"# before\nwith stdout_redirected(io.StringIO()): ...\n# after\nimport tempfile, os\nfd, tmp = tempfile.mkstemp()\nwith stdout_redirected(os.fdopen(fd, 'w')): ...\nos.remove(tmp)","handlingStrategy":"type-guard","validationCode":"fd = getattr(f, 'fileno', lambda: f)()\nassert isinstance(fd, int) and fd >= 0, 'need a real file or fd'","typeGuard":"def is_real_file(f):\n    fd = getattr(f, 'fileno', lambda: None)()\n    return isinstance(fd, int) and fd >= 0","tryCatchPattern":null,"preventionTips":["Use contextlib.redirect_stdout for in-memory capture.","Always pass open() file objects or ints into redirection helpers."],"tags":["file-descriptor","stdout","redirection"],"backgroundTag":"invalid-file-descriptor","analyzedSha":"ddb1299bddff079e447af52ec12549c50636bfa8","analyzedAt":"2026-08-27T03:36:54.287Z","schemaVersion":2},"datasetVersion":"2026-08-27T08:17:20.692Z"}