I'm trying to write a script for barcode printers.
Here is my Code:
def printLabel(barcode, qty, articlenr=''):
dev = findPrinter()
dev.write("")
return True
if __name__ =="__main__":
for i in range(2):
try:
# Everything works fine, the for loop breaks
printLabel('01234567890123','1', 'Hello World')
break
except usb.core.USBError as error:
if "Resource busy" in unicode(error):
# Printer is doing something, wait 3 seconds, try again
time.sleep(3)
print 'Retrying after error:"Resource busy"\n' + str(error)
printLabel('01234567890123','1', 'Hello World')
elif "Operation Timeout" in unicode(error):
# Printer is not responding
print 'ERROR! Check Paper!\n' + str(error)
else:
print 'Unknown error' + str(error)
I have to ask for the status of the printer before he tries to printLabel, because if I can't ask for it he maybe gets in the "Resource busy" if clause inside the exception, prints the label, starts all over again and prints it again.
But if I could ask for the status I can say him something like:
def waitForPrinter(dev):
dev = findPrinter()
if dev.status() is True: ## True if he is ready and False if he is Busy or something
printLabel(arguments and stuff)
else:
time.sleep(3)
waitForPrinter()
I couldn't find a function in the documentation for asking the device status and don't know how to solve the problem right now.
At the moment i can only fetch the device status with the USBError.
Related
Hello I want to know how to load a Dialog Topic file using python.
I made sure that the file path is right, but it keeps saying that it isn't. I have also used the tutorials in NAO 2.1's documentation ALDialog and ALModule
Please send me a code that works or tell me the error. I tried using the following code:
NAO_IP = "nao.local"
dialog_p = None
ModuleInstance = None
class NaoFalanteModule(ALModule):
def __init__(self, name):
ALModule.__init__(self, name)
self.tts = ALProxy("ALTextToSpeech")
self.tts.setLanguage("Brazilian")
global dialog_p
try:
dialog_p = ALProxy("ALDialog")
except Exception, e:
print "Error dialog"
print str(e)
exit(1)
dialog_p.setLanguage("Brazilian")
self.naoAlc()
def naoAlc(self):
topf_path = "/simpleTestes/diaSimples/testeSimples_ptb.top"
topf_path = topf_path.decode("utf-8")
topic = dialog_p.loadTopic(topf_path.encode("utf-8"))
# Start dialog
dialog_p.subscribe("NaoFalanteModule")
dialog_p.activateTopic(topic)
raw_input(u"Press 'Enter' to exit.")
dialog_p.unload(topic)
dialog_p.unsubscribe
def main():
parser = OptionParser()
parser.add_option("--pip",
help="Parent broker port. The IP address or your robot",
dest="pip")
parser.add_option("--pport",
help="Parent broker port. The port NAOqi is listening to",
dest="pport",
type="int")
parser.set_defaults(
pip=NAO_IP,
pport=9559)
(opts, args_) = parser.parse_args()
pip = opts.pip
pport = opts.pport
myBroker = ALBroker("myBroker",
"0.0.0.0",
0,
pip,
pport)
global ModuleInstance
ModuleInstance = NaoFalanteModule("ModuleInstance")
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
printI tried using the following code:
print "Interrupted by user, shutting down"
myBroker.shutdown()
sys.exit(0)
if __name__ == "__main__":
main()
The path to the topic needs to be the absolute path to that file, whereas you're passing a relative path compared to your current execution directory. The reason is that ALDialog is a separate service running in it's own process and knows nothing about the execution context of whoever is calling it.
And the program .top file must be uploaded to the robot using Choregraphe.
So, your absolute path in this case might be something like
topf_path = "/home/nao/simpleTestes/diaSimples/testeSimples_ptb.top"
... or if you want to be a bit cleaner, if you know your script is being executed at the root of your application package, use os.path:
topf_path = os.path.abspath("diaSimples/testeSimples_ptb.top")
Is this code correct? I ended up getting an Errno 111 and the program still quit rather than trying again and again.
When i get a connection error, i want to wait 10 seconds and then retry to get the URL again.
I'm using Python 2.7.
import errno
for attempt in range(20):
try:
browser.get(url)
except EnvironmentError as exc:
if exc.errno == errno.ECONNREFUSED:
anow = datetime.datetime.now()
print("got a 111 connection error",anow)
time.sleep(10)
elif exc.errno == errno.ECONNRESET:
anow = datetime.datetime.now()
print("got a RESET connection error",anow)
time.sleep(10)
else:
continue
else:
break
else:
print("tried 20 times - kept getting Error")
So this is what I ended up doing, and it seems to work:
What I wanted was something that would re-try again after any error, but also tell me what the error was. This code is running on PythonANywhere so i am not worried about keyboard interrupts, etc... Besides, the attempt in range() ensures that the code doesn't run forever as it would in a While-True loop.
for attempt in range(1,3):
try:
browser.get(url)
print("browser success",i)
break
except Exception as e:
print(e," Attempt:" + str(attempt))
time.sleep(4)
pass
I was trying to use subprocess to extract lines from log file. The intention here is to extract the logs while some program is getting executed and wait for some time copy all the logs to another file.
#!/bin/python
import threading
import time, subprocess
class GetLogs(threading.Thread):
'''
Get the developer logs
'''
def __init__(self):
'''
init
'''
self.stop = False
threading.Thread.__init__(self)
print "Initialised thread"
def run(self):
'''
Collect the logs from devlog
'''
command = "tail -f /var/log/developer_log | tee /tmp/log_collected"
response = subprocess.check_output(command.split(), shell=True)
print "Subprocess called"+str(response)
while ( self.stop is False ):
time.sleep(1)
print "Continuing"
continue
print "Finished the log file"
gl = GetLogs()
gl.start()
##Do some activity here
print "Sleeping for 10 sec"
time.sleep(10)
gl.strop = True
print "Done"
This doesn't work - program gets stuck.
subprocess.check_output() waits for all the output. It waits for the child process to exit or close its STDOUT stream.
tail -f never exits and never closes its STDOUT stream. Therefore none of the lines of code below the call to check_output() will execute.
As the warning about deadlocks in https://docs.python.org/2/library/subprocess.html suggests, look at using Popen() and communicate() instead.
I have a single method named grep_phalanx_log whose functionality is to SSH to a machine and grep for some values.
My main method will call this method with different host names/credentials, log file name, grep pattern.
So, I need to grep for a SAME pattern in two different servers in PARALLEL. If the match is found in one server, I want the other server to stop grep-ing. If the pattern is not found in both the servers for a specified time, my method grep_phalanx_log will return a negative value. Based on the negative value, I have to proceed with some other requirement.
class eventFlowTestNfx(object)
def grep_phalanx_log(self, host_name, username, password, grep_cmd, timeout=10, time_to_monitor=20):
ssh_client = paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
Log.info("Grep command to be executed: %r" % grep_cmd)
try:
ssh_client.connect(host_name, username=username, password=password, timeout=timeout)
end_time = time.time() + time_to_monitor
while time.time() < end_time:
ssh_stdin, ssh_stdout, ssh_stderr = ssh_client.exec_command(grep_cmd)
output = ssh_stdout.read()
if not output:
time.sleep(1)
else:
Log.info("NFX: Match message from %r is %r" % (host_name, output))
return output
if not output:
Log.error("FAILED: Message not processed.")
Log.error("Host Name: %r and grep command: %r" % (host_name, grep_cmd))
raise Exception("NFX agent could not process message")
except:
Log.error("End to End flow is broken, check the logs!")
return -1
def main(self):
for cr_dict in correlation_list:
cr_process = multiprocessing.Process(target=self.grep_phalanx_log(), args=(cr_dict["host"], cr_dict["username"], cr_dict["password"], cr_received_cmd_skeleton,))
cr_process.start()
So, I have my code stared 2 process, I am not sure how they will talk to each other and terminate the other.
You could replace time.sleep(1) with:
if not output.strip(): # blank output
is_found = found.wait(1) # sleep >= 1 second unless found
if is_found:
break # stop grepping
else: # found something
found.set()
...
return output
where found = multiprocessing.Event(): creat it in the parent process and pass to each child.
Ok, I've tried to resolve this with a couple of different libraries. I'm working on a script to look at thousands of sites and kick out specific items on the pages. I need to be able to reset the connection so that the script will continue without losing any data. I've tried catching the error and waiting but that doesn't seem to fix it as it eventually causes the script to error completely out. I get the error on the below snippet of code in my status check module.
def status(url): #checks the response code
try:
req=urllib2.urlopen(url)
response=req.getcode()
return response
except urllib2.HTTPError, e:
return e.code
print e.code
except urllib2.URLError, e:
print e.args
return e.args
But before trying this I used the below as instead of urrlib2
parsedurl = urlparse(url)
conn = httplib.HTTPConnection(parsedurl.netloc)
conn.request('HEAD',parsedurl.path)
response = conn.getresponse()
return response.status