Python脚本无法使用文件

时间:2016-06-25 19:16:00

标签: python python-2.7 raspberry-pi2

如果我从终端命令行运行“python /home/pi/temp/getTemp.py”我得到 “错误,串口''不存在!”如果我cd到临时目录并运行“python getTemp.py”它运行正常。谁能告诉我为什么?

#!/usr/bin/env python

import os
import sys
import socket
import datetime
import subprocess
import signal

port = "/dev/ttyUSB0"
tlog = '-o%R,%.4C'
hlog = '-HID:%R,H:%h'
clog = '-OSensor %s C: %.2C'


def logStuff(data):
    with open("/home/pi/temp/templog.txt", "a") as log_file:
        log_file.write(data + '\n')       

def main():

    try:

        output = subprocess.check_output(['/usr/bin/digitemp_DS9097U', '-q', '-a'])

        for line in output.split('\n'):

            if len(line) == 0:
                logStuff("len line is 0")
                continue

            if  'Error' in line:
                logStuff("error in output")
                sys.exit()

            line = line.replace('"','')

            if line.count(',') == 1:
                (romid, temp) = line.split(',')

            poll = datetime.datetime.now().strftime("%I:%M:%S %p on %d-%B-%y")        

            content =(romid + "," + poll + "," + temp)
            print content
            return content

    except subprocess.CalledProcessError, e:
        print "digitemp error:\n", e.output

    except Exception as e:
        logStuff('main() error: %s' %e)
        os.kill(os.getpid(), signal.SIGKILL)


if __name__ == "__main__":
    main()

1 个答案:

答案 0 :(得分:0)

它可能找不到配置文件,当你使用-i运行初始化网络时,它通常存储在〜/ .digitemprc中。如果它是在不同的目录中创建的,你需要通过传递-c

告诉digitemp在哪里找到它