Unique import * only allowed at module level [duplicate] - python

This question already has answers here:
Python: Why should 'from <module> import *' be prohibited?
(6 answers)
Closed 5 months ago.
I am making a utility program which has multiple programs built into it but I made some changes to my program for it re-run when the user has prompted which then for some reason, I am facing the error
import * only allowed at module level
Here's my code
def main():
import os
import sys
import time
import pywhatkit as whatsapp
from speedtest import Speedtest
from tkinter import *
from tkinter import messagebox
from os import listdir
from PIL import Image
print("*"*30)
print("Utility Build v1: Starting")
print("*"*30)
time.sleep(3)
print("NOTE: Before using this program for repairing corrupted disk, please locate this utility .py file into the corrupted storage. Thanks")
time.sleep(3)
print("*"*30)
print("*"*30)
print("Commands: Choose by inputting allocated number")
print("Utility 1: Speed Test")
print("Utility 2: Whatsapp Message Automation")
time.sleep(2)
print("Please Wait...Loading")
time.sleep(4)
print("Utility 3: Disk/Removable Storage Repair(a.k.a Dr Corrupt)")
print("Utility 4: Python .py status monitor")
print("*"*30)
print("*"*30)
print("q = Quit Utility Program")
input_ = input(": ")
if input_ == "q":
exit()
if input_ == "1":
time.sleep(2)
print("*"*30)
print("Speed Test: Starting")
print("*"*30)
st = Speedtest()
Download_ = print("Your connection download speed is:", st.download())
Upload_ = print("Your connection upload speed is:", st.upload())
Download1_ = st.download()
Upload1_ = st.upload()
print("*"*30)
print("Speed Test: Finishing Up!")
print("*"*30)
answer = input("Would you like results? ")
if answer == "yes":
print("NOTE: The first 2 digits frm the left is your internet speed")
time.sleep(2)
top = Tk()
top.geometry("100x100")
messagebox.showinfo("Speed Test: Download", Download1_)
top.mainloop()
reply = input("Would like to leave Utility Build(yes) or go to home page?(no) ")
else:
reply1 = print("Would like to leave Utility Build(yes) or go to home page?(no) ")
if reply1 == "yes":
main()
else:
exit()
if input_ == "2":
whatsapp.sendwhatmsg("+61450776320", "Hi, this is a test", 0, 0)
if input_ == "3":
for filename in listdir('./'):
if filename.endswith('.png'):
try:
img = Image.open('./'+filename) # open the image file
img.verify() # verify that it is, in fact an image
except (IOError, SyntaxError) as e:
print('Bad file:', filename) # print out the names of corrupt files

"Module level" just means in a part of the script that's not in a class or function. Any names you define there go directly into the module namespace.
The error message is therefore just saying to move
def main():
import os
import sys
import time
import pywhatkit as whatsapp
from speedtest import Speedtest
from tkinter import *
from tkinter import messagebox
from os import listdir
from PIL import Image
to
import os
import sys
import time
import pywhatkit as whatsapp
from speedtest import Speedtest
from tkinter import *
from tkinter import messagebox
from os import listdir
from PIL import Image
def main():
Actually, the interpreter only really cares about the line from tkinter import *. The others are a matter of convention and readability.
CPython does optimizations on the local namespace inside a function that requires the interpreter to know the names of all local variables up-front. A star import prevents that from happening since you don't know what names will be in the imported module until you run it. The global namespace doesn't have this restriction, so you can do star imports there.
Python is a language for consenting adults. Just because something is "bad practice" or not maintainable does not make it a syntax error.

Related

While Loop No Longer Updating Data when added "Press Enter to Exit"

I am a beginner to Python and recently was making a **Discord Rich Prescense** application. The problem is that I was using a While Loop and added a "*Press Enter to Exit*" feature. This made the Rich Prescense stuck on One Quote. I have attached a screenshot of the problem.
from config import credentials
from data import quotes
from pypresence import Presence
import random
import time
def quotegen():
RPC = Presence(credentials.clientid)
RPC.connect()
while True:
RPC.update(details="Random Quote:", state=random.choice(quotes.quotes))
i = input("Press Enter to Exit")
time.sleep(30)
if not i:
break
Screenshot of what its supposed to do:
Using the keyboard module (https://pypi.org/project/keyboard/)
you can do it all.
I modified your code to fit your requirements:
import keyboard # using module keyboard
from config import credentials
from data import quotes
from pypresence import Presence
import random
import time
def quotegen():
RPC = Presence(credentials.clientid)
RPC.connect()
while True:
RPC.update(details="Random Quote:", state=random.choice(quotes.quotes))
i = input("Press Enter to Exit")
time.sleep(30)
if keyboard.is_pressed('enter'): # if key 'enter' is pressed
break

pytube program exiting after entering the link and storing it into a variable

When I run my code below, the program exits after entering a link.
It looks like it is actually doing something but it doesn't print out anything. It just exits in 1-2 seconds after entering the YouTube link.
The problem only occurred after I defined the functions and put my statements in it. Before that, it worked correctly.
import sys
import getpass
import time
from pytube import YouTube
import keyboard
from termcolor import *
osusername = getpass.getuser()
print("═══════════════════════════════════")
print(" Main Menu ")
print("═══════════════════════════════════\n")
def Option1():
print("")
print("═══════════════════════════════════")
print(" YouTube Downloader ")
print("═══════════════════════════════════")
link = input("Enter the link:")
yt = YouTube(link)
print("Title: ",yt.title)
print("Number of views: ",yt.views)
print("Length of video: ",yt.length,"seconds")
print("Ratings: ",yt.rating)
print("\n")
res = input("Would you like to download this video? y/n \n")
path = 'C:\Program Files\downl'
if res == "y":
print("Downloading video...")
yt.streams.first().download(path)
else:
print("Press any button to close the program")
def Menu():
print("[1] ~ Download YouTube Videos")
def keyPressed():
while True:
try:
if keyboard.is_pressed('1'):
Option1()
except:
break
Menu()
keyPressed()
When I run your code. The Program stops and doesn't work for me too. Then I realised that the pytube installed in my system was an older version. So I simply updated the version of pytube by:
pip install --upgrade pytube
After then, when I run the code the code works pretty well.

Audio does not complete when called from another function

I have the following code quasi-working
from gtts import gTTS
import speech_recognition as rs
import pyaudio
import audioop
import os
import math
from os import system
import threading
from datetime import datetime
def say(text):
filename = 'speak.mp3'
language = 'en'
myobj = gTTS(text=text, lang=language, slow=False)
myobj.save(filename)
player = vlc.MediaPlayer(filename)
player.play()
def listen(x):
r=rs.Recognizer()
with rs.Microphone() as source:
audio=r.listen(source)
try:
text = r.recognize_google(audio)
process(text.lower())
except:
system('say I did not get that. Please say again.')
listen(0)
def process(text):
print(text)
# Do things here based on text
if 'what time is it' in text:
say(datetime.now().strftime("%H%M"))
return
#process("what time is it") "Seventeen oh six"
# Listen for me to say something, if I say 'what time is it' return the time
#listen(0) "Se"
If I run process(text) manually such as:
process("what time is it")
Python will speak back to me something like "1706" (Seventeen oh six)
However, if I call it from the listen() function python will start to play the file but it gets cut off and is more like "Se" and then nothing.
I've tried multiple things including using time.sleep(n) but no changes seem to make the entire file play when called through the listen(n) function.

How can I fix this error?: ImportError: cannot import name 'titlescreen'

So, I've been trying to make a title screen for my game. In this title screen, you can choose to start playing or you can choose to read the game rules. The rules and the title are both definitions in different .py files.
I have tried importing the definitions to the tittle screen and to the instructions. But as soon as I import the title to the instruction file, It will tell me that it isn't possible to import it.
#tittlescreen.py file
import sys,time,random
import fileinput, time
from time import sleep
from rules import instructions
from begin import start
import os
answer = None
while answer not in ("1" , "2"):
answer = input(" Type '1' or '2': ")
if answer == "1":
os.system('clear')
start()
elif answer == "2":
os.system('clear')
instructions() #It's here that it begins to have a problem
#rules.py File
import sys,time,random
import fileinput, time
from time import sleep
from titlescreen import titlescreen
from begin import start
import os
proceed = "1"
while proceed not in ("0"):
pross = input("Press '0' to begin playing.")
if pross == "0":
os.system('clear')
titlescreen() #And here
The error that shows up is this one:
Traceback (most recent call last):
File "main.py", line 4, in <module>
from titlescreen import titlescreen
File "/home/runner/titlescreen.py", line 4, in <module>
from instructions import instruções
File "/home/runner/instructions.py", line 4, in <module>
from titlescreen import titlescreen
ImportError: cannot import name 'titlescreen'
I don't know why it won't let me import the "titlescreen" definition to the "instructions" definition.
I really do hope that I can make a working title screen and instructions that can access eachother, just like in a normal game.
I am assuming that you want to run the "titlescreen.py" file when you call titlescreen() in the "rules.py" file. Right? Unfortunately, that's not exactly how "from titlescreen import titlescreen" works.
Take this similar example. The way the following code works...
from X import Y
Is that Python looks in the file named X.py for a function definition named Y. Since there are no functions in titlescreen.py, it can't find anything!
If you want to import a function named "titlescreen" in the file titlescreen.py, and it should look something like this...
def titlescreen():
answer = None
while answer not in ("1" , "2"):
answer = input(" Type '1' or '2': ")
if answer == "1":
os.system('clear')
start()
elif answer == "2":
os.system('clear')
instructions()
Hopefully that does the trick.

how to use gtts repeatedly?

when i call my function once i have no errors but if i call it repeatedly i will have the following error :
Exception has occurred: PermissionError [Errno 13] Permission denied:
'tolkback.mp3'
from gtts import gTTS
import pyglet
from playsound import playsound
def TalkBack(case_ans):
print("in ...................................")
tts = gTTS(case_ans)
tts.save('tolkback.mp3')
print("saving...............................")
playsound('tolkback.mp3')
print("saying................................")
TalkBack("my bad end 1")
TalkBack("go go end 2")
TalkBack("find me my self end 3")
TalkBack("games maker end 4")
TalkBack("say my name end 5")
the program should talk back the text
this is the solution that i made >> with the Gide of my friend furas
from playsound import playsound
import webSearch
import os
import random
def name_generator():
ran = random.randint(1,5000)
ran = str(ran)
return ran
def TalkBack(case_ans):
print("in ...................................")
tts = gTTS(case_ans)
new_name = name_generator()
new_name= new_name+".mp3"
tts.save(new_name)
print("saving...............................")
playsound(new_name)
print("saying................................")
try:
os.remove(new_name)
except:
print("i cant")
TalkBack("my bad end 1")
TalkBack("go go end 2")
TalkBack("find me my self end 3")
TalkBack("games maker end 4")
TalkBack("say my name end 5")
generating a new .mp3 file with a random name and deleting it after using it

Categories