How to compile a python chat program to an exe? - python-2.7

Well this is a code for the "host" of a two way chatroom. The client's code is very similar. I have tried to compile both of them into an exe with various ways and none of them had a nice result. The exe simply doesnt run. I got all modules, i've tried many codes( many adding the dll files etc into the program too.) I try to compile it as a pyw since it has graphics inside. There is one more py file that has some more info that those two (client and host) pyw files get somehow, but they can still run without it with python.exe . I dont know how can I help you understand so let me know if you got any questions. Thanks in advance.
This is the host in python 2.7 code:
import thread
from ChatFns import *
#---------------------------------------------------#
#---------INITIALIZE CONNECTION VARIABLES-----------#
#---------------------------------------------------#
#Initiate socket and bind port to host PC
WindowTitle = 'Chat - Host User'
s = socket(AF_INET, SOCK_STREAM)
HOST = gethostname()
PORT = 8000
conn = ''
s.bind((HOST, PORT))
#---------------------------------------------------#
#------------------ MOUSE EVENTS -------------------#
#---------------------------------------------------#
def ClickAction():
#Write message to chat window
EntryText = FilteredMessage(EntryBox.get("0.0",END))
LoadMyEntry(ChatLog, EntryText)
#Scroll to the bottom of chat windows
ChatLog.yview(END)
#Erace previous message in Entry Box
EntryBox.delete("0.0",END)
#Send my mesage to all others
conn.sendall(EntryText)
#---------------------------------------------------#
#----------------- KEYBOARD EVENTS -----------------#
#---------------------------------------------------#
def PressAction(event):
EntryBox.config(state=NORMAL)
ClickAction()
def DisableEntry(event):
EntryBox.config(state=DISABLED)
#---------------------------------------------------#
#-----------------GRAPHICS MANAGEMENT---------------#
#---------------------------------------------------#
#Create a window
base = Tk()
base.title(WindowTitle)
base.geometry("400x470")
base.resizable(width=FALSE, height=FALSE)
#Create a Chat window
ChatLog = Text(base, bd=0, bg="white", height="8", width="50", font="Arial",)
ChatLog.insert(END, "Waiting for client user to connect...\n")
ChatLog.config(state=DISABLED)
#Bind a scrollbar to the Chat window
scrollbar = Scrollbar(base, command=ChatLog.yview, cursor="heart")
ChatLog['yscrollcommand'] = scrollbar.set
#Create the Button to send message
SendButton = Button(base, font=30, text="Send", width="12", height=5,
bd=0, bg="#E6E6E6", activebackground="#FA5858",
command=ClickAction)
#Create the box to enter message
EntryBox = Text(base, bd=0, bg="white",width="29", height="5", font="Arial")
EntryBox.bind("<Return>", DisableEntry)
EntryBox.bind("<KeyRelease-Return>", PressAction)
#Place all components on the screen
scrollbar.place(x=376,y=6, height=386)
ChatLog.place(x=6,y=6, height=386, width=370)
EntryBox.place(x=128, y=401, height=60, width=265)
SendButton.place(x=6, y=401, height=60)
#---------------------------------------------------#
#----------------CONNECTION MANAGEMENT--------------#
#---------------------------------------------------#
def GetConnected():
s.listen(1)
global conn
conn, addr = s.accept()
LoadConnectionInfo(ChatLog, 'Connected with: ' + str(addr) + '\n---------------------------------------------------------------')
while 1:
try:
data = conn.recv(1024)
LoadOtherEntry(ChatLog, data)
if base.focus_get() == None:
FlashMyWindow(WindowTitle)
playsound('notif.wav')
except:
LoadConnectionInfo(ChatLog, '\n [ User disconnected. ]\n [ Waiting for them to connect...] \n ')
GetConnected()
conn.close()
thread.start_new_thread(GetConnected,())
base.mainloop()

Python is an interpreted language, it's not supposed to be compiled into an .exe file. However, there are tools like http://py2exe.org/ that create an executable file with Python, strapping the interpreter itself into the file.

Related

Load topic file to NAO robot 2.1

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")

sending command to my Camera via usb port RAS PI (python)

I'm trying to send command to my Flir camera TAU2 using USB and normally i should receive a respond from it, so what i'm doing first is that i'm configuring my serial port
and then i'm sending my command via the serial port:
and then listening to the serial for a respond :
this is a part of my code:
def __init__(self):
self.serCam = serial.Serial(port='/dev/ttyUSB0',
baudrate=9600,
parity=serial.PARITY_NONE,
stopbits=1,
xonxoff=False
)
def close_connection(self):
if self.serCam.isOpen():
self.serCam.close()
def serial_Read(self):
while self.serCam.inWaiting():
try:
self.state=serCam.readline()
return state
print state
except:
pass
def control(self):
self.len= self.serCam.write(serial.to_bytes([0x6E,0x00,0x00,0x0B,
0x00,0x00,0x2F,0x4A,0x00,
0x00,0x00]))
print ('commande envoye' )
return len
i don't receive anything from my camera, do you have any idea please from where it can be ?

Serial.serialutil.serialException: Attempting to use a port that is not open

I am using Python code to control my mini GRBL CNC machine that connected to Laptop with windows operating system over MQTT Protocol,
Here is the code.
import paho.mqtt.client as mqtt
import time
import serial
# Open grbl serial port
s = serial.Serial('COM5',115200)
# Wake up grbl
s.write("\r\n\r\n")
time.sleep(2) # Wait for grbl to initialize
s.flushInput() # Flush startup text in serial input
f = """
O1000
T1 M6
(Linear / Feed - Absolute)
G0 G90 G40 G21 G17 G94 G80
G54 X-75 Y-75 S500 M3 (Position 6)
G43 Z100 H1
Z5
G1 Z-20 F100
X-40 (Position 1)
Y40 M8 (Position 2)
X40 (Position 3)
Y-40 (Position 4)
X-75 (Position 5)
Y-75 (Position 6)
G0 Z100
M30
"""
# Runs when the client receives a CONNACK connection acknowledgement.
def on_connect(client, userdata, flags, result_code):
print "Successful connection."
# Subscribe to your topics here.
client.subscribe("hi")
# Runs when a message is PUBLISHed from the broker. Any messages you receive
# will run this callback.
def on_message(client, userdata, message):
if message.topic == "hi":
if message.payload == "run":
# Stream g-code to grbl
for line in f:
l = line.strip() # Strip all EOL characters for consistency
print 'Sending: ' + l,
s.write(l + '\n') # Send g-code block to grbl
grbl_out = s.readline() # Wait for grbl response with carriage return
print ' : ' + grbl_out.strip()
# Close file and serial
s.close()
# You could do something here if you wanted to.
elif message.payload == "STOP":
# Received "STOP". Do the corresponding thing here.
# Close file and serial
s.close()
print "CNC is stopped."
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect("iot.eclipse.org", 1883, 60)
client.loop_forever()
But when i run it i got
successful connection
and then,
serial.serialutil.serialException: Attempting to use a port that is not open ,Although the CNC works fine from GUI.At first i thought that the opening GUI caused this error, but even when i closed it i am still having the same issue.So, maybe i am facing this problem because of MQTT, maybe it's a security issue because when i run that python code but without using PAHO MQTT protocol every things works fine, the same port opens and CNC works.
Isn't it supposed to work until i send "run" because the serial opening order comes after receiving the message?
You are closing the serial port when ever you get a message delivered. That means you can only ever process one message.

Receive code not working XBee python

Configured two xbee pro s2b using X-CTU, one as coordinator and other as router, API=2, baudrate as 9600. The sender code (coordinator) is as below:
import time
from xbee import XBee
import serial
PORT = "/dev/ttyUSB0"
BAUDRATE = 9600
#open serial port
sender_port = serial.Serial(PORT, BAUDRATE)
print "serial port object>>>", sender_port
#xbee object API=2
sender = XBee(sender_port,escaped=True)
#address of the remote xbee to which data is to sent
ADDRESS = "\x00\x13\xA2\x00\x40\xD9\x6F\xE5"
#send data using the tx_long_addr
while True:
try:
print "sending data..."
sender.tx_long_addr(frame_id='A', dest_addr=ADDRESS, data="hello")
time.sleep(1)
except KeyboardInterrupt:
break
sender.halt()
sender_port.close()
below is the receiver code (router)
import time
from xbee import XBee
import serial
PORT = "/dev/ttyUSB1"
BAUDRATE = 9600
def byte2hex(byteStr):
return ''.join(["%02X" % ord(x) for x in byteStr]).strip()
def decodereceivedFrame(data):
source_address = byte2hex(data['source_addr'])
xbee_id = data['id']
rf_data = data['rf_data']
options = byte2hex(data['options'])
return [source_address, xbee_id, rf_data, options]
#open serial port at receiving end
remote = serial.Serial(PORT, BAUDRATE)
#xbee object API=2
remote_xbee = XBee(remote, escaped=True)
while True:
try:
print "yes i m here"
data = remote_xbee.wait_read_frame()
print "data >>>", data
decoderdata = decodereceivedFrame(data)
print "data received<<<<", decoderdata
except KeyboardInterrupt:
break
remote_xbee.halt()
remote.close()
But on executing the receiver code, nothing happens, it does not print the received message. On X-CTU frames are being transmitted and received without any errors, am i doing something wrong in the code. Please guide .
Thank you
Found the issue, my fault----
sender = ZigBee(sender_port, escaped=True)
sender.send('tx', frame_id='A', dest_addr="\x5E\x71", dest_addr_long="\x00\x13\xA2\x00\x40\xD9\x6F\xE5", data="Hello")
Works now ..!!! :)

Web Server: socket programming for TCP connections in Python

I'm trying to run a python web server. The server says is running so I assume it is all working, except that I can only see the html text. The jpeg/image and the pdf files won't dispaly. Here is what i have so far.
#import socket module
from socket import *
serverSocket = socket(AF_INET, SOCK_STREAM)
serverSocket.bind(('', 12000))
serverSocket.listen(1)
while True:
print 'Ready to serve...'
connectionSocket, addr = serverSocket.accept()
print 'Required connection', addr
try:
message = connectionSocket.recv(1024)
filename = message.split()[1]
f = open(filename[1:])
outputdata = f.read()
#Fill in start
connectionSocket.send('HTTP/1.0 200 OK\r\n\r\n')
#Fill in end
#Send the content of the requested file to the client
for i in range(0, len(outputdata)):
connectionSocket.send(outputdata[i])
connectionSocket.close()
except IOError:
#Send response message for file not found
#Fill in start
connectionSocket.send('404 Not Found')
#Fill in end
#Close client socket
#Fill in start
connectionSocket.close()
#Fill in end
serverSocket.close()
I'm working on the same thing. I added the line:
connectionSocket.send('Content-Type: image/jpeg')
right after this:
connectionSocket.send('HTTP/1.0 200 OK')
I assume I'm/we're just missing some line in the header.