Python to send a command line to Zebra Designer For Developers - python

Is there a way that Python can send or in other words, exist a command line that can be send via Python to the " Zebra Designer For Developers Software" to generate the PRN File?
I guess I should add a little bit more context about my question.
I'm working on a software to print labels using NiceLabel Software, the label I need to print is a dynamic label, this means that label information and layout is constantly changing.
I'm able to print the label however if for some reason I need to update the Label Layout a new PRN file needs to be generated, so far I has being do it manually but this is kind of odd since the main reason of my using python is to eliminate the human error
What I'm trying to do is to use Python to generate the PRN file instead users generating the file manually
Please see below a code that we are working on
## Imports
from configparser import ConfigParser
from zebra import Zebra
## Testing Variables
NUM = "128077-00S"
SER_NUM = "3132J908A6"
MODEL = "EM000"
## Get Config File
config = ConfigParser()
config.read('config.ini')
## Set Config Variables
printer = config['printer_setup'].get('printer')
prnFile = config['label_setup'].get('label')
## Read Label File
labelFile = open(prnFile)
label = labelFile.read()
labelFile.close()
## Printing
z = Zebra()
try:
z.getqueues().index(printer)
except ValueError:
print("Printer Not Found: " + printer)
input("\nPress enter to continue...")
else:
z.setqueue(printer)
out = label
out = out.replace("NUM", NUM)
out = out.replace("SER_NUM", SER_NUM)
out = out.replace("MODEL", MODEL)
z.output(out)
print("Label Printed Successfully!")
input("\nPress enter to continue...")
thanks for your help !

As I understand the question, you could replace your first three, or four, "test variables" + config file with argparse usage.
Then you run the script with any arguments you want, such as
python3 app.py -c config.ini --num="128077-00S" --sernum="3132J908A6" --model="EM000"

Related

How to fix ALDialog Python Script NAOqi Error

I am trying to use ALDialog module to have a virtual conversation with the Choregraphe simulated NAO6 robot. I have the below script:
import qi
import argparse
import sys
def main(session):
"""
This example uses ALDialog methods.
It's a short dialog session with two topics.
"""
# Getting the service ALDialog
ALDialog = session.service("ALDialog")
ALDialog.setLanguage("English")
# writing topics' qichat code as text strings (end-of-line characters are important!)
topic_content_1 = ('topic: ~example_topic_content()\n'
'language: enu\n'
'concept:(food) [fruits chicken beef eggs]\n'
'u: (I [want "would like"] {some} _~food) Sure! You must really like $1 .\n'
'u: (how are you today) Hello human, I am fine thank you and you?\n'
'u: (Good morning Nao did you sleep well) No damn! You forgot to switch me off!\n'
'u: ([e:FrontTactilTouched e:MiddleTactilTouched e:RearTactilTouched]) You touched my head!\n')
topic_content_2 = ('topic: ~dummy_topic()\n'
'language: enu\n'
'u:(test) [a b "c d" "e f g"]\n')
# Loading the topics directly as text strings
topic_name_1 = ALDialog.loadTopicContent(topic_content_1)
topic_name_2 = ALDialog.loadTopicContent(topic_content_2)
# Activating the loaded topics
ALDialog.activateTopic(topic_name_1)
ALDialog.activateTopic(topic_name_2)
# Starting the dialog engine - we need to type an arbitrary string as the identifier
# We subscribe only ONCE, regardless of the number of topics we have activated
ALDialog.subscribe('my_dialog_example')
try:
raw_input("\nSpeak to the robot using rules from both the activated topics. Press Enter when finished:")
finally:
# stopping the dialog engine
ALDialog.unsubscribe('my_dialog_example')
# Deactivating all topics
ALDialog.deactivateTopic(topic_name_1)
ALDialog.deactivateTopic(topic_name_2)
# now that the dialog engine is stopped and there are no more activated topics,
# we can unload all topics and free the associated memory
ALDialog.unloadTopic(topic_name_1)
ALDialog.unloadTopic(topic_name_2)
if __name__ == "__main__":
session = qi.Session()
try:
session.connect("tcp://desktop-6d4cqe5.local:9559")
except RuntimeError:
print ("\nCan't connect to Naoqi at IP desktop-6d4cqe5.local(port 9559).\nPlease check your script's arguments."
" Run with -h option for help.\n")
sys.exit(1)
main(session, "desktop-6d4cqe5.local")
My simulated robot has desktop-6d4cqe5.local as IP address and its NAOqi port is running on 63361. I want to run the dialogs outside of the Choregraphe in a python script and only be able to use the dialog box within the Choregraphe to test it. When I ran the above python file I got:
Traceback (most recent call last):
File "C:\Users\...\Documents\...\choregraphe_codes\Welcome\speak.py", line 6, in <module>
import qi
File "C:\Python27\Lib\site-packages\pynaoqi\lib\qi\__init__.py", line 93
async, PeriodicTask)
^
SyntaxError: invalid syntax
I couldn't figure out the problem as there was not much resources online and the robot's documentations are a bit hard to understand.
Please help, thank you.
You are running the script using a Python version greater than 3.5, that sees async as a keyword, now.
NAOqi only supports Python 2.
Try running your script with python2 explicitly.

Updating database after exporting to EXE

I am exporting a script I have made in Python that sends commands to IP Addresses of projectors to shut them down. The functionality of the code works, and the projectors will shut down. The list of projectors is stored in a dictionary in a different file to the script to allow it to be edited and accessed by other scripts.
Once I export my script to an exe using Pyinstaller v3.3.1 for Python 3.5.1, the .exe file no longer updates from the .py file that contains the dictionary, and instead has a version already stored in memory that I cannot update.
How can I make the executable file still read from the dictionary and update every time it is run?
Thanks,
Josh
Code:
dictonaryfile.py (reduced for security, but format shown).
projectors = {
'1': '192.168.0.1'
}
Script that performs shutdown
from pypjlink import Projector
from file3 import projectors
for item in projectors:
try:
myProjector = Projector.from_address(projectors[item])
myProjector.authenticate('PASSWORD REMOVED FOR SECURITY')
state = myProjector.get_power()
try:
if state == 'on':
myProjector.set_power('off')
print('Successfully powered off: ', item)
except:
print('The projector in ', item, ', raised an error, shutdown
may not have occurred')
continue
except:
print(item, 'did not respond to state request, it is likely powered
off at the wall.')
continue
As you noticed, once an exe is made, you can't update it. A workaround for a problem like this is ask for the location of dictonaryfile.py in your code-
from pypjlink import Projector
projector_location = input('Enter projector file location')
with open(projector_location) as f:
for line in f:
# extract data from f
....
For applications like these, it's a good idea to take a configuration file(.ini) and python has Configparser to read from config files. You could create your config file as -
[Projectors]
1 = '192.168.0.1'
2 = '192.168.0.45' # ..and so on
And read projectors from this file with Configparser -
config = configparser.ConfigParser()
config.read(projector_location)
projectors = config['PROJECTORS']
for k, v in projectors.items():
# your code here

Python fails silently when moving code in another file

I'm pretty new to python and I have a strange issue which I can't manage to understand by my own, I'm sure it's stupid but I can see what it is and never encountered before, even having wiring several python scripts with lots of subfiles
For the record I'm coding and launching my script with Spyder (Python 3.6 version) on Windows but I set #!/usr/lib/python2.7/ at the beginning of each file
My main script is a big file and I wanted to refactor it by externalising code in some other files
The main is like that :
if __name__ == "__main__":
configuration = Conf.loadConf(os.path.join(scriptDir,confFile))
print(configuration)
loadFavs(configuration,bioses,setDict)
When loadFavs is in main script everything works fine
As soon as I move it in fav.py file at same level than my main script adding import fav and modifying fav.loadFavs(configuration,bioses,setDict) it stops working and Spyder just says nothing without any reason :
In [1]: runfile('C:/DevZone/workspaceFX/scripts4recalbox/BestArcade/fav.py', wdir='C:/DevZone/workspaceFX/scripts4recalbox/BestArcade')
In [2] runfile('C:/DevZone/workspaceFX/scripts4recalbox/BestArcade/fav.py', wdir='C:/DevZone/workspaceFX/scripts4recalbox/BestArcade')
The first line configuration = Conf.loadConf(os.path.join(scriptDir,confFile)) should print things on screen and it doesn't even show
As soon as I put back the code in main script my code works again
It happens with several different part of the script I tried to put in different files
I'm at a loss here, what I checked :
having at the beginning of each file
#!/usr/lib/python2.7/
# -- coding: utf-8 --
always end the script on an empty line
creating each file within Spyder and not outside
I don't thing the code I move is the issue has it works fine in main script and I had the issue with several pieces of code but here it is :
def parseSetFile(setFile, setDict) :
file = open(setFile,'r')
genre = None
# Parse iniFile in iniFile dir
for line in file.readlines() :
line = line.rstrip('\n\r ')
if (line.startswith('[') and not line == '[FOLDER_SETTINGS]' and not line == '[ROOT_FOLDER]') :
genre = line
if genre not in setDict :
setDict[genre] = []
else :
if (genre is not None and not line == '' ) :
setDict[genre].append(line)
def loadFavs(configuration, bioses, setDict) :
print("Load favs small set")
parseSetFile(os.path.join(configuration['scriptDir'],dataDir,smallSetFile),setDict)
print("Load favs big set")
parseSetFile(os.path.join(configuration['scriptDir'],dataDir,bigSetFile),setDict)
print('Nb Genre : %s' %len(setDict))
sumGames = 0
for key in setDict.keys() :
# print(key)
# print(setDict[key])
sumGames = sumGames + len(setDict[key])
print('Nb Games : %s' %sumGames)
print('Nb Bios : %s' %len(bioses))
OK i'm effectively massively stupid :
In [1]: runfile('C:/DevZone/workspaceFX/scripts4recalbox/BestArcade/fav.py', wdir='C:/DevZone/workspaceFX/scripts4recalbox/BestArcade')
I'm launching my fav.py subscript not the main one, and off course it doesn't have any main ......

Python Orange (Version 3.3.6) on Window 10 can't create demo widget

As per the documentation, I created the following files:
setup.py (in folder C:\Python34\Lib\site-packages\Orange\widgets\orange-demo)
from setuptools import setup
setup(name="Demo",
packages=["orangedemo"],
package_data={"orangedemo": ["icons/*.svg"]},
classifiers=["Example :: Invalid"],
# Declare orangedemo package to contain widgets for the "Demo" category
entry_points={"orange.widgets": "Demo = orangedemo"},
)
and OWDataSamplerA.py (in folder C:\Python34\Lib\site-packages\Orange\widgets\orange-demo\orangedemo)
import sys
import numpy
import Orange.data
from Orange.widgets import widget, gui
class OWDataSamplerA (widget.OWWidget):
name = "Data Sampler"
description = "Randomly selects a subset of instances from the data set"
icon = "icons/DataSamplerA.svg"
priority = 10
inputs = [("Data", Orange.data.Table, "set_data")]
outputs = [("Sampled Data", Orange.data.Table)]
want_main_area = False
def __init__(self):
super().__init__()
# GUI
box = gui.widgetBox(self.controlArea, "Info")
self.infoa = gui.widgetLabel(box, 'No data on input yet, waiting to get something.')
self.infob = gui.widgetLabel(box, '')
def set_data(self, dataset):
if dataset is not None:
self.infoa.setText('%d instances in input data set' % len(dataset))
indices = numpy.random.permutation(len(dataset))
indices = indices[:int(numpy.ceil(len(dataset) * 0.1))]
sample = dataset[indices]
self.infob.setText('%d sampled instances' % len(sample))
self.send("Sampled Data", sample)
else:
self.infoa.setText('No data on input yet, waiting to get something.')
self.infob.setText('')
self.send("Sampled Data", None)
I created a .svg icon and left the __init__.py file blank. After running pip install -e ., a Demo.egg-info directory is created and it includes several files, but no demo widget is created. After restarting Python Orange no visible changes occur at all.
Any advice would be most welcome.
A separate version of Python 3.6 is bundled with Orange.
To install a new widget, you need to have the proper Python instance in the path.
On Windows, you can find a special shortcut "Orange Command Prompt". You will need to run it as Administrator to install new packages in newer version.
Once in the appropriate directory, you can run your pip install.. command.

Changing DataSource Password Using WLST (Multiple Domains)

I am very new to WLST scripting & currently at beginner level. I have a script which prompts for a password for each datasource it reads. While that part is working fine, the challenge i am facing is that, in production environment, where we want to run this script, there will be multiple managed servers having same datasource with different name but same JNDI as both datasources connecting to same database.
In that scenario the way script is working currently, it will prompt for password for every datasource it finds, but i wanted to modify the script so that it check the JNDIName for datasource & if password was already prompted for any datasource with same JNDI then it should use the same password rather than prompting for password again.
Also there are multi datasources, how can those be handled? Is it possible? besides i am not aware how to get the JNDIName for each datasource. I was trying to get JNDIName as following, which is not working -
jndiName = dataSource.getJNDIName()
This is error i am getting on command line -
Problem invoking WLST - Traceback (innermost last):
File "C:\Script\PostDeploy-DataSourcePasswords.py", line 59, in ?
File "C:\Script\PostDeploy-DataSourcePasswords.py", line 43, in updateJDBCPasswords
AttributeError: getJNDIName
This is the script i am working with -
import sys
#import wlstutility
#wlstutility.initialise(globals())
#from wlstutility import *
#from wlstutility.constructors import *
if len(sys.argv)<1:
print 'Usage: wlst.sh wibble.py <host:port>'
print ' for example: wlst.sh wibble.py prfadmin:14801'
exit()
hostPort = sys.argv[1]
print ('host:port = %s' % hostPort )
connectionUrl = ('t3://%s' % hostPort)
WL_USER='weblogic'
commitChanges=True
WL_PWD=raw_input("Enter Weblogic console password: ")
connect(WL_USER, WL_PWD, connectionUrl)
def updateJDBCPasswords():
PARAMS_TEMPLATE = '/JDBCSystemResources/%s/JDBCResource/%s/JDBCDriverParams/%s'
domainConfig()
# Get JDBC DataSources
cd("JDBCSystemResources")
dataSources = cmo.getJDBCSystemResources()
edit()
# For each DataSource update the password
for dataSource in dataSources :
dsName = dataSource.getName()
print ('DataSource Name : = %s' % dsName)
password=raw_input("Enter database password for " + dsName +" : ")
cd(PARAMS_TEMPLATE % (dsName, dsName, dsName) )
cmo.setPassword(password)
## ===========================================================
# Let's get going
edit()
startEdit()
updateJDBCPasswords()
# dump the changes made so far
print "=== START: The changes that will be applied ==="
showChanges()
if commitChanges :
# =========================================================
# commit the changes
save()
activate(block="true")
else:
# =========================================================
# rollback the changes
print "=== ROLLBACK - cancelling the changes so that they don't get applied ==="
cancelEdit('y')
# =========================================================
# all done - bye!
disconnect()
exit()
Any Help will be much appreciated.
Thanks & Regards,
Amrut Raut.
You try at your test/pre-live environments with simple WLST script that could fetch the JNDI names. You can fetch the JNDI names from the ds below:
cd('/JDBCSystemResource/' + dsName + '/JdbcResource/' + dsName + '/JDBCDataSourceParams/NO_NAME_0')
jarray_jndi_names=get('JNDINames')
jndi_names=[]
for jname in jarray_jndi_names:
jndi_names.append(jname)
Change dsName values with your input or whatever you feel better for your environment.
Once you got the JNDI names you need to use plain if condition to check it already exist then you can use your logic.
keep Note that all multidata sources configured with generic datasources only.
After trying with above hint share your experience.

Categories

Resources