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
66.2k17 gold badges115 silver badges133 bronze badges
asked Feb 28, 2012 at 16:23
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
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
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
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 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 .
answered Aug 17, 2019 at 11:41
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 I wrote my first 2 lines of code in IDLE3 and executed them: import curses stdscr = curses.initscreen but I got this output:
I already know that there is the way to execute it in the linux terminal, Posts: 3,885 Threads: 56 Joined: Jan 2018 Reputation: Jan-04-2018, 04:13 PM 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 You could also use Posts: 17 Threads: 3 Joined: Dec 2017 Reputation:
It kinda does exactly nothing. XD Posts: 3,885 Threads: 56 Joined: Jan 2018 Reputation:
The fact is that I don’t yet use Raspberry pi. If you run the command Posts: 17 Threads: 3 Joined: Dec 2017 Reputation:
I’ve cropped the code but now it just goes crazy. import curses import subprocess subprocess.call(['lxterminal']) Posts: 3,885 Threads: 56 Joined: Jan 2018 Reputation: Jan-04-2018, 06:25 PM 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 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 The Posts: 17 Threads: 3 Joined: Dec 2017 Reputation: Oh, it didnt liked it.
But I have given up by this point. Posts: 3,885 Threads: 56 Joined: Jan 2018 Reputation:
The code needs to be adapted for the Raspbery pi by replacing the Posts: 17 Threads: 3 Joined: Dec 2017 Reputation:
I have tried it with lxterminal, but nothing happened. Posts: 3,885 Threads: 56 Joined: Jan 2018 Reputation: Jan-05-2018, 03:28 PM 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! |
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
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