def parse_arguments():
parser = argparse.ArgumentParser(description='Command Line Arguments',
formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument('-c', '--config', type=str, help='Config file path', default=None)
return parser.parse_args()
if __name__ == "__main__":
# === Command line arguments ===
args = parse_arguments()
if args.config:
CONFIG_PATH = args.config
def init_path(stdscr: curses.window) -> Paths:
global interrupted
# initialize some things here
if initui.interrupted:
interrupted = True
try:
curses.wrapper(init_path)
if not interrupted:
curses.wrapper(main, logger=app_logger)
def main(stdscr: curses.window, logger: Optional[logging.Logger] = None):
# more setup and initialization
if logger:
logger.info("Starting up the application")
ui.ui_loop()
У меня есть TUI-приложение на основе проклятий, которое я запускаю следующим образом: [code]def parse_arguments(): parser = argparse.ArgumentParser(description='Command Line Arguments', formatter_class=argparse.RawTextHelpFormatter) parser.add_argument('-c', '--config', type=str, help='Config file path', default=None) return parser.parse_args()
if __name__ == "__main__": # === Command line arguments === args = parse_arguments() if args.config: CONFIG_PATH = args.config
def init_path(stdscr: curses.window) -> Paths: global interrupted # initialize some things here if initui.interrupted: interrupted = True try: curses.wrapper(init_path) if not interrupted: curses.wrapper(main, logger=app_logger)
def main(stdscr: curses.window, logger: Optional[logging.Logger] = None): # more setup and initialization if logger: logger.info("Starting up the application") ui.ui_loop() [/code] Я могу протестировать пользовательский интерфейс с помощью pyte, используя некоторый код, на который я ссылался из https://mrossinek.gitlab.io/programming/testing-tui-applications-in-python/ : [code]def run_tui_test(screen_file_path, keystrokes, W=80, H=24): # Child process initializes the TUI while parent process sets up virtual screen pid, f_d = os.forkpty() if pid == 0: interrupted = False
def init_path(stdscr: curses.window): global interrupted # initialize some things here if initui.interrupted: interrupted = True
curses.wrapper(init_path) if not interrupted: curses.wrapper(main, logger=None) else: screen = pyte.Screen(W, H) stream = pyte.ByteStream(screen)
# Send keystrokes to TUI for keystroke in keystrokes: # print(f"Sending key: {repr(keystroke)} | Encoded: {keystroke.encode()}") os.write(f_d, keystroke.encode())
# Scrape pseudo-terminal's screen while True: try: [f_d], _, _ = select.select([f_d], [], [], 1) except (KeyboardInterrupt, ValueError): break else: try: # Scrape screen of child process data = os.read(f_d, 1024) stream.feed(data) except OSError: break
# Read expected lines from file with open(screen_file_path, 'r') as file: expected_lines = file.read().split('\n')
# Compare expected lines with screen.display for i, (expected_line, screen_line) in enumerate(zip(expected_lines, screen.display)): screen_line_str = ''.join(screen_line) assert expected_line == screen_line_str, f"Line {i+1} does not match: expected '{expected_line}', got '{screen_line_str}'" [/code] Все это работает хорошо, но... есть ли способ передать аргументы (например, --config) при тестировании TUI?
Я пытался проверить содержимое командной строки после изменения значений argv, обновленные значения не отображаются:
#include
#include
#include
#include
#include
int main(int argc, char*argv[])
{
if (argc < 2) {
printf( Usage: %s arg1 arg2 .....
Я в настоящее время преподаю себе Python и просто задавался вопросом (в связи с моим примером ниже) в упрощенных терминах, что представляет Sys.Argv . Это просто запрашивает вход?
У меня есть std::mutex в родительском процессе. Родительский процесс является ответвлениемдочернего процесса. Дочерний процесс блокируется при получении блокировки. Это может быть связано с тем, что родительский процесс получил блокировку.
Когда я определяю переменную на уровне модуля, запускаю новый подпроцесс и изменяю эту переменную в дочернем процессе, должно ли это изменение быть видимым в родительском процессе? Из моих экспериментов кажется, что ответ нет , но я размышляю, не...