Curses error setupterm could not find terminal

I am trying to get a simple curses script to run using Python (with PyCharm 2.0). This is my script: import curses stdscr = curses.initscr() curses.noecho() curses.cbreak() stdscr.keypad(1) while...

I am trying to get a simple curses script to run using Python (with PyCharm 2.0).

This is my script:

import curses
stdscr = curses.initscr()
curses.noecho()
curses.cbreak()
stdscr.keypad(1)
while 1:
    c = stdscr.getch()
    if c == ord('p'): print("I pressed p")
    elif c == ord('q'): break

curses.nocbreak(); stdscr.keypad(0); curses.echo()
curses.endwin()

When I run this from my IDE (PyCharm 2) I get the following error:


_curses.error: setupterm: could not find terminal
Process finished with exit code 1

If I run the script from bash it will simply be stuck in the while loop not reacting to either pressing p or q.

Any help would be appreciated.

simont's user avatar

simont

66.2k17 gold badges115 silver badges133 bronze badges

asked Feb 28, 2012 at 16:23

user1017102's user avatar

Go to run/debug configuration(the one next to Pycharm run button). Sticking on Emulate Terminal In Output Console. Then you will be able to run your program with the run button.

answered Jan 26, 2018 at 6:46

Trieu Nguyen's user avatar

1

You’ll see this error if you’re using Idle. It’s because of Idle’s default redirection of input/output. Try running your program from the command line. python3 <filename>.py

answered Sep 1, 2019 at 7:42

Clarius's user avatar

ClariusClarius

1,0619 silver badges9 bronze badges

I found this question when searching for examples because I am also learning to use curses so I don’t know much about it. I know this works though:

import curses
try:
    stdscr = curses.initscr()
    curses.noecho()
    curses.cbreak()
    stdscr.keypad(1)
    while 1:
        c = stdscr.getch()
        if c == ord('p'):
            stdscr.addstr("I pressed p")
        elif c == ord('q'): break
finally:
    curses.nocbreak(); stdscr.keypad(0); curses.echo()
    curses.endwin()

I also added the try: finally: to make sure I get the terminal to it’s original appearance even if something simple goes wrong inside the loop.

You have to use the addstr to make sure the text is going to be displayed inside the window.

answered Aug 14, 2013 at 18:44

rui's user avatar

I was having the same problem. See Curses Programming with Python — Starting and ending a curses application.

There’s a curses.wrapper() function that simplifies the process of starting/ending a curses application.

Here’s the example from the Python doc:

from curses import wrapper

def main(stdscr):
    # Clear screen
    stdscr.clear()

    # This raises ZeroDivisionError when i == 10.
    for i in range(0, 11):
        v = i-10
        stdscr.addstr(i, 0, '10 divided by {} is {}'.format(v, 10/v))

    stdscr.refresh()
    stdscr.getkey()

wrapper(main)

answered Jan 14, 2017 at 19:20

Zachary Wilson's user avatar

Zachary WilsonZachary Wilson

1,2241 gold badge8 silver badges4 bronze badges

If you are using macOS and running PyCharm you will have to set environment variables from the IDE itself, for execution scope.

Edit Configurations -> Environment variables

then add the below name-value pairs

TERM linux

TERMINFO /etc/zsh

The above is equivalent to exporting environment variable from the console which is done like this

$ export TERM=linux
$ export TERMINFO=/bin/zsh

the default for TERM is xterm, other values are [konsole, rxvt]
rxvt for example is often built with support for 16 colors. You can try to set TERM to rxvt-16color.

/bin/zsh is path of the terminal application that I use in mac.

It’s like telling your program that you will be logging into linux(TERM) like terminal which can be found at /bin/zsh. For using bash shell it could be something like /bin/bash .

Community's user avatar

answered Aug 17, 2019 at 11:41

hassan_ashraf's user avatar

1

A lot of people have been getting the following error message when using curses in python:

Traceback (most recent call last):
  File "/home/bertil/anaconda3/bin/vd", line 152, in <module>
    main()
  File "/home/bertil/anaconda3/bin/vd", line 130, in main
    vdtui.run(*sources)
  File "/home/bertil/anaconda3/lib/python3.7/site-packages/visidata/vdtui.py", line 2841, in run
    ret = wrapper(cursesMain, sheetlist)
  File "/home/bertil/anaconda3/lib/python3.7/site-packages/visidata/vdtui.py", line 2831, in wrapper
    return curses.wrapper(setupcolors, f, *args)
  File "/home/bertil/anaconda3/lib/python3.7/curses/__init__.py", line 73, in wrapper
    stdscr = initscr()
  File "/home/bertil/anaconda3/lib/python3.7/curses/__init__.py", line 30, in initscr
    fd=_sys.__stdout__.fileno())
_curses.error: setupterm: could not find terminal

I have been able to solve the problem by running:

export TERMINFO=/bin/zsh
export TERM=linux

However, I have to do it every single time I open a new terminal, which gets very annoying in the long run, especially because I look to use tools like visidata a lot (which generated the above error).

I am on Manjaro Linux with i3, and my terminal is urxvt.

I have realized that I only actually need the export TERM=linux part.

I have tried adding it to .profile, butexport TERM=linux it doesn’t help.

Adding export TERM=linux to .bashrc solves the problem, but I am worried about other things not working when changing TERM from the default rxvt-unicode-256color.

Thread Rating:

  • 0 Vote(s) — 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5

Curses could not find terminal

I want to start programming with the module curses in Python on my
Raspberry pi3(with rasbian), But I already ran into a problem.

I wrote my first 2 lines of code in IDLE3 and executed them:

import curses
stdscr = curses.initscreen

but I got this output:

Output:

Traceback (most recent call last): File "/home/pi/Desktop/programms/Tools/curse.py", line 3, in <module> curses.initscr() File "/usr/lib/python3.5/curses/__init__.py", line 30, in initscr fd=_sys.__stdout__.fileno()) _curses.error: setupterm: could not find terminal

I already know that there is the way to execute it in the linux terminal,
but it would be just way to much work if I want to test some code every 10 seconds and I have no Idea how to even do that.
If there is no other way, i’ll do it with the linux terminal, if someone could
explain it to me (please :) ).

Posts: 3,885

Threads: 56

Joined: Jan 2018

Reputation:
307

Jan-04-2018, 04:13 PM
(This post was last modified: Jan-04-2018, 04:13 PM by Gribouillis.)

I don’t think there is a way to do this within IDLE3. When your program runs in Idle, its standard streams are pipes that communicate with Idle’s main program.

What you could do is launch a terminal from your program’s main function, something along the line of:

import curses
import subprocess

def main():
    try:
        scr = curses.initscr()
    except _curses.error:
        subprocess.call(['lxterminal', '--command', 'python', __file__])
    else:
        run_normal_code(scr)

It should be possible to add an option to prevent a fork bomb in case curses.initscr() also fails in the child process. One can use argparse to add an option.

You could also use sys.stdout.fileno() which succeeds in a real terminal but raises io.UnsupportedOperation in IDLE3.

Posts: 17

Threads: 3

Joined: Dec 2017

Reputation:
0

It kinda does exactly nothing. XD
It doesn’t give me an error message but also doesn’t open the terminal.
It should do at least something without the name of the file, right?
(this message should be in no way aggressive. Thank you for your Idea.)

Posts: 3,885

Threads: 56

Joined: Jan 2018

Reputation:
307

The fact is that I don’t yet use Raspberry pi. If you run the command lxterminal in a terminal, does it launch a second terminal? If not, you need to find the command to launch a terminal. This command has an option to start any program within the launched terminal.

Posts: 17

Threads: 3

Joined: Dec 2017

Reputation:
0

I’ve cropped the code but now it just goes crazy.
it keeps opening and closing terminals @[email protected]

import curses
import subprocess
subprocess.call(['lxterminal'])

Posts: 3,885

Threads: 56

Joined: Jan 2018

Reputation:
307

Jan-04-2018, 06:25 PM
(This post was last modified: Jan-04-2018, 06:25 PM by Gribouillis.)

You have launched a fork bomb. You’d better shutdown and reboot. It’s not the three lines you just posted that open and close many terminals. Can you post the real code?

Here is a full code that works for me in linux, but the terminal application is konsole, which has its own options

import argparse
import subprocess
import sys

def main_work(args):
    print('Hello from term-example')

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument(
        '--noterminal',
        help="don't start a new terminal'",
        action='store_true')
    ns = parser.parse_args()
    try:
        sys.stdout.fileno()
    except Exception:
        # not a terminal for sure
        if ns.noterminal:
            raise RuntimeError('Need a terminal to run.')
        else:
            subprocess.call(['konsole', '--noclose', '-e', sys.executable, __file__, '--noterminal'])
    else:
        main_work(ns)

    
if __name__ == '__main__':
    main()

When I run this code in a terminal, it simply executes the code in main_work(). When I run it from IDLE3 by pressing the F5 key, it launches a new console and executes the code from main_work() in this console.

The konsole command has an option --noclose so that it stays here after the execution of
the code. An alternative is to add a command that waits at the end, such as if ns.noterminal: input()

Posts: 17

Threads: 3

Joined: Dec 2017

Reputation:
0

Oh, it didnt liked it.

Output:

Traceback (most recent call last): File "C:UsersHendrikDesktopProgrammierenPython2Calculator.py", line 16, in main sys.stdout.fileno() io.UnsupportedOperation: fileno During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:UsersHendrikDesktopProgrammierenPython2Calculator.py", line 28, in <module> main() File "C:UsersHendrikDesktopProgrammierenPython2Calculator.py", line 22, in main subprocess.call(['konsole', '--noclose', '-e', sys.executable, __file__, '--noterminal']) File "C:UsersHendrikAppDataLocalProgramsPythonPython36-32libsubprocess.py", line 267, in call with Popen(*popenargs, **kwargs) as p: File "C:UsersHendrikAppDataLocalProgramsPythonPython36-32libsubprocess.py", line 709, in __init__ restore_signals, start_new_session) File "C:UsersHendrikAppDataLocalProgramsPythonPython36-32libsubprocess.py", line 997, in _execute_child startupinfo) FileNotFoundError: [WinError 2] Das System kann die angegebene Datei nicht finden

But I have given up by this point.
Thanks for your help, but my system seems too hate curses,
You could say its- «cursed» XD

Posts: 3,885

Threads: 56

Joined: Jan 2018

Reputation:
307

The code needs to be adapted for the Raspbery pi by replacing the konsole command by the terminal command that works on your machine. I think it is lxterminal but you need to find the correct way to call it yourself. This has nothing to do with curses.

Posts: 17

Threads: 3

Joined: Dec 2017

Reputation:
0

I have tried it with lxterminal, but nothing happened.
I tried lxterminal in the terminal, and it worked.
That means it is the right terminal, right?

Posts: 3,885

Threads: 56

Joined: Jan 2018

Reputation:
307

Jan-05-2018, 03:28 PM
(This post was last modified: Jan-05-2018, 03:28 PM by Gribouillis.)

I think what may happen is that the lxterminal closes immediately after the program exits. You could try

import argparse
import subprocess
import sys
import traceback
 
def main_work(args):
    print('Hello from term-example')
 
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument(
        '--noterminal',
        help="don't start a new terminal'",
        action='store_true')
    ns = parser.parse_args()
    try:
        sys.stdout.fileno()
    except Exception:
        # not a terminal for sure
        if ns.noterminal:
            raise RuntimeError('Need a terminal to run.')
        else:
            subprocess.call(['lxterminal', '-e', '{} {} --noterminal'.format(sys.executable, __file__)])
    else:
        try:
            main_work(ns)
        except Exception:
            if ns.noterminal:
                traceback.print_exc()
                input()# <---- this is to prevent the program to end and close the terminal
            else:
                raise
        else:
            if ns.noterminal:
                input() # <---- this is to prevent the program to end and close the terminal
     
if __name__ == '__main__':
    main()

Also you can try to run directly this command in a terminal to see if it says anything (this is not python):

lxterminal -e "python3 Calculator.py --noterminal"

Edit: I installed lxterminal in my kubuntu system and the above code works!
Edit: Support added for holding the terminal if the program fails (with exception).

Possibly Related Threads…
Thread Author Replies Views Last Post
  curses issue otalado 2 1,791 Jun-29-2021, 02:07 PM
Last Post: tmz
  How to make curses.border() use A_BOLD atttribute? pjfarley3 0 2,672 Feb-03-2021, 11:22 PM
Last Post: pjfarley3
  Curses script doesn’t work wavic 1 2,870 Jan-08-2021, 09:11 PM
Last Post: wavic
  Why aren’t all curses panel functions supported in python curses.panel? pjfarley3 2 1,824 Jul-22-2020, 11:08 PM
Last Post: pjfarley3
  curses library autompav96 2 2,209 Mar-02-2019, 02:12 AM
Last Post: woooee
  curses key codes not working jgrillout 0 2,367 Feb-11-2019, 01:46 AM
Last Post: jgrillout
  Pretty table and curses? MuntyScruntfundle 0 2,301 Oct-16-2018, 10:22 AM
Last Post: MuntyScruntfundle
  curses.initscr doesn’t work zaphod424 3 8,374 Feb-28-2018, 12:36 PM
Last Post: Gribouillis

I am developing a python application for a remote system which has a device connected via a serial port.

At the moment my workflow looks like this

  • write code locally
  • commit to git
  • git push
  • change to terminal window holding ssh session
  • git pull
  • run python code

This is kind of awkward and I want to speed things up and increase my work efficiency using some scripts

I have written two scripts, one for local and one for remote

My local script looks like this

#!/bin/bash

# do git commit
if [ "$#" -eq 3 ]
then
    if [ "$1" == "-m" ]
    then
        git commit -am "$2"
    else
        echo "syntax error, -m expected as argument 1"
        exit
    fi
else
    git commit -am "execute.sh script"
fi

# do git push
git push

# login to ssh and execute script
ssh <user>@<ip> 'bash -s' < remote-execute.sh

My remote-execute.sh looks like this

#!/bin/bash

# cd
cd <dir>

# do git pull
git pull

# run python
python3 main.py

My python code uses Python Curses (ncurses) for GUI interaction

When I run these scripts, I encounter the error

Traceback (most recent call last):
  File "Monitor.py", line 1140, in <module>
    curses.wrapper(main)
  File "/usr/lib/python3.5/curses/__init__.py", line 73, in wrapper
    stdscr = initscr()
  File "/usr/lib/python3.5/curses/__init__.py", line 30, in initscr
    fd=_sys.__stdout__.fileno())
_curses.error: setupterm: could not find terminal

This must be due to how I am using ssh with the «-s» switch to execute the remote script.

Is there a way to fix this? It seems like some kind of terminal stuff isn’t being forwarded properly? I can’t say anything more than this because it’s a bit beyond my knowledge.

Я пытаюсь получить простые проклятия script для запуска с использованием Python (с PyCharm 2.0).

Это мой script:

import curses
stdscr = curses.initscr()
curses.noecho()
curses.cbreak()
stdscr.keypad(1)
while 1:
    c = stdscr.getch()
    if c == ord('p'): print("I pressed p")
    elif c == ord('q'): break

curses.nocbreak(); stdscr.keypad(0); curses.echo()
curses.endwin()

Когда я запускаю это из своей IDE (PyCharm 2), я получаю следующую ошибку:


_curses.error: setupterm: could not find terminal
Process finished with exit code 1

Если я запустил script из bash, он просто застрял бы в цикле while, не реагируя на нажатие p или q.

Любая помощь будет оценена.

28 фев. 2012, в 18:10

Поделиться

Источник

4 ответа

Я нашел этот вопрос при поиске примеров, потому что я также научился использовать проклятия, поэтому я мало знаю об этом. Я знаю, что это работает, хотя:

import curses
try:
    stdscr = curses.initscr()
    curses.noecho()
    curses.cbreak()
    stdscr.keypad(1)
    while 1:
        c = stdscr.getch()
        if c == ord('p'):
            stdscr.addstr("I pressed p")
        elif c == ord('q'): break
finally:
    curses.nocbreak(); stdscr.keypad(0); curses.echo()
    curses.endwin()

Я также добавил попытку: наконец: чтобы убедиться, что я получаю терминал к этому оригинальному виду, даже если что-то просто не получается внутри цикла.

Вы должны использовать addstr, чтобы убедиться, что текст будет отображаться внутри окна.

rui
14 авг. 2013, в 18:46

Поделиться

Перейдите в конфигурацию запуска/отладки (рядом с кнопкой запуска Pycharm). Наложение на эмуляцию терминала в выходной консоли. Затем вы сможете запустить свою программу с помощью кнопки запуска.

Trieu Nguyen
26 янв. 2018, в 08:37

Поделиться

У меня была такая же проблема. См. Программирование Curses с помощью Python — запуск и завершение приложения curses.

Здесь есть функция curses.wrapper(), которая упрощает процесс запуска/завершения приложения curses.

Вот пример из документа Python:

from curses import wrapper

def main(stdscr):
    # Clear screen
    stdscr.clear()

    # This raises ZeroDivisionError when i == 10.
    for i in range(0, 11):
        v = i-10
        stdscr.addstr(i, 0, '10 divided by {} is {}'.format(v, 10/v))

    stdscr.refresh()
    stdscr.getkey()

wrapper(main)

Zachary Wilson
14 янв. 2017, в 20:52

Поделиться

Ещё вопросы

  • 0Хранение идентификаторов таблиц внутри другой таблицы для последующего извлечения данных
  • 0Невозможно получить непрочитанные письма из почтового ящика office365 с помощью функции PHP imap_headers ()
  • 0Как загрузить и вставить несколько изображений в PHP?
  • 0IE8 $ (‘body’). Width () = 0 при перерисовке
  • 0jqGrid Редактирование нескольких строк не сохраняется в базе данных в iOS7
  • 0Установите переменные по умолчанию в функциях MySQL, если значения не верны
  • 0Как отсортировать вектор <pair <int, pair <int, pair <string, pair <int, int>>>>>?
  • 0fsockopen () возвращает разные значения на локальном хосте и сервере www
  • 1Проблема в разборе JSON String
  • 1Найти минимум без нуля и NaN в Pandas Dataframe
  • 0Как использовать форматтер / парсеры директивы ngModel в пользовательской директиве?
  • 1Сообщение SignalR не работает при отправке со стороны сервера клиенту
  • 0Ошибка почтовой программы PHPMAILER: сбой подключения SMTP () (нет доступа к Php.ini)
  • 0Создать поддомен с помощью cpanel api
  • 1Заменить подстроку внутри строки новым GUID для каждой найденной подстроки
  • 1Могу ли я установить значение по умолчанию для StringField вне конструктора поля?
  • 0Один ng-options зависит от того, что выбрано в другом — AngularJS
  • 1Используя fetch для получения данных из API, как получить доступ к данным после разрешения обещания?
  • 0Поверните это изображение на клик — JQuery
  • 1Android: Как определить, что активность уходит в фон?
  • 0код для захвата pointcloud из kinect не работает
  • 0Автозаполнение jQuery UI плагин с JSP и сервлетов не работает
  • 1Как получить уверенность в гипотезе результата Sphinx4?
  • 0Попытка выяснить, есть ли лучший способ структурировать этот запрос с помощью объединений
  • 1Хранимая процедура CLR возвращает SqlDataReader, но тип метода void
  • 0Подсчитайте, сколько Array в JSON
  • 1Превратить массив слов из документа с их координатами в предложения
  • 0Массив фильтров во втором контроллере
  • 0Добавить ссылку в даты DatePicker
  • 0Получить QImage или QPixmap из QStandardItemModel — TableView
  • 0CodeIgniter не загружает загружаемую библиотеку
  • 0Страница загрузки для углового разрешения
  • 0Проверка достоверности: уникальный параметр, 4-й параметр
  • 1Я получаю исключение IndexOutOfBoundsException с моим массивом, что я делаю не так?
  • 1Импортировать проблемную таблицу «hibernate_sequence» с Generation.type
  • 1rxjs / redux observable Действия, отправляемые в неправильном порядке при запуске нескольких тестов
  • 0переменная сфера в угловой службе
  • 0Могу ли я иметь HA MySQL / MariaDB Slave?
  • 1концентрические излучающие круги d3
  • 1Элемент не активен, так как другой элемент скрывает его в python
  • 0Почему первая вкладка размещена неправильно?
  • 0Я использую Xercesc для анализа XML-документа. я хотел знать, как я собираюсь использовать значения XML в качестве входных данных для моей программы?
  • 0MYSQL LEFT JOIN 3 таблицы (1-я таблица возвращает пустые значения)
  • 0Разбить строку с координатами в широту / долготу в MySQL
  • 1Как я могу сделать этот Observable более пригодным для повторного использования?
  • 1c # winforms -Pass параметр между модальными формами
  • 0Использование std :: begin (collection) против collection.begin () в C ++
  • 0Как вставить автоматически увеличенный идентификатор поля mysql в php и обновить идентификатор одной таблицы в другую?
  • 1Выполнить файл Python из другого каталога
  • 1Предел глубины рекурсии для программы Фибоначчи на Python

Сообщество Overcoder

I am trying to get a simple curses script to run using Python (with PyCharm 2.0).

This is my script:

import curses
stdscr = curses.initscr()
curses.noecho()
curses.cbreak()
stdscr.keypad(1)
while 1:
    c = stdscr.getch()
    if c == ord('p'): print("I pressed p")
    elif c == ord('q'): break

curses.nocbreak(); stdscr.keypad(0); curses.echo()
curses.endwin()

When I run this from my IDE (PyCharm 2) I get the following error:


_curses.error: setupterm: could not find terminal
Process finished with exit code 1

If I run the script from bash it will simply be stuck in the while loop not reacting to either pressing p or q.

Any help would be appreciated.


You must set enviroment variables TERM and TERMINFO, like this:

export TERM=linux
export TERMINFO=/etc/terminfo

And, if you device have no this dir (/etc/terminfo), make it, and copy terminfo database.

For «linux», and «pcansi» terminals you can download database:

  • http://forum.xda-developers.com/attachment.php?attachmentid=2134052&d=1374459598
  • http://forum.xda-developers.com/showthread.php?t=552287&page=4

Понравилась статья? Поделить с друзьями:
  • Current thread is not owner java как исправить
  • Current running mode как исправить
  • Cx freeze python error in main script ansys
  • Current pending sectors victoria как исправить
  • Current pending errors count как исправить hddscan