nwnusun

   ::  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

前景

Python编写HDFS服务安装的过程中,需要将构建好的JSON对象输出到文件,采用那种方式更便捷

方案1

open 函数
    def writeExecCmdCheckActionsFile(self, out_res, check_item):
        """
        输出到文件
        """
        try:
            # host_check_java_env_check.result
            self.hostCheckCustomActionsFilePath = self.hostCheckCustomActionsFilePath + check_item + '.result'
            print("Host check custom action report at " + self.hostCheckCustomActionsFilePath)
            with open(self.hostCheckCustomActionsFilePath, 'w+') as configfile:
                configfile.write(str(out_res))
        except Exception as err:
            logging.error("Can't write host check file at %s :%s " % (self.hostCheckCustomActionsFilePath, err))

上述代码中with open(self.hostCheckCustomActionsFilePath, 'w+') as configfile: 打开了文件流对象 configfile, 用write()方法将字符串写入

write()方法

write()方法可将任何字符串写入一个打开的文件。需要重点注意的是,Python字符串可以是二进制数据,而不是仅仅是文字。

write()方法不会在字符串的结尾添加换行符('\n'):

注意:configfile.write(str(out_res)) 中,out_res 是一个Python json对象,不是字符串,所以用 str() 将json转为str,然后再写入

如果不想用 str() 方法转换,可以采用如下第二种方案

方案2

JSON模块

导入json库

import json
用法
  • json.dumps() 将Python对象编码成json字符串
  • json.dump() 将Python对象转化为json存储到文件中
  • json.load() 将文件中的json格式转化成Python对象提取出来
  • json.loads() 将json字符串编码成Python对象
测试

json.dumps json 对象--->str

import json

def run1():
    # 定义一个json对象
    a = {"name": "zhangsan", "age": 18}
    print(type(a))
    b = json.dumps(a)
    print(type(b))

if __name__ == '__main__':
    run1()
--------------输出------------
<class 'dict'>
<class 'str'>

json.dump json对象写入text.txt

def run2():
    try:
        file = "text.txt"
        a = {"name": "zhangsan", "age": 18}
        with open(file, 'w') as f:
            json.dump(a, f)
    except Exception as e:
        print(e)

当前目录下输出一个文件text.txt,内容如下

{"name": "zhangsan", "age": 18}

json.load json文件--> json对象

def run3():
    """
    text.txt --> json type
    :return:
    """
    try:
        file = "text.txt"
        with open(file, 'r') as f:
            return json.load(f)
    except Exception as e:
        print(e)


if __name__ == '__main__':
    a = run3()
    print(type(a)) 
--------输出如下------------
<class 'dict'>

json.loads() json字符串--> json对象

def run4():
    # 定义一个json字符串
    a = """{"name": "zhangsan", "age": 18}"""
    print(type(a))
    b = json.loads(a)
    print(type(b))
------输出如下-----
<class 'str'>
<class 'dict'>

总结

在本次编码中,需求是将构建好的Json对象返回,最终写入文件,所以选择json.dump()

代码如下:

    def output_file(self, data, fun):
        try:
            logfile = self.outFilePath + "_" + fun + '.result'
            print("function output file:" + logfile)
            with open(logfile, 'w') as f:
                json.dump(data, f)
        except Exception as e:
            logging.error("ouput to file error" + str(e))

data: json对象

logfile: 当前路径下的输出文件名称

执行 hdfs_config.py 最终输出如下:

-rw-r--r--. 1 root root    99 10月 27 12:56 hdfs_install_task_checkHDFSGroup.result
-rw-r--r--. 1 root root    99 10月 27 12:56 hdfs_install_task_checkHDFSUser.result
-rw-r--r--. 1 root root   238 10月 27 12:56 hdfs_install_task_chown2Hadoop.result
-rw-r--r--. 1 root root 53512 10月 27 12:56 hdfs_install_task_decompressionHDFS.result
-rw-r--r--. 1 root root   123 10月 27 12:56 hdfs_install_task_lnsHDFSConfig.result
-rw-r--r--. 1 root root   223 10月 27 12:56 hdfs_install_task_makeHDFSDir.result
-rw-r--r--. 1 root root   100 10月 20 11:30 checkWebUI.py
-rw-r--r--. 1 root root   747 10月 25 11:56 datanode.py
-rw-r--r--. 1 root root 23344 10月 27 12:55 hdfs_config.py  ## 执行脚本
-rw-r--r--. 1 root root 24886 10月 27 12:41 hdfs_install_task

内容:

{"exit_code": 0, "exec_cmd": "ln -s /srv/dstore/1.0.0.0/hdfs/etc /etc/dstore/1.0.0.0/hdfs", "message": "ln -s is success!"}
posted on 2022-10-27 14:44  匿名者nwnu  阅读(108)  评论(0编辑  收藏  举报