代码:
import os
from time import *
import socket
import time
global diskspace
#####################
#display temp
#uses shell script to find out temp then uses python to display it
#python uses os module to run line of shell script
os.system("cat /sys/class/thermal/thermal_zone0/temp > sysTemp")
temp = open("sysTemp") # Open a file
str = temp.read(); # read characters in sysTemp
temp.close() # close opened file
t=eval(str) # convert string into number
t2=t*2 # multiply by 2, evaluated number
t3=(t/1000.00) # convert five figure temp (milli-degrees) to degrees to two decimal places
print ("temp is:")
temperature = int(t3)
print(temperature)
def temp():
if temperature > 60:
print("The temp is over 60. Cool down")
elif temperature < 40:
print("temp is below 40")
check()
#find name
##################
#check for internet connection
###################
#Display disk space
###################
def getDiskSpace():
p = os.popen("df -h /")
i = 0
while 1:
i = i +1
line = p.readline()
if i==2:
diskspace = (line.split()[4:5])
ds = diskspace[0]
print("The disk space used is:")
print(ds)
global ds
#Display CPU usage
###################
def getCPUuse():
print(os.popen("top -n1 | awk '/Cpu(s):/ {print $2}'").readline().strip())
#Display IP
###################
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("gmail.com",80))
IP = (s.getsockname()[0])
s.close()
print("The Ip is:" + IP)
getDiskSpace()
###################
#writing it to a .txt file
f = open("data.txt","w") #opens file with name of "test.txt"
f.write("raspberry pi data.n")
f.write("ip:n")
f.write(IP + "n")
#f.write("Disk usage:" + str(ds))
f.write("temp: {0}".format(t3))
f.write("disk usage: {0}".format(ds))
f.close()
temp()
getCPUuse()
print("...")
time.sleep(10)
它是一个监视pi的临时、磁盘空间、cpu使用情况和ip并将其写入txt文件的程序主要问题是这条线路的
f.write("Disk usage:" + diskspace + "n")
它说它没有定义,我尝试过很多事情,比如在def之前将其创建为空白,但没有为文本文件上的磁盘空间写入任何内容。其他东西写入文本文件,但不是这个
输出:温度为:58Ip为:192.168.1.36追踪(最近一次通话):文件"temp.py",第74行,inf.write("磁盘使用:"+磁盘空间)名称错误:未定义全局名称"磁盘空间"
如果你删除了关于写入位的位,{"40%"]通常会被打印出来以获得磁盘空间。
我添加了一些更改后的代码来打印数据,不抛出错误,但不写入。
您正在尝试在实际进入getDiskSpace()方法之前进行写入。
尝试在执行之前运行getDiskSpace()
f.write("Disk usage:" + diskspace + "n")
您需要在getDiskSpace的函数定义中使用全局定义。你不能在主程序中全局定义它,也不能在函数内部扩展它。