在配管时被剥光了

2024-05-23 15:37:25 发布

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

命令

 sys_info_json = '"'+stamp+'":{"cpu_free" : "'+str[0]+'","disk_available" : "'+str[1]+'","disk_free" : "'+str[2]+'","ram" : "'+str[3]+'","memory_free" :"'+str[4]+'"}'
 print sys_info_json
 os.system("echo " + sys_info_json + " >> sys_info.txt")

这里stamp和str[]是预定义的。你知道吗

我想以JSON格式保存数据。 当管道传输到文本文件(sys_信息.txt)双引号被去掉了。你知道吗


Tags: 命令infotxtjsonfreeosstampsys
2条回答

不要试图通过字符串连接来构建JSON。有一个内置的图书馆。不要通过os.system写入文件:使用openwrite函数。你知道吗

import json
data = {"cpu_free" : str[0], "disk_available": str[1], "disk_free": str[2], "ram": str[3], "memory_free": str[4]}
with open('sys_info.txt', 'w') as f:
    f.write("%s:%s" % (stamp, json.dumps(data)))

另外,不要调用liststr,因为它是a)不是字符串,b)隐藏了内置的str()函数。你知道吗

如果要在系统shell中看到引号,就必须对引号进行转义,类似这样的操作

In [16]: sys_info_json = '\\"test\\"'

In [17]: os.system("echo " + sys_info_json)
"test"
Out[17]: 0

用变量重写pythonstr也是不好的做法。尝试用未使用的python单词定义变量。你知道吗

相关问题 更多 >