Избавьтесь от серьезной боли (из-за подробностей реализации низкого уровня HDF5) и посмотрите HDFql .
Здесь приводится решение с использованием HDFql в C # для чтения многомерного (размер 3x3) набора данных с именем dset
типа данных double, хранящегося в файле HDF5 с именем test.h5
(предположим, что и файл, и набор данных уже существуют) :
// use HDFql namespace (make sure it can be found by the C# compiler)
using AS.HDFql;
public class Test
{
public static void Main(string []args)
{
// declare variables
double [,]data = new double[3, 3];
int x;
int y;
// use (i.e. open) HDF file "test.h5"
HDFql.Execute("USE FILE test.h5");
// register variable "data" for subsequent use (by HDFql)
HDFql.VariableRegister(data);
// select (i.e. read) dataset "dset" into variable "data"
HDFql.Execute("SELECT FROM dset INTO MEMORY " + HDFql.VariableGetNumber(data));
// unregister variable "data" as it is no longer used/needed (by HDFql)
HDFql.VariableUnregister(data);
// display content of variable "data"
for(x = 0; x < 3; x++)
{
for(y = 0; y < 3; y++)
{
System.Console.WriteLine(data[x, y]);
}
}
}
}
Для Windows, только консоль, используйте модуль msvcrt
:
import msvcrt
num = 0
done = False
while not done:
print(num)
num += 1
if msvcrt.kbhit():
print "you pressed",msvcrt.getch(),"so now i will quit"
done = True
Для Linux это статья описывает следующее решение, для него требуется модуль termios
:
import sys
import select
import tty
import termios
def isData():
return select.select([sys.stdin], [], [], 0) == ([sys.stdin], [], [])
old_settings = termios.tcgetattr(sys.stdin)
try:
tty.setcbreak(sys.stdin.fileno())
i = 0
while 1:
print(i)
i += 1
if isData():
c = sys.stdin.read(1)
if c == '\x1b': # x1b is ESC
break
finally:
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_settings)
Для кросс-платформы или, если вам также нужен графический интерфейс, вы можете использовать Pygame:
import pygame
from pygame.locals import *
def display(str):
text = font.render(str, True, (255, 255, 255), (159, 182, 205))
textRect = text.get_rect()
textRect.centerx = screen.get_rect().centerx
textRect.centery = screen.get_rect().centery
screen.blit(text, textRect)
pygame.display.update()
pygame.init()
screen = pygame.display.set_mode( (640,480) )
pygame.display.set_caption('Python numbers')
screen.fill((159, 182, 205))
font = pygame.font.Font(None, 17)
num = 0
done = False
while not done:
display( str(num) )
num += 1
pygame.event.pump()
keys = pygame.key.get_pressed()
if keys[K_ESCAPE]:
done = True
Следующее является оберткой класса вокруг одного из вышеупомянутых решений:
#!/usr/bin/env python3
импорт, распараллеливающий
очередь импорта
класс NonBlockingInput:
def __init__(self, exit_condition):
self.exit_condition = exit_condition
self.input_queue = queue.Queue()
self.input_thread = threading.Thread(target=self.read_kbd_input, args=(), daemon=True)
self.input_thread.start()
def read_kbd_input(self):
done_queueing_input = False
while not done_queueing_input:
console_input = input()
self.input_queue.put(console_input)
if console_input.strip() == self.exit_condition:
done_queueing_input = True
def input_queued(self):
return_value = False
if self.input_queue.qsize() > 0:
return_value = True
return return_value
def input_get(self):
return_value = ""
if self.input_queue.qsize() > 0:
return_value = self.input_queue.get()
return return_value
, если имя ==' основной ':
NON_BLOCK_INPUT = NonBlockingInput(exit_condition='quit')
DONE_PROCESSING = False
INPUT_STR = ""
while not DONE_PROCESSING:
if NON_BLOCK_INPUT.input_queued():
INPUT_STR = NON_BLOCK_INPUT.input_get()
if INPUT_STR.strip() == "quit":
DONE_PROCESSING = True
else:
print("{}".format(INPUT_STR))