module(sys) sys is not accessed pylance - python

I'm learning python with the book python crash course , i wrote the code for the game alien invasion , but it is not working , when i write "import sys" , the word sys is underscore and the program opens up the screen for like a millisecond and then it closes itself, i look for an answer in this site and YouTube and i haven't been able to find a solution, can anyone help? thanks in advance.
I'm using vs code on Linux mint.
this is what i wrote so far:
from settings import Settings
from ship import Ship
import sys
class AlienInvasion:
"""overall class to manage game assets and behavior"""
def __init__(self):
""" initialize the game and creates game resources"""
pygame.init()
self.settings = Settings()
self.screen = pygame.display.set_mode(
(self.settings.screen_width, self.settings.screen_height))
pygame.display.set_caption("Alien Invasion")
self.ship = Ship(self)
def run_game(self):
"""start the main loop for the game."""
while True:
self._check_events()
#whatch for keyboard and mouse events .
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
#redraw the screen during each pass through the loop.
self.screen.fill(self.settings.bg_color)
self.ship.blitme()
#make the most recently drawn screen visible.
pygame.display.flip()
if __name__ == '__main__':
#make a game instance, and run the game.
ai = AlienInvasion()
ai.run_game()

It looks like there's probably an error being thrown somewhere in your script that is causing the program to stop running, and as such, close the terminal as soon as it is opened. In my experience, this only happens when you execute the script from a file browser UI by double-clicking it.
To fix this, try running the program from somewhere that will stay open, even when the program is terminated, like, for example, the built-in terminal in vscode (you can reveal by going to view > terminal). To run the program, then simply run the command:
python path/to/my/script.py
If it causes an error, you will then be able to see it printed nicely, without the terminal closing.
On another note, importing sys has nothing to do with this problem. The reason it is highlighted by pylance is that you have imported it, but then you haven't used it anywhere (for example calling a function like sys.exit()), so it thinks that the line is unnecessary. It will go away once you use the sys module somewhere else in the script.

According to your error content, I think this is caused by the fact that the file is not found, meanwhile sys is not used in your code.
Here are some reasons caused "FileNotFoundError", you could confirm one by one:
1. File name and file type
The wrong file name was inserted into the code. Please carefully check the document name.
2. Escape of Python string
In the string of file, the address string information similar to C:\user\desktop will be involved, which conflicts with the escape function in Python string, such as \n representing line feed. Use r"C:\User\Desktop" or C:\\User\\Desktop to avoid Python escaping strings.
3. Relative path problem
Generally, it is not recommended to use. In the process of Python running, the relative path is the folder that the process points to when running, and the folder is used as the file tree of the root node, that is, if you open the file by using the relative path, you can only access the file under its root node.
You could use the methods os.path.abspath() and os.path.abspath('..') provided in the OS library to view and change the absolute path where Python runs.
4. Python runtime location
If it is such a problem, you can add the following code to the head of the file:
import sys
sys.path.append("../your/target/path/")

try pip install os-sys and pip install syspath
enter link description here

Related

pygame window takes forever to start

So I'm following the alien invasion project from python crash course, at the beginning the book teaches how to open a simple window with a specific background color. I literally copy-pasted the code from the book and it still does not work.
import pygame
import sys
from settings import Settings
def run_game():
# Initialize game and create a screen object.
pygame.init()
# Init settings
my_settings = Settings()
screen = pygame.display.set_mode((my_settings.screen_widht, my_settings.screen_height))
pygame.display.set_caption("Alien Invasion")
# Start the main loop for the game.
while True:
# Watch for keyboard and mouse events.
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
# Redraw the screen during each pass through the loop.
screen.fill(my_settings.bg_color)
# Make the most recently drawn screen visible.
pygame.display.flip()
run_game()
EDIT: To clarify, I'm not saying the code doesn't work, it works without errors but takes a minute to open... it's something with my system, but I don't know what it is, that's why I'm asking
Edit2: I realized that if I remove pygame.init() the window opens instantly, not sure what it means
pygame.init() initializes all pygame modules. This may take some time on some systems. If you don't need all pygame modules, just leave it out. For the display and event handling it is not necessary to call pygame.init() at all. If you need other modules, you can itialize them separately (e.g. pygame.font.init(), pygame.mixer.init()).
See pygame.init()
Initialize all imported pygame modules. No exceptions will be raised if a module fails, but the total number if successful and failed inits will be returned as a tuple. You can always initialize individual modules manually, but pygame.init()initialize all imported pygame modules is a convenient way to get everything started. The init() functions for individual modules will raise exceptions when they fail.
You may want to initialize the different modules separately to speed up your program or to not use modules your game does not require.

Python Os function called from Tkinter does not work when converted to .exe

Need your help lads and lasses!
I made a very simple hangman game with a GUI in Tkinter and created a button event that calls the following function to restart the game. This works fine as a Python script but does not work when converting script to .exe with Pyinstaller. ('Window" here is the root Tkinter window)
def restart_func():
window.destroy()
os.startfile("main.py")
return
Any ideas why or alternative way of doing this would be much appreciated.
you should recreate your window and initialize it the same way you originially did.
def restart_func():
global window
window.destroy()
window = tk.Tk()
run_gui_initialization_function()
this is usually why some applications prefer OOP instead of functional programming, as there is usually no global state in OOP programming, while for functional programming, your run_gui_initialization_function should reinitialize all of your global state variables again.
an alternative way people do this is as follows
def main():
# do main app here
if __name__ == "__main__":
main()
this way you just need to run main() again after deleting your window if you ever need to restart your app.
Edit: okay, here's an easier to implement but too messy way to do this, you can start a detached version of your application from your executable ... but this is the wrong way to restart an application, and it might fail in some cases.
from subprocess import Popen
import sys
def restart_func():
window.destroy()
if getattr(sys, 'frozen', False) and hasattr(sys, '_MEIPASS'):
Popen(sys.executable,start_new_session=True) # if running as executable
else:
os.startfile("main.py") # if running as python script

Integrate Pygame in PySimpleGUI

I have a game written with a Pygame loop and it currently draws everything happening in the pygame window. I now want to integrate this window into a larger PySimpleGUI window to have nice functionality around the game. Is this possible?
I tried to use the code from here. The problem is that I get an error like this which comes from VIDEODRIVER at line 25:
pygame.error: windib not available
I changed this to 'windows' but then the Pygame window is separated from the PySimpleGUI as a different window.
Can I make the pygame loop as a window INSIDE the PySimpleGUI? Thank you.
It looks like the detached window is an open, unresolved issue with pygame 2.
If you're able to downgrade to pygame 1.9.6, the linked demo works as expected on Windows after changing the line 25 to:
os.environ['SDL_VIDEODRIVER'] = 'windows' as described.
As said there,
This line only work on windows:
os.environ['SDL_VIDEODRIVER'] = 'windib'
So make a code to skip it when the os is not Windows.
import platform
if platform.system == "Windows":
os.environ['SDL_VIDEODRIVER'] = 'windib'

Starting a pygame/python script over again

Using IDLE, I have written an interactive python program using pygame and saved it as file Songboard01.py. I use IDLE's run command or f5 to run the script. The user responds initially to the IDLE shell, which asks a startup question, after which all the responses are mouse clicks on the pygame screen. In addition to game play, the screen allows the user to click on alternatives such as (1) 'Quit', (2) 'Instructions', (3) 'Credits', (4) 'Solutions', and (5) 'Play again'. The first three work fine, and the game is able to pick up without a problem after (2) or (3). It is 'Play again' that has me stumped.
This function:
def new_game():
done = True # closes pygame while-loop
pygame.quit()
import Songboard01.py
will start the game over with the startup question in the IDLE shell, but it only works once. If the user tries to get a new game a second time, the error message ends:
File "/Users/anobium/Desktop/SongBoard/Songboard01.py", line 314, in new_game
import Songboard01.py
ModuleNotFoundError: No module named 'Songboard01.py'; 'Songboard01' is not a package
A python program cannot import itself, and using the import function will raise an error. Also, you shouldn't put a ".py" at the end of a package name. I recommend putting your main game loop and putting a break if the user chooses (1), (2), (3), or (4). Put a continue if the user chooses (5). Your game will go back to the start if the user chooses (5).
Sample code:
#do your imports
import pygame #and all other needed modules
#Make classes or setup the game
while True:
#Do all of the game stuff
#Ok now make the buttons
#if button = 1 or 2 or 3 or 4:
break
#else if button = 5:
continue

How to exit stopped Python progam in Pygame 'fullscreen' mode?

I'm developing some Raspberry Pi code - Python in Pygame - and I often want to view it's video-out in fullscreen mode. But since it's in dev, I often run into code errors that stop the Python program - printing the error-info in the Idle shell. But in fullscreen mode, even though the program has stopped, I haven't found a way to exit the screen to get back to Idle.
Anybody know a simple way?
I know I could probably be more defensive in catch-exception blocks, but I would think there's some non programatic way to exit after an error-stop.
It is a nice place to make use of the try--finally pattern -
If your code have an init function to enter fullscreen, and a main to actually run the game, it could go like that:
import pygame
...
def init():
global screen
screen = pyame.display.set_mode(...)
...
def main():
...
try:
init()
main()
finally:
pygame.quit()

Categories