2015-02-23 48 views
-1

代码:写一个变量到一个txt在python扔了几个错误

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) 

它是监视温度,磁盘空间,CPU使用率和IP的圆周率,并将其写入到一个txt的程序文件 的主要问题是这一行

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

和它说,它没有定义,我试图像清晰度为空白之前创造了很多事情,但再没有获取有关文本文件的磁盘空间写入。其他的东西写入文本文件,但没有这一项

输出: 温度是:知识产权为:192.168.1.36 回溯(最近通话最后一个): 文件“temp.py”线74,在 f.write(“磁盘使用情况:” +磁盘空间) NameError:全局名称“的磁盘空间”,如果你删除有关写位位,{'40%'是没有定义

]通常得到为磁盘空​​间打印。

ive添加了一些打印数据的更改代码,抛出错误,但没有写它。

+0

如果'i!= 2'会发生什么? 'diskspace'何时被定义? – 2015-02-23 15:20:17

+0

diskspace不会被打印,并且会抛出通常的错误。它也不会被写入文本文件。 – oddubcoder 2015-02-23 15:25:17

回答

0

您正在尝试编写实际进入getDiskSpace()方法之前的代码。

尝试运行getDiskSpace()你做

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

没有工作 – oddubcoder 2015-02-23 15:47:10

0

之前,您需要使用getDiskSpace的函数定义内部全局定义。您不能在主程序中对其进行全局定义,并且可以在函数内部进行扩展。

+0

它仍然没有将它写入文本文件 – oddubcoder 2015-02-24 10:16:54