I'm making a bot in python and it works normally, but I need a certain part of the code to be in an infinite loop, so when i put the code inside the "while True" it looks like my imports are unusable. can someone explain to me how i can solve this?ยด
import datetime
import os
import time
import cv2
import pytesseract
from playwright.sync_api import sync_playwright
caminho = r"C:\Program Files\Tesseract-OCR\tesseract.exe"
data = datetime.datetime.now()
h = data.strftime("%h")
d = data.strftime("%d")
H = data.strftime("%H")
M = data.strftime("%M")
S = data.strftime("%S")
hd = h + d
t = H + M
pasta =f"C:/Kprints/{hd}"
chave = "****"
with sync_playwright() as p:
browser = p.chromium.launch()
page = browser.new_page()
page.goto("*****")
page.locator('xpath=/html/body/div/div[5]/div[2]/div[2]/div/div/div/div/div/div[19]/button[1]').click()
time.sleep(3)
page.locator('xpath=/html/body/div/div[5]/div[2]/div[2]/div/div/div/div/div/div[4]/input').click()
page.fill('xpath=/html/body/div/div[5]/div[2]/div[2]/div/div/div/div/div/div[4]/input', "****")
page.locator('xpath=/html/body/div/div[5]/div[2]/div[2]/div/div/div/div/div/div[6]/input').click()
page.fill('xpath=/html/body/div/div[5]/div[2]/div[2]/div/div/div/div/div/div[6]/input', "****")
page.locator('xpath=/html/body/div/div[5]/div[2]/div[2]/div/div/div/div/div/button').click()
page.locator('xpath=/html/body/div/div[5]/div[2]/div[2]/div/div[1]/div/div/div[2]/div[1]/img[1]').click()
page.locator('xpath=/html/body/div/div[5]/div[2]/div[2]/div/div[1]/div/div/div[2]/div[2]/div[2]/div/div[2]').click()
page.locator('xpath=/html/body/div/div[5]/div[2]/div[2]/div/div/div/div/div/div[2]/div[5]/button').click()
time.sleep(1)
while True:
page.screenshot(path=f"{pasta}/{t}.png")
time.sleep(1)
img = cv2.imread(f"{pasta}/{t}.png")
time.sleep(1)
pytesseract.pytesseract.tesseract_cmd = caminho
texto = pytesseract.image_to_string(img)
time.sleep(1)
if not os.path.isdir(pasta):
os.mkdir(pasta)
list = os.listdir(pasta)
for arquivo in list:
if chave not in texto:
os.remove(f"{pasta}/{arquivo}")
Errors:
Unused import statement 'import os'
Unused import statement'import cv2'
Unused import statement 'import pytesseract'
This code is unreachable
Your analyzer is saying the code using them can't be reached because your while loop, being infinite, renders it impossible to reach any code after it. Either:
The loop never ends, or
The calls inside it raise an exception, that (thanks to no try blocks being involved) will bubble up (skipping the remaining code) and end the program.
Either way, as written, the code after the loop never runs, so those imports are effectively unused.
The question for you is: Do you expect/need the code after that loop to run? If so, the loop cannot be infinite and you need to change the code so it can end. If not, why is the code after the loop even there?
Those are not errors. Those should be just warnings.
Can you try re-run and post actual output here?
You code gets stuck in that loop so imports not used and yes pytesseract can not be reached.
Practice this code snippet first:
key = ""
while key != "q":
key = input("Enter a Key: ")
if key == "q":
break
print(f"You Entered: {key}")
Related
I would like some help. I'm trying to send a variable to T0. I've tried but I cannot send a variable value. Please help.
CODE
import serial
import time
import struct
from requests import get
ip = get('https://api.ipify.org').text
ser = serial.Serial("/dev/ttyAMA0")
time.sleep(1)
k=struct.pack('B', 0xff )
while True:
ser.write(b't0.txt=ip')
ser.write(k)
ser.write(k)
ser.write(k)
You have to wrap your string in quotation marks (") for Nextion to read the string.
Not a Python expert, but this should give you a clue:
Change ser.write(b't0.txt=ip') to something like ser.write(b't0.txt="' + ip + '"').
This works for me.
port=serial.Serial(port='/dev/ttyAMA0',baudrate=9600, timeout=1.0)
eof = "\xff\xff\xff"
tn = str(datetime.now().time())
alt = 'page0.T0.txt="'+tn+'"'+eof
dimCmd = "dim=0"
undimCmd = "dim=100"
cmd1 = "https://api.thingspeak.com/apps/thinghttp/send_request?api_key=YOUR_API_KEY" #IF USING THINGSPEAK
#get temp Sub - USING THINGSPEAK GET LOCAL WEATHER
def GetTemp():
global temp
response = urllib.urlopen(cmd1)
temp = response.read()
temp = temp[:-2] #gets all characters in temp except the last 2
while True:
port.write(alt) #writes time to T0 textbox on screen
port.write(undimCmd + eof) #set screen brightness to 100%
port.write("page 1")#set screen to page 1 for multiple page setups
I'm very new at Python scripting and am working on a script to turn on a fan when my Raspberry Pi3 reaches a specific temp. I've been trying to debug my code all day and found I can't figure out what's wrong. Here is my code:
import os
import sys
import signal
import subprocess
import atexit
import time
from time import sleep
import RPi.GPIO as GPIO
pin = 18
maxTMP = 60
def setup():
GPIO.setmode(GPIO.BCM)
GPIO.setup(pin, GPIO.OUT)
GPIO.setwarnings(False)
return()
def setPin(mode):
GPIO.output(pin, mode)
return()
def exit_handler():
GPIO.cleanup()
def FanON():
SetPin(True)
return()
def FanOFF():
SetPin(False)
return()
try:
setup()
while True:
process = subprocess.Popen('/opt/vc/bin/vcgencmd measure_temp',stdout =
subprocess.PIPE,shell=True)
temp,err = process.communicate()
temp = str(temp).replace("temp=","")
temp = str(temp).replace("\'C\n","")
temp = float(temp)
if temp>maxTMP:
FanON()
else:
FanOFF()
sleep(5)
finally:
exit_handler()
Here is my error:
File "/home/pi/Scripts/run-fan.py", line 36
while True:
^
IndentationError: unexpected indent
I've tried to indent every way possible. I need help.
Thanks!
I want to preface this with, you should use four spaces for your indentation. If you do, it will be way, way easier to see problems like the one you have here. If you use an IDE like Spyder or PyCharm, there are settings that automatically highlight indentation problems for you (regardless of how many spaces you want to use).
That said, with your current indentation scheme of one-space-per-indent, you want to replace your bottom block with this:
try:
setup()
while True:
process = subprocess.Popen('/opt/vc/bin/vcgencmd measure_temp',stdout =
subprocess.PIPE,shell=True)
temp,err = process.communicate()
temp = str(temp).replace("temp=","")
temp = str(temp).replace("\'C\n","")
temp = float(temp)
if temp>maxTMP:
FanON()
else:
FanOFF()
sleep(5)
If you used four spaces instead of one on your original code, it would have looked like this:
try:
setup()
while True:
process = subprocess.Popen('/opt/vc/bin/vcgencmd measure_temp',stdout =
subprocess.PIPE,shell=True)
temp,err = process.communicate()
temp = str(temp).replace("temp=","")
temp = str(temp).replace("\'C\n","")
temp = float(temp)
if temp>maxTMP:
FanON()
else:
FanOFF()
sleep(5)
There's another problem here, which is that your while True block will currently never exit (maybe you want a break statement somewhere).
I expect I'm doing something wrong here, but whenever I try to insert the snippet to save session information for the chatbot, the terminal closes immediately with an error. Here's my source:
import aiml
k = aiml.Kernel()
#k.learn("std-startup.xml")
#k.respond("load aiml b")
#k.saveBrain("test.brn")
k.loadBrain("test.brn")
#while True: print k.respond(raw_input("> "))
keepAlive = True
while True:
output = k.respond(raw_input("> "))
print output,
session = k.getSessionData("Bob")
sessionFile = file("Bob.ses", "wb")
marshal.dump(session, sessionFile)
sessionFile.close()
probably you need to use k in place of Kernel
session = k.getSessionData("Bob")
print bot.respond(raw_input(">"), "Bob")
As of right now I have a majority of the code done for browsing a subreddit, and downloading the top images at the time of the request. I was able to do this using PRAW and urllib to download the images once i get their link. The final part that i am stuck on is putting the images files in an array and actually setting them as my background. Here is what i have
import praw
import time
import os
import urllib as ul
import os
def backGroundChanger(sub):
USER_AGENT='wall paper changer for linux/windows by /u/**********' #specifies what my bot does and by who
REDDIT_ID= #reddit id
REDDIT_PASS= #reddit password
reddit=praw.Reddit(USER_AGENT) #creates bot
reddit.login(REDDIT_ID,REDDIT_PASS) #logsin
print reddit.is_logged_in()
images=reddit.get_subreddit(sub)
while True:
count=0
for sub in images.get_hot(limit=10):
imageLink=sub.url
print imageLink
n=str(count)
ul.urlretrieve(imageLink, "i" + n )
count+=1
file=[]
dir=os.getcwd()
for files in os.listdir("."):
if(files.endswith(".jpg|| .png"): # not sure if this will work
file.append(files)
changeBackGround(file,dir)
def changeBackGround(file, dir):
#Do back ground changing stuff here
def main():
subreddit=input("What subreddit would you like me to pull images from? ")
print "You chose " + subreddit
backGroundChanger(subreddit)
main()
This might work, maybe not; its untested.
Read up on the os.system function for a means to use system programs to set the background, like xsetbg in linux. Look here for setting the windows background (it only involves hacking the registry).
import os
import glob
import random
import sys
import time
import urllib
import praw
def backGroundChanger(sub):
USER_AGENT = 'wall paper changer for linux/windows by /u/**********' #specifies what my bot does and by who
REDDIT_ID = #reddit id
REDDIT_PASS = #reddit password
reddit = praw.Reddit(USER_AGENT) #creates bot
reddit.login(REDDIT_ID, REDDIT_PASS) #logsin
print reddit.is_logged_in()
images = reddit.get_subreddit(sub)
while True:
count = 0
for sub in images.get_hot(limit = 10):
imageLink = sub.url
print imageLink
n = str(count)
urllib.urlretrieve(imageLink, "i" + n )
count += 1
files = glob.glob("*.jpg") + glob.glob("*.png")
changeBackGround(files)
def changeBackGround(ifiles):
#Do back ground changing stuff here
the_file = ifiles[random.randint(0, len(ifiles) - 1)]
if(sys.platform.startswith("win")): # Windows
# Do this yourself
pass
elif(sys.platform.startswith("linux")): # Linux
os.system("xsetbg -center %s" % the_file)
def main():
subreddit = input("What subreddit would you like me to pull images from? ")
print "You chose " + subreddit
backGroundChanger(subreddit)
main()
I need to extract all the urls from an ip list,
i wrote this python script, but i have issue extracting the same ip multiple times (more threads are created with the same ip).
Could anyone Improve on my solution using multithreading ?
Sorry for my english
Thanks all
import urllib2, os, re, sys, os, time, httplib, thread, argparse, random
try:
ListaIP = open(sys.argv[1], "r").readlines()
except(IOError):
print "Error: Check your IP list path\n"
sys.exit(1)
def getIP():
if len(ListaIP) != 0:
value = random.sample(ListaIP, 1)
ListaIP.remove(value[0])
return value
else:
print "\nListaIPs sa terminat\n"
sys.exit(1)
def extractURL(ip):
print ip + '\n'
page = urllib2.urlopen('http://sameip.org/ip/' + ip)
html = page.read()
links = re.findall(r'href=[\'"]?([^\'" >]+)', html)
outfile = open('2.log', 'a')
outfile.write("\n".join(links))
outfile.close()
def start():
while True:
if len(ListaIP) != 0:
test = getIP()
IP = ''.join(test).replace('\n', '')
extractURL(IP)
else:
break
for x in range(0, 10):
thread.start_new_thread( start, () )
while 1:
pass
use a threading.Lock. The lock should be global, and create at the beginning when you create the IP list.
lock.acquire at the start of getIP()
and release it before you leave the method.
What you are seeing is, thread 1 executes value=random.sample, and then thread 2 also executes value=random.sample before thread 1 gets to the remove. So the item is still in the list at the time thread 2 gets there.
Therefore both threads have a chance of getting the same IP.