2017-05-05 1 views
0

첫 번째 글은 Python을 배우는 초기 단계입니다. 부드럽게하십시오. 작동하는 코드 조각이 있지만 출력을 읽기가 어렵습니다. 화면을 아래로 스크롤하는 상향식 목록이 아닌 정적으로 화면에 센서를 표시하고 싶습니다. 인쇄 기능을 변경하여 쉘 윈도우의 단일 위치에서 매 초마다 온도를 업데이트 할 수 있습니까? 항상 화면에 동일한 위치에 요소를 인쇄하려면주어진 위치에 텍스트를 표시하는 방법은 무엇입니까?

import os 
import glob 
import time 

os.system('modprobe w1-gpio') 
os.system('modprobe w1-therm') 

def read_temp_raw(i): 
    base_dir = '/sys/bus/w1/devices/' 
    device_folder = glob.glob(base_dir + '28*')[i] 
    device_file = device_folder + '/w1_slave' 
    f = open(device_file, 'r') 
    lines = f.readlines() 
    f.close() 
    return lines 

def read_temp(i): 
    lines = read_temp_raw(i) 
    while lines[0].strip()[-3:] != 'YES': 
     time.sleep(0.2) 
     lines = read_temp_raw() 
    equals_pos = lines[1].find('t=') 
    if equals_pos != -1: 
     temp_string = lines[1][equals_pos+2:] 
     temp_c = float(temp_string)/1000.0 
     temp_f = temp_c * 9.0/5.0 + 32.0 
     return temp_c, temp_f 

while True: 
    print "Sensor 1", (read_temp(0)) 
    print "Sensor 2", (read_temp(1)) 
    print "Sensor 3", (read_temp(2)) 
    time.sleep(2) 
+0

StackOverflow에 오신 것을 환영합니다. 당신의 질문 제목은 센서보다 콘솔 텍스트 그리기에 관한 질문 내용과 일치하지 않습니다. –

+0

사실, 위의 코드에서 센서 부분이 도움이 될 수 있습니다. 재미있게도 필자는 sys.stdout.write와 캐리지 리턴을 사용하여 보았지만 아직 작동시키지 못했습니다. – Marko

+0

질문에 더 잘 부합하도록 제목이 바뀌 었습니다. 마음에 들지 않았 으면 좋겠어요. 콘텐츠를 반영하도록 내용을 바꾸어주세요. – zmo

답변

1

미리 감사드립니다, 당신은 몇 가지 특별한 콘솔 문자를 사용할 수 있습니다 :

  • 는 ASCII 문자 \r 항상 같은 라인을 덮어 쓰게됩니다

당신이 할 그렇다면 :

# use the new format of print, not the old one 
from __future__ import print_function 

while True: 
    print ("Sensors: {}\t{}\t{}  ".format(
       read_temp(0), read_temp(1), read_temp(2)), end='\r') 
    time.sleep(2) 
,만 자체를 새로 고쳐집니다 한 줄거야 : 솔루션은 윈도우를 포함한 대부분의 콘솔에서 작동

Sensors: 42 42 42 

것을. 당신은 항상 세 가지 라인을 가지고 싶다면

는, 당신은 화면마다 당신을 취소해야하는 루프 :

  • \33[2J가 (당신이 C 바인딩 키보드를 칠 때처럼 화면을 취소 할 ANSI 명령 - L). 해당 솔루션이 아닌 ANSI 콘솔에서 작동하지 않습니다하지만

즉 :

while True: 
    print('\33[2J') 
    print('Sensor 1: {}'.format(read_temp(0))) 
    print('Sensor 2: {}'.format(read_temp(1))) 
    print('Sensor 3: {}'.format(read_temp(2))) 

. 좀 더 복잡한 출력을하려면

  • , 당신은 ncurses를 기반으로하고 명령 행에서 사용자 인터페이스를 그릴 수있는 blessings 라이브러리를 사용할 수 있습니다.

는 방법은 다음과 같습니다. 특수 문자를 사용하는 방법에 대한 걱정, 그냥 열 + 행 (location()0, 0 매개 변수를 사용하여 위치를 사용하지 않도록

import blessings 

term = blessings.Terminal() 
with term.fullscreen(): 
    while True: 
     with term.location(0, 0): 
      print('--- This is the first line ---') 
      print('Sensor 1: {t.bold}{}{t.normal}'.format(read_temp(0), t=term)) 
      print('Sensor 2: {t.bold}{}{t.normal}'.format(read_temp(1), t=term)) 
      print('Sensor 3: {t.bold}{}{t.normal}'.format(read_temp(2), t=term)) 
      print('--- This is the fifth line ---') 

그 다음과 같이 인쇄됩니다 :

--- This is the first line --- 
Sensor 1: 0 
Sensor 2: 122 
Sensor 3: 244 
--- This is the fifth line --- 

콘솔 상단에.측면으로 820,973,210


N.B : 그것을 사용하는 것이 더 안전주의 : 심지어 읽기 실패시, 장치 파일을 닫습니다

def read_temp_raw(i): 
    base_dir = '/sys/bus/w1/devices/' 
    device_folder = glob.glob(base_dir + '28*')[i] 
    device_file = device_folder + '/w1_slave' 
    with open(device_file, 'r') as f: 
     return f.readlines() 

.

+0

코드의 첫 번째 변형 - 모두 한 줄로 유지합니다. 이미/r을 시도했지만 캐리지 리턴 대신 이상한 상자가 나타납니다. 그래서 여전히 오름차순으로 진행됩니다. \ n * 100을 사용하는 선명한 화면을 만들었지 만,이 비단뱀 쉘에서는 작동하지 않습니다. 어쨌든 필수적이지 않은 화면을 지우면 이제는 읽을 수 있습니다. 궁극적으로 나는 이것들을 DB에 로깅해야 할 것이고, 그것은 상황이 훨씬 더 복잡해질 것이라고 확신합니다! 다시 한 번 감사드립니다! – Marko