在python中将变量写入txt会引发一些错误

在python中将变量写入txt会引发一些错误,python,linux,python-3.x,global-variables,Python,Linux,Python 3.x,Global Variables,守则: 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 /

守则:

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) 
它说它没有定义,我尝试过很多方法,比如在def为空之前创建它,但是在文本文件中没有为diskspace写入任何内容。其他东西会写入文本文件,但不会写入此文件

输出: 温度为: 58 Ip为:192.168.1.36 回溯(最近一次呼叫最后一次): 文件“temp.py”,第74行,在 f、 写入(“磁盘使用:”+diskspace) NameError:未定义全局名称“diskspace”

如果删除关于写入位的位,{'40%']通常会为磁盘空间打印


我添加了一些已更改的代码,这些代码打印数据,不会抛出错误,但不会写入数据。

在实际使用getDiskSpace()方法之前,您正在尝试编写这些代码

在执行此操作之前,请尝试运行getDiskSpace()

f.write("Disk usage:" + diskspace + "\n")

您需要在getDiskSpace的函数定义中使用全局定义。您不能在主程序中全局定义它,也不能在函数中进行扩展。

如果
i!=2
,会发生什么情况?
diskspace
何时定义?diskspace不会被打印,并且通常会抛出错误。它不会被忽略也不会写入文本文件。它仍然不会写入文本文件
f.write("Disk usage:" + diskspace + "\n")