python - 是否有 Python 等同于 Perl 的 __DATA__ 文件句柄?

标签 python perl filehandle

在 Perl 中,我经常从脚本末尾的文件句柄 __DATA__ 中读取数据:

while (<DATA>) {
    chomp;
    say;
}
__DATA__
line1
line2 

我发现这比读取文件更快地测试代码等,因为这意味着我可以即时编辑其内容。

来自doc :

The __DATA__ token tells the perl compiler that the perl code for compilation is finished.

Everything after the __DATA__ token is available for reading via the filehandle FOOBAR::DATA, where FOOBAR is the name of the current package when the __DATA__ token is reached.

在 Python 中有对应的东西吗?如果没有,有人可以建议实现类似事情的最 Python 风格的方法吗?

最佳答案

不,Python 中没有直接的等价物。将您的数据放入多行变量中:

DATA = '''\
line1
line2
'''

然后您可以使用DATA.splitlines() v2/v3 如果您必须访问单独的行。你可以把它放在你的 Python 文件的末尾,前提是你只在一个函数中使用名称 DATA,这个函数直到整个模块加载后才被调用。

或者,打开当前模块并从中读取:

with open(__file__.rstrip('co')) as data:
    for line in data:
        while line != '# __DATA__\n':
            continue
        # do something with the rest of the 'data' in the current source file.

# ...

# __DATA__
# This is going to be read later on.

然而,模块的其余部分必须至少仍然是有效的 Python 语法;不能告诉 Python 解析器停止解析超过给定点。

一般来说,在 Python 中,您只需将数据文件放在源文件的旁边 并读取它。您可以使用 __file__ 变量生成“当前目录”的路径,从而指向同一位置的任何其他文件:

import os.path

current_dir = os.path.dirname(os.path.abspath(__file__))
with open(os.path.join(current_dir, 'data.txt')) as data:
    # read from data.txt

关于python - 是否有 Python 等同于 Perl 的 __DATA__ 文件句柄?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38368956/

相关文章:

解开文件句柄后,Perl 无法 Binmode STDOUT

php - 如何使用 php ://memory file handle? 执行 cURL PUT 请求

Python 3.6 嵌套字典动态更新

Perl:将 MSB 和其余位与十六进制分开

macos - 类似于 nodemon 的工具,用于 perl

perl - 我所有的 Moose 类都必须包含 'namespace::autoclean' 和 'make_immutable' 还是有某种方法可以默认获取这些?

perl - 尝试打印到已关闭的文件句柄没有错误或警告

python - Python 2.7 中的断言对我不起作用示例 assertIn

python - 在Python中访问父类的静态类变量

python - uWSGI服务器日志……读取文件的权限被拒绝……哪个文件?