I am trying to restart my main.py after the program has finished running. However, when I go into the last file (unlock.py) then put at the end of the script:
from main import *
main()
I get a circular import error. I am not sure a way to work around this so if anyone knows, your help would be greatly appreciated. If you have any questions, feel free to ask.
You can use the execv method of os module:
import os
import sys
os.execv(__file__, sys.argv)
If you're getting any permission errors:
os.execv(sys.executable,
[sys.executable, os.path.join(sys.path[0], __file__)] + sys.argv[1:])
To disable warnings:
import warnings
warnings.filterwarnings("ignore")
Without seeing the structure of your program, the best recommendation I can give is to pass your main function around as an argument. That way, in unlock.py, you don't need to import the main module.
Consider this simple example:
main.py
import unlock
def main(function_to_pass):
# do stuff
unlock.some_func(function_to_pass,*rest_of_args)
if __name__ == '__main__':
main(main)
unlock.py
def some_func(function_to_call,*args):
# do stuff
if some_condition:
function_to_call()
EDIT: I realized that you don't need to pass main into itself. main can simply reference itself. That is,
def main():
# do stuff
unlock.some_func(main,*args)
When I import pygame, it prints the version and welcome message. The message reads:
pygame 1.9.4
Hello from the pygame community. https://www.pygame.org/contribute.html
Why is this printed?
How can I disable this message?
As can be seen in the source code, the message is not printed if the environment variable PYGAME_HIDE_SUPPORT_PROMPT is set. So the following code could be used to import pygame without printing the message:
import os
os.environ['PYGAME_HIDE_SUPPORT_PROMPT'] = "hide"
import pygame
Note that the value does not have to be "hide" but can be anything else as well, and the environment variable can also be set in other ways to achieve the same.
Here's the better way alternative suggested by #Mad Physicist:
import contextlib
with contextlib.redirect_stdout(None):
import pygame
Or, if your Python is older than 3.4 you can achieve the same thing without the contextlib import by temporarily disabling stdout while importing pygame.
import os, sys
with open(os.devnull, 'w') as f:
# disable stdout
oldstdout = sys.stdout
sys.stdout = f
import pygame
# enable stdout
sys.stdout = oldstdout
The source code contains a condition guarding the printing of this message:
if 'PYGAME_HIDE_SUPPORT_PROMPT' not in os.environ:
print('pygame %s' % ver)
print('Hello from the pygame community. https://www.pygame.org/contribute.html')
See this commit
This was added fairly recently (October 2018) and so far 1.9.4 was released prior to this. Once the next version > 1.9.4 is released you should simply by able to run your code with PYGAME_HIDE_SUPPORT_PROMPT= ./my_code.py to hide the message.
You can navigate to the pygame library folder, something like this for 3.6 32 bit version:
Python36-32\Lib\site-packages\pygame
and edit the __init__.py file and remove the last line to get rid of this message.
import pygame
Get the location of the init file: f = pygame.__file__
Open f and comment out the print on the last two lines of the file
About Eduardo's answer, I was having problems with my formatter autopep8 and was unable to put the line to set the PYGAME_HIDE_SUPPORT_PROMPT environment variable above the line to import pygame. Thus, I had to do something like this:
import os # last import (all other imports above this one)
os.environ['PYGAME_HIDE_SUPPORT_PROMPT'] = 'hide'
def import_pygame():
global pygame
import pygame
import_pygame()
I hope this helps anyone having the same issue.
For me, only this worked in python 3:
import sys, os
# Disable print
def blockPrint():
sys.stdout = open(os.devnull, 'w')
# Enable print
def enablePrint():
sys.stdout = sys.__stdout__
blockPrint()
import pygame
enablePrint()
(thanks for Brigand!)
This works fine for me:
from os import environ
environ['PYGAME_HIDE_SUPPORT_PROMPT'] = '1'
import pygame
You just have to make sure your imports don't get rearranged.
And it has come before any import of anything that imports pygame, not just before your import of pygame.
For me, PYGAME_HIDE_SUPPORT_PROMPT does not work.
Add this for the whole block of imports:
sys.stdout = open(os.devnull, "w")
# your other imports go here
import pygame
sys.stdout = sys.__stdout__
I kindly ask you though to only use this if the program will be launched graphically, to avoid spawning a console, or when you'll leave another message. You can print a shorter or more fitting one, or you can add it in a GUI.
Editing Pygame is not desirable if you are going to distribute your project in any way.
Go in pygame's __init__.py file, go at the bottom of that file, and comment out those two print function-
print('pygame %s' % ver)
print('Hello from the pygame community. https://www.pygame.org/contribute.html')
However, I would not do that since, pygame community is an open-source community, and they would want as many people as possible, to contribute to pygame, thats why they have this print function at that last. I would not comment it out, if I were you.
This is one time process to disable it!
Step 1:
Run a dummy.py containing following code:
import pygame
pygame.__file__
Step 2:
Copy the path of the pygame source code excluding __init__.py
Example:
C:\\Users\\dell\\AppData\\Roaming\\Python\\Python37\\site-packages\\pygame\\
Step 3:
Go to the copied location by pasting it into the run dialog box or any other way
Step 4:
open __init__.py in any text editor and search for welcome
delete the following code from the file:
if 'PYGAME_HIDE_SUPPORT_PROMPT' not in os.environ:
print('pygame %s' % ver)
print('Hello from the pygame community. https://www.pygame.org/contribute.html')
Now save the file and you are good to go!
You can go into pygame's __init__.py file and comment out the line that causes the message to be printed. It's exactly at line 355. Here is the code that does that.
# Thanks for supporting pygame. Without support now, there won't be pygame
#later.
if 'PYGAME_HIDE_SUPPORT_PROMPT' not in os.environ:
print('pygame {} (SDL {}.{}.{}, Python {}.{}.{})'.format(
ver, *get_sdl_version() + sys.version_info[0:3]
))
print('Hello from the pygame community.
https://www.pygame.org/contribute.html')
You can just go ahead and comment those lines out. I have tested it, it does not cause any problems.
But always be thankful for pygame's free and opensource library.
# remove pygame installed with "pip install..."
python pip uninstall pygame
# remove all folder with pygame
sudo apt-get update -y; sudo apt-get upgrade -y
sudo apt-get install python-pygame
The version installed with the last line will work without announcing its name.
... could someone explain the difference?
What I type in the command prompt:
sys.path.append('M:/PythonMods')
import qrcode
myqr = qrcode.make("randomtexxxxxxxxxt")
myqr.show()
myqr.save("M:/myqr.png")
MAKES A QR FOR THE TEXT.
The code I type:
sys.path.append('M:/PythonMods')
import scipy
from qrcode import myqr
file=open('myqr3.png',"r")
myqr.show()
file.close()
It doesn't recognise sys, do I need to import something? How come it runs in the command prompt?
Thanks in advance for any help.
add at the begining of your source file:
import sys
and while we're reviewing your code, in executable source files it is advised to do so:
import sys
sys.path.append('M:/PythonMods')
import qrcode
if __name__ == "__main__":
myqr = qrcode.make("randomtexxxxxxxxxt")
myqr.show()
myqr.save("M:/myqr.png")
so your code will run only when you execute it as a file, not when you import it. You may want to define your three lines as a function, and call your function in the if __name__ == "__main__": part, to be able to reuse it like any library!
At the top of the script, please include the following line:
import sys
sys is not a built-in, you do need to explicitly import it:
import sys
The ipython interactive shell imports a lot of modules by default; perhaps you are using that to test your code. The default Python runtime does not import sys for you.
I tried running the following python code in Eclipse on Windows but it is showing errors saying pwd is not a valid import:
import os
import pwd
import socket
pinfo=pwd.getpwuid(os.getuid())
Can I use if not win32 to bypass this part so when it runs on Windows it just jumps at and doesn't create an error?
if not win32:
import os
import pwd
import socket
pinfo=pwd.getpwuid(os.getuid())
else:
return
If yes, what do I need to do to use this win32 since it's also showing an error saying undefined variable?
You should use sys.platform for that.
if sys.platform != 'win32':
...
if sys.platform != 'win32':
...
I guess those 2 questions may have an answer to your question.
Is there a portable way to get the current username in Python?
What is the Windows equivalent of pwd.getpwnam(username).pw_dir?
you can check OS by using
import os
if os.name != 'nt':
# do something
If I execute a python script which is actually a symbolic link linked to the real script from somewhere else, is there anyway we can print the location of the real script?
Alternatively, if you don't want to use argv
#!/usr/bin/python
import os
print os.path.realpath(__file__)
#!/usr/bin/python
import os
import sys
print os.path.realpath(sys.argv[0])