How to use pygame to display something via HDMI on /dev/fb0 (using raspian OS lite) - pygame

I'm trying to get pygame to send anything to the framebuffer /dev/fb0 on a raspberry pi running the lite version of raspbian. I'm connected via ssh, the image should show up on the HDMI output.
I can send something to /dev/fb0 which shows up
sudo fbi -T 1 1.jpg
sends an image file, that I can see on the monitor
while true; do sudo cat /dev/urandom > /dev/fb0; sleep .01; done
sends white noise.
How do I connect pygame to "/dev/fb0"?
I tried many examples, but none work.
For example this code gives me a error
import os, pygame, time
def setSDLVariables(driver):
print("Setting SDL variables...")
os.environ["SDL_FBDEV"] = "/dev/fb0"
os.environ["SDL_VIDEODRIVER"] = driver
print("...done")
def printSDLVariables():
print("Checking current env variables...")
print("SDL_VIDEODRIVER = {0}".format(os.getenv("SDL_VIDEODRIVER")))
print("SDL_FBDEV = {0}".format(os.getenv("SDL_FBDEV")))
setSDLVariables('fbcon')
printSDLVariables()
try:
pygame.init()
except pygame.error:
print("Driver '{0}' failed!".format(driver))
size = (pygame.display.Info().current_w, pygame.display.Info().current_h)
print("Detected screen size: {0}".format(size))
returns
pi#raspberrypi:~/pve_img $ sudo python3 pg.py
pygame 2.1.2 (SDL 2.0.14, Python 3.9.2)
Hello from the pygame community. https://www.pygame.org/contribute.html
Setting SDL variables...
...done
Checking current env variables...
SDL_VIDEODRIVER = fbcon
SDL_FBDEV = /dev/fb0
Traceback (most recent call last):
File "/home/pi/pve_img/pg.py", line 22, in <module>
size = (pygame.display.Info().current_w, pygame.display.Info().current_h)
pygame.error: video system not initialized
Any hints on running pygame with a frame buffer in 2021?

The solution:
I had installed pygame using pip.
sudo python3 -m pip install pygame
Uninstalling pygame and the installing pygame differently
sudo apt-get install python3-pygame
I can then send things to the screen. Example
screen = pygame.display.set_mode(size )
clock = pygame.time.Clock()
for x in range(20):
screen.fill((0, 0, 0))
pygame.display.flip()
clock.tick(1)
screen.fill((200, 200, 0))
pygame.display.flip()
clock.tick(1)
installs a version that works with the above code.

Related

pygame py2app Library not loaded: #loader_path/.dylibs/libSDL-1.2.0.dylib

I wouldn't call myself a programmer and am unfamiliar with Mac and Linux, so any links or pointers to additional background would help greatly. I've started with the most basic pygame I could google, (from https://realpython.com/pygame-a-primer/). The test.py and test.app runs on my VM but not on anyone else's real Macs.
test.py file
import pygame
pygame.init()
screen = pygame.display.set_mode((400, 300))
done = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
pygame.display.flip()
setup.py file
from setuptools import setup
APP = ['test.py']
DATA_FILES = []
OPTIONS = {}
setup(
app=APP,
data_files=DATA_FILES,
options={'py2app': OPTIONS},
setup_requires=['py2app'],
)
command to create the test.app
$ python3 setup.py py2app
The test.app runs fine on the VM, but whenever the test.app runs on a real Mac (tested 2, one ran on Catalina ver???) this error message appears:
Traceback (most recent call last):
File "/Applications/test.app/Contents/Resources/__boot__.py", line 101, in <module>
_run()
File "/Applications/test.app/Contents/Resources/__boot__.py", line 84, in _run
exec(compile(source, path, "exec"), globals(), globals())
File "/Applications/test.app/Contents/Resources/test.py", line 1, in <module>
import pygame
File "pygame/__init__.pyc", line 120, in <module>
File "pygame/base.pyc", line 14, in <module>
File "pygame/base.pyc", line 10, in __load
File "imp.pyc", line 343, in load_dynamic
ImportError: dlopen(/Applications/test.app/Contents/Resources/lib/python3.7/lib-dynload/pygame/base.so, 2): Library not loaded: #loader_path/.dylibs/libSDL-1.2.0.dylib
Referenced from: /Applications/test.app/Contents/Resources/lib/python3.7/lib-dynload/pygame/base.so
Reason: image not found
2020-05-02 11:27:50.309 test[931:15836] test Error
----------------------------
Working environment: VirtualBox 6.1, macOS Sierra (Version 10.12) with the following:
$ pip list
Package Version
----------- ----------
altgraph 0.17
certifi 2020.4.5.1
macholib 1.14
modulegraph 0.18
pip 20.1
py2app 0.21
pygame 1.9.6
setuptools 39.0.1
wheel 0.34.2
$ brew list --versions
freetype 2.10.1
gdbm 1.18.1
jpeg 9d
libmikmod 3.3.11.1
libogg 1.3.4
libpng 1.6.37
libtiff 4.1.0
libvorbis 1.3.6
openssl#1.1 1.1.1g
pkg-config 0.29.2_3
python 3.7.7
readline 8.0.4
sdl 1.2.15_1
sdl2 2.0.12_1
sdl_image 1.2.12_7
sdl_mixer 1.2.12_3
sdl_ttf 2.0.11_1
sqlite 3.31.1
webp 1.1.0
xz 5.2.5
Any ideas or pointers would be greatly appreciated. The actual program is an OhHell card game which supports Windows clients (via pyinstaller), but I'm also trying to support a Mac client to play with my friends on a Mac. Similar to the test.py and test.app (ohhell.py and ohhell.app) runs on the VM Mac but same issue/error occurs with real macs. I've just included the simplest code snippet that I was able to google that reproduced the exact error message.
-john
Workaround Solution: Linking to a dynamic library on a Mac with full path and What path does #loader_path resolve to?. Using the '$ install_name_tool -change "#loader_path/.dylibs/libSDL-1.2.0.dylib" "/Applications/test.app/Contents/Frameworks/libSDL-1.2.0.dylib" base.so' resolved the Library not loaded: loader_path/.dylibs/libSDL-1.2.0.dylib errors. I assume this hard codes the path, but with my friends it's fine to tell them to make sure it resides in the /Applications folder.
However a secondary problem came up, 'pygame.error: File is not a Windows BMP file'. I used py2app, so the pygame delete and reinstall threads didn't seem like a feasible solution (pygame unnecesary w/py2app), so switching the images to uncompressed bitmap (256 colors) worked.
For those curious, I did try Pyinstaller for Mac but that presented a whole new set of problems.

cant install pygame in pycharm

First of all, I'm new to programming. So,forgive me for my mistakes. I've installed pygame in python IDLE. But when I try to install it in pycharm, this happens:
Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation. All rights reserved.
(venv) C:\Users\ARMAN\PycharmProjects\GAMES>pip install pygame
Collecting pygame
Using cached https://files.pythonhosted.org/packages/0f/9c/78626be04e193c0624842090fe5555b3
Complete output from command python setup.py egg_info:
WARNING, No "Setup" File Exists, Running "buildconfig/config.py"
Using WINDOWS configuration...
Download prebuilts to "prebuilt_downloads" and copy to "./prebuilt-x86"?[Y/n]Traceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\Users\ARMAN\AppData\Local\Temp\pip-install-5f1r3j6w\pygame\setup.py", line 194, in <module>
buildconfig.config.main(AUTO_CONFIG)
File "C:\Users\ARMAN\AppData\Local\Temp\pip-install-5f1r3j6w\pygame\buildconfig\config.py", line 210, in main
deps = CFG.main(**kwds)
File "C:\Users\ARMAN\AppData\Local\Temp\pip-install-5f1r3j6w\pygame\buildconfig\config_win.py", line 576, in main
and download_win_prebuilt.ask(**download_kwargs):
File "C:\Users\ARMAN\AppData\Local\Temp\pip-install-5f1r3j6w\pygame\buildconfig\download_win_prebuilt.py", line 302, in ask
reply = raw_input(
EOFError: EOF when reading a line
----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in C:\Users\ARMAN\AppData\Local\Temp\pip-install-5f1r3j6w\pygame\
(venv) C:\Users\ARMAN\PycharmProjects\GAMES>py -m pip install -U pygame --user
Collecting pygame
Using cached https://files.pythonhosted.org/packages/0f/9c/78626be04e193c0624842090fe5555b3805c050dfaa81c8094d6441db2be/pygame-1.9.6.tar.gz
Complete output from command python setup.py egg_info:
WARNING, No "Setup" File Exists, Running "buildconfig/config.py"
Using WINDOWS configuration...
Download prebuilts to "prebuilt_downloads" and copy to "./prebuilt-x86"? [Y/n]Traceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\Users\ARMAN\AppData\Local\Temp\pip-install-nykuwxyw\pygame\setup.py", line 194, in <module>
buildconfig.config.main(AUTO_CONFIG)
File "C:\Users\ARMAN\AppData\Local\Temp\pip-install-nykuwxyw\pygame\buildconfig\config.py", line 210, in main
deps = CFG.main(**kwds)
File "C:\Users\ARMAN\AppData\Local\Temp\pip-install-nykuwxyw\pygame\buildconfig\config_win.py", line 576, in main
and download_win_prebuilt.ask(**download_kwargs):
File "C:\Users\ARMAN\AppData\Local\Temp\pip-install-nykuwxyw\pygame\buildconfig\downloa
reply = raw_input(
EOFError: EOF when reading a line
----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in C:\Users\ARMAN\AppData\Local\T
(venv) C:\Users\ARMAN\PycharmProjects\GAMES>
I get an error. I've updated everything. Found a similar problem here:
https://intellij-support.jetbrains.com/hc/en-us/community/posts/115000435070-Command-python-setup-py-egg-info-failed-with-error-code-1-whatever-package-I-try-to-install-.
But I can't understand the solution. So, please kindly help me.
This isn't my answer, but an answer from here:
Pygame docs recommends that you use Python version 3.6.1 or greater,
so I would suggest you to use the most recent non-beta version. Also,
some pygame wheels are not available to this version yet.
After the python installation make sure its added to your PATH
variable and try to install Pygame using this command given that you
are on windows:
py -m pip install -U pygame --user
If you get a PermissionError then
run the command prompt as administrator.
I hope this helps.

falcon gunicorn ImportError: No module named hparams

I have already been working on a source that I have already created using gunicorn and nginx so that multiple people can access it without any problems.
Previously, falcon was running as a .py, but https://www.digitalocean.com/community/tutorials/how-to-deploy-falcon-web-applications-with-gunicorn-and-nginx-on-ubuntu-16-04
There was a problem while referring to site
my program's name is demo_server.py
and that code includes
import argparse
import falcon
from hparams import hparams, hparams_debug_string
import os
from synthesizer import Synthesizer // model (train model)
and when I type like these
gunicorn -b localhost: 5000 demo: app --reload
, The following error appears.
Failed to read config file: demo_server.py Traceback (most recent call
last):   File
"/data/falcon_app/venv/lib/python3.5/site-packages/gunicorn/app/base.py",
line 93, in get_config_from_filename
    execfile_ (filename, cfg, cfg)   File "/data/falcon_app/venv/lib/python3.5/site-packages/gunicorn/compat.py",
line 72, in execfile
    return six.exec_ (code, * args)   File "demo_server.py", line 3, in
    from hparams import hparams, hparams_debug_string ImportError: No module named 'hparams'
How do I resolve this ImportError?
Thanks..
Most probably you have installed gunicorn which corresponds to python2.7 on your local machine and you had to use python3.x which contains site-packages to run your falcon application.
Try install gunicorn3
sudo apt install gunicorn3
and then
gunicorn3 demo_server:app
worked for me

Getting Error while building mysql for python on Mac OS X El Capitan

I read some of the related topics and tried to implement those solutions to my situation but still I get the following error after this command :
(project2_env) Efe-MacBook-Air:MySQL-python-1.2.4b4 efe$ python setup.py build
The Error message is :
Extracting in /var/folders/rv/vbf7xqh1601_xjkrn85w7hp00000gn/T/tmpptpsggg7
Traceback (most recent call last):
File "/Users/efe/virtualenvs/downloads/MySQL-python-1.2.4b4/distribute_setup.py", line 143, in use_setuptools
raise ImportError
ImportError
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "setup.py", line 7, in <module>
use_setuptools()
File "/Users/efe/virtualenvs/downloads/MySQL-python-1.2.4b4/distribute_setup.py", line 145, in use_setuptools
return _do_download(version, download_base, to_dir, download_delay)
File "/Users/efe/virtualenvs/downloads/MySQL-python-1.2.4b4/distribute_setup.py", line 125, in _do_download
_build_egg(egg, tarball, to_dir)
File "/Users/efe/virtualenvs/downloads/MySQL-python-1.2.4b4/distribute_setup.py", line 99, in _build_egg
_extractall(tar)
File "/Users/efe/virtualenvs/downloads/MySQL-python-1.2.4b4/distribute_setup.py", line 486, in _extractall
self.chown(tarinfo, dirpath)
TypeError: chown() missing 1 required positional argument: 'numeric_owner'
Edit: I reinstalled homebrew, then I run this following command. That is successfully installed.
brew install mysql
However, I cannot still import MySQLdb in python.
As it is more complicated than the previous answer, i won't told you about the custom installation of python mysql.
Found this, the Jude's way :
Install mysql via homebrew, then you can install mysql python via pip.
xcode-select --install
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
//don't know how to install mysql via homebrew, but it should be done here
pip install MySQL-python
https://stackoverflow.com/a/25356073/6660122
Taken from the Python2 doc, still relevant in 3.5 :
"Alternate installation: the user scheme
This scheme is designed to be the most convenient solution for users that don’t have write permission to the global site-packages directory or don’t want to install into it. It is enabled with a simple option: "
python setup.py install --user
Could help in your case.
Notice there are different scheme to use : --home, or --prefix and --exec-prefix, or --install-base and --install-platbase
Finally I found a solution for myself and by myself. I gave up using directly MySQLdb library and instead of that, I installed PyMySQL. By the way I had already installed MySQL Workbench before, so mysql server was already running.
Here is what I do step by step. I hope someone can get benefit from it.
1) Create a virtual environment:
virtualenv virt1
2) Make your virtual environment activated:
source virt1/bin/activate
3) Now, you are in your virtual environment. Install PyMySQL:
pip install PyMySQL
4) Now, try whether your MySQL connection is OK or not with a simple py executable:
#!/usr/bin/python
import pymysql.cursors
# Connect to the database
connection = pymysql.connect(host='localhost',
user='YourDBuserName',
password='YourDBpassword',
db='YourDBname',
charset='utf8',
cursorclass=pymysql.cursors.DictCursor)
try:
with connection.cursor() as cursor:
# Read a single record
sql = "SELECT `id`, `name` FROM `YourTableName` WHERE `id`=%s"
cursor.execute(sql, (1,))
result = cursor.fetchone()
print(result)
finally:
connection.close()
5) You should see that your first row from the table appears on the screen.
Note: The part "import pymysql.cursors" could be tricky. First, I wrote as "import PyMySQL.cursors" and that didn't work!

I get an error message when I try FreqDist() in NLTK -- NameError: name 'nltk' is not defined

I'm learning about the NLTK and my mac
is working fine except I have trouble with the FreqDist(). (I saw another question about FreqDist() but he was getting a different error message. TypeError: unhashable type: 'list')
Here's an example:
>>> from nltk.corpus import brown
>>> news_text = brown.words(categories='news')
>>> fdist = nltk.FreqDist([w.lower() for w in news_text])
Traceback (most recent call last):
` File "<stdin>", line 1, in <module>`
`NameError: name 'nltk' is not defined`
This error message is pretty consistent. I get this message every time I try the FreqDist(). Other commands like - >>> brown.fileids() are fine.
Thanks for your help!
Before you can use FreqDist, you need to import it.
Add a line as follows:
import nltk
or if you just want to use FreqDist you should try this:
>>> from nltk.corpus import brown
>>> from nltk import FreqDist
>>> news_text = brown.words(categories='news')
>>> fdist = FreqDist([w.lower() for w in news_text])
which means you haven't installed nltk.
follow these steps to install nltk:
1:go to this link https://pypi.python.org/pypi/setuptools at the end of page you find setuptools-7.0.zip (md5) download it, then unzip it. you can find easy_install.py python script.
2:use the command sudo easy_install pip. By this time pip will be installed ready to use, (make sure you are in the directory where you can find easy_install script file).
3:use this command sudo pip install -U nltk. successful execution ensure that nltk is now installed.
4:open the IDLE then you type the following:
import nltk
if nltk is installed properly then you will be returned with console.
setuptools are required for older versions of Python. There is no need for the same if you are running 3.2+
You can easily download the same from https://pypi.python.org/pypi/nltk
For more information on http://www.nltk.org/install.html
nltk requires data you need to download first.
Then run the following code:
import nltk
nltk.download('stopwords')
from nltk.corpus import stopwords
stopwords.words("english")