如果提供了任何命令行参数,则将打印语句输出重定向到文件

2024-05-18 19:23:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我写了一个函数,它只有使用openstackapi从Openstack获取细节的功能。我已经在做日志记录了,但是为了快速验证少数网络,我将几个print语句的输出重定向到一个文件中。(看起来是这样的),这个很好用。你知道吗

def get_net_details():
    ...
    filename = open('validation.txt', 'a')
    network_name = network['name']
    print >> filename, 'Network Name : {0}'.format(network_name)
    network_id = subnet_detail['subnet']['network_id']
    print >> filename, 'Network ID : {0}'.format(network_id)
    network_type = network['provider:network_type']
    print >> filename, 'Network Type : {0}'.format(network_type)
    print >> "========================================="
    filename.close()

问题是,仅当用户在脚本执行时提供任何命令行输入(通过argparse或任何其他方式进行切换)时,我才想将print语句的输出记录到文件中。你知道吗

任何帮助都将不胜感激。。!你知道吗


Tags: 文件函数nameidformatopenstacktype记录
1条回答
网友
1楼 · 发布于 2024-05-18 19:23:27

首先重写函数,使其以流作为输入:

def get_net_details(outstream):
    ...
    network_name = network['name']
    print >> outstream, 'Network Name : {0}'.format(network_name)
    network_id = subnet_detail['subnet']['network_id']
    print >> outstream, 'Network ID : {0}'.format(network_id)
    network_type = network['provider:network_type']
    print >> outstream, 'Network Type : {0}'.format(network_type)
    print >> outream, "========================================="

然后让调用者将打开的文件或sys.stdout(取决于命令行标志)作为param传递。你知道吗

def main(...):
    # argparse stuff here

    if someflag:
        outstream = open(path/to/file, "w")
    else:
        outstream = sys.stdout
    try:
        get_net_details(outstream)
    finally:
        if someflag:
            outstream.close()

相关问题 更多 >

    热门问题