Read loop that does not crash when file is recreated - python

I have a python script that needs to read bytes from a file and publish them in MQTT room. But the file could be recreated during the process (the python script have to be running 24/24).
I tried this code, but when the file is being recreated os.path.isfile always return false.
def mqttToTtyOnMessage(client, userdata, message):
tty = openFile(filename, os.O_WRONLY)
print("%s # %s : Message from %s to %s\n" %
(threadName, time.ctime(time.time()), message.topic, filename))
try:
os.write(tty, message.payload)
except:
print("%s # %s : Unable to write message to file %s\n%s" %
(threadName, time.ctime(time.time()), filename, sys.exc_info()))
while True:
if os.path.isfile(filename):
print("%s # %s : File exist, come back to main loop." % (threadName, time.ctime(time.time())))
subTty = openFile(filename, os.O_WRONLY)
os.write(subTty, message.payload)
break
else:
print("%s # %s : File still not exist, wait few seconds and check again." % (threadName, time.ctime(time.time())))
time.sleep(1)
os.close(tty)
The function openFile looks like this :
def openFile(filename, permission):
try:
fd = os.open(filename, permission)
except:
print("%s # %s : Unable to write message to file %s\n%s" %
(threadName, time.ctime(time.time()), filename, sys.exc_info()))
return (fd)
I hope you have ideas about an error in my code or another way to achieve this.
Thanks
EDIT: Solve this problem by changing the way I checked if the file exist :
def mqttToTtyOnMessage(client, userdata, message):
try:
tty = openFile(filename, os.O_WRONLY)
os.write(tty, message.payload)
print("%s # %s : Message from %s to %s\n" %
(threadName, time.ctime(time.time()), message.topic, filename))
except OSError:
print("%s # %s : Unable to write message to file %s\n%s\n" %
(threadName, time.ctime(time.time()), filename, sys.exc_info()))
while True:
try:
subTty = openFile(filename, os.O_WRONLY)
os.write(subTty, message.payload)
break
except:
print("%s # %s : Can't open file for the moment, try again in 5s.\n%s\n" % ("mqttToTty", time.ctime(time.time()), sys.exc_info()))
time.sleep(5)
os.close(tty)

Related

How to Fix Except Error in Python on Linux

I'm trying to execute a python script from Linux but I'm keep getting this error on the except line. Can someone figure this out?
$ python pygeo_ip.py
def search(self):
message = ''
result_count = 0
gip = pygeoip.GeoIP('GeoLIteCity.dat')
ip = self.ip_textbox.text()
try:
ip = socket.gethostbyname(str(ip))
message = "Host: %s Is Currently Available" % (str(ip))
except socket.error, e:
message = "Host: %s Is Currently Unavailable" % (key, val)
result_count += 1
msg_box("SeArCh CoMpLeTe", "%d REsults Were Found For %s"
% (result_count, str(ip))
except Exception, e: <------- Error
msg_box("", str(e))
msg_box("Search Complete", "No Results Were Found For %s" % (str(ip))
return
Error:
File "pygeo_ip.py", line 142
except Exception, e:
^
SyntaxError: invalid syntax
Pretty sure (without having tested anything) your problem is having missed the last close bracket
Line should read:
msg_box("SeArCh CoMpLeTe", "%d REsults Were Found For %s" % (result_count, str(ip)) )

webapp to desktop conversion issue using nightrain

I'm new here on Stackoverflow and this is my first question. I've searched here from the various questions if it's possible to create native desktop applications based on the web language php that is my specialization.
I've found some topic that talk about a github repository called nightrain. I've decided to download it to give a try, and I've also updated the php script version to the 7.2.10 but every time i try to start the build.py script, on my mac console will be printed an error. I'm not expert with the python, so I would ask if someone can help me to solve this issue, I've googled a bit but there aren't documentations about this script.
Here is the reported error
yur$ python /Users/yur/Desktop/nightrain-master/build.py
Traceback (most recent call last):
File "/Users/yur/Desktop/nightrain-master/build.py", line 19, in
compiler.compile_nightrain_mac()
File "/Users/yur/Desktop/nightrain-master/Classes/Compiler.py", line 179, in compile_nightrain_mac
call(["pyinstaller.py", "--clean", "-w", "-y", "-F", spec_path, application_icon, "-n", "nightrain", "Application.py"])
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 522, in call
return Popen(*popenargs, **kwargs).wait()
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 710, in init
errread, errwrite)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 1335, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
And this is the code of the build.py script
from Classes.Compiler import Compiler
from Classes.Settings import Settings
settings = Settings()
compiler = Compiler("./dist", "./nrtmp", "./Resources")
# clean output folder
compiler.clean_dist()
# compile nightrain
if compiler.is_windows():
compiler.compile_nightrain_windows()
if compiler.is_linux():
compiler.compile_nightrain_linux()
if compiler.is_mac():
compiler.compile_nightrain_mac()
# compile PHP
if compiler.is_windows():
compiler.compile_php_windows()
if compiler.is_linux():
compiler.compile_php_linux()
if compiler.is_mac():
compiler.compile_php_mac()
# copy required files
if compiler.is_windows():
compiler.copy_resources()
compiler.copy_php_windows()
settings.create_default_settings(compiler.get_settings_ini_dest())
if compiler.is_linux():
compiler.copy_resources()
compiler.copy_php_linux()
compiler.copy_php_ini_linux()
settings.create_default_settings(compiler.get_settings_ini_dest())
if compiler.is_mac():
app_version_dir = "%s/%s" % (compiler.output_dir, "app_version")
shell_version_dir = "%s/%s" % (compiler.output_dir, "shell_version")
nightrain_app_file_dest = "%s/nightrain.app" % app_version_dir
nightrain_shell_file_dest = "%s/nightrain" % shell_version_dir
nightrain_app_file_source = "%s/nightrain.app" % compiler.output_dir
nightrain_shell_file_source = "%s/nightrain" % compiler.output_dir
# create the output directories
compiler.make_dir(app_version_dir)
compiler.make_dir(shell_version_dir)
# move nightrain.app to app version dir
compiler.move_file(nightrain_app_file_source, nightrain_app_file_dest)
# move nightrain shell version to shell version dir
compiler.move_file(nightrain_shell_file_source, nightrain_shell_file_dest)
# copy PHP libraries to app version
destination = "%s/Contents/MacOS/lib/php" % nightrain_app_file_dest
compiler.copy_php_mac(destination)
# copy PHP libraries to shell version
destination = "%s/lib/php" % shell_version_dir
compiler.copy_php_mac(destination)
# copy resources to app version
mac_os_x_dir = "%s/Contents/MacOS" % nightrain_app_file_dest
compiler.copy_resources(mac_os_x_dir)
settings.create_default_settings("%s/%s" % (mac_os_x_dir, "settings.ini"))
# copy resources to shell version
compiler.copy_resources(shell_version_dir)
settings.create_default_settings("%s/%s" % (shell_version_dir, "settings.ini"))
# copy PHP ini to app version
destination = "%s/Contents/MacOS/lib/php/bin/php.ini" % nightrain_app_file_dest
compiler.copy_php_ini_mac(destination)
# copy php ini to app version
destination = "%s/lib/php/bin/php.ini" % shell_version_dir
compiler.copy_php_ini_mac(destination)
This is the Compiler.py script code
import sys
import os
import shutil
import urllib
import zipfile
import Settings
from subprocess import call
class Compiler:
build_dir = "./build"
output_dir = "./dist"
tmp_dir = "./nrtmp"
resources_dir = "./resources"
php_linux_binary_dir = "/home/naetech/php"
php_mac_binary_dir = "/Users/naetech/php"
php_windows_binary_dir = "C:\\nightrain_php"
def __init__(self, output_dir, tmp_dir, resources_dir):
self.output_dir = output_dir
self.tmp_dir = tmp_dir
self.resources_dir = resources_dir
#staticmethod
def is_linux():
platform = sys.platform
if "linux" in platform:
return True
else:
return False
#staticmethod
def is_windows():
if "win" in sys.platform and "darwin" not in sys.platform:
return True
else:
return False
#staticmethod
def is_mac():
if "darwin" in sys.platform:
return True
else:
return False
def compile_php_windows(self):
# remove the old binary
if os.path.exists(self.php_windows_binary_dir):
shutil.rmtree(self.php_windows_binary_dir)
# create a random tmp directory
if os.path.exists(self.tmp_dir):
shutil.rmtree(self.tmp_dir)
os.mkdir(self.tmp_dir)
# Non thread safe 64bit vers https://windows.php.net/downloads/releases/php-7.2.10-nts-Win32-VC15-x64.zip
# Thread safe 32bit vers https://windows.php.net/downloads/releases/php-7.2.10-Win32-VC15-x86.zip
# download the latest version of PHP
php_file_zip_download_link = "https://windows.php.net/downloads/releases/php-7.2.10-Win32-VC15-x86.zip"
php_file_zip_dest = "%s/%s" % (self.tmp_dir, "php-7.2.10-Win32-VC15-x86.zip")
print "Downloading %s" % php_file_zip_download_link
urllib.urlretrieve(php_file_zip_download_link, php_file_zip_dest)
print "Finished downloading %s" % php_file_zip_download_link
zfile = zipfile.ZipFile(php_file_zip_dest)
for name in zfile.namelist():
(dirname, filename) = os.path.split(name)
extracted_dir = "%s\\%s" % (self.php_windows_binary_dir, dirname)
print "Decompressing " + filename + " on " + dirname
if not os.path.exists(extracted_dir):
os.makedirs(extracted_dir)
zfile.extract(name, extracted_dir)
return True
def compile_php_mac(self):
# remove the old binary
if os.path.exists(self.php_mac_binary_dir):
shutil.rmtree(self.php_mac_binary_dir)
# create a random tmp directory
if os.path.exists(self.tmp_dir):
shutil.rmtree(self.tmp_dir)
os.mkdir(self.tmp_dir)
# download the latest version of PHP
php_tar_file_save_location = "%s/%s" % (self.tmp_dir, "php7210.tar.gz")
# fixme add a config file so the developers can update this link without modifying the source codes
# http://us1.php.net/get/php-7.2.10.tar.gz/from/this/mirror
php_tar_download_link = "http://us1.php.net/get/php-7.2.10.tar.gz/from/this/mirror"
self.download_file(php_tar_download_link, php_tar_file_save_location)
php_extracted_dir = "%s/%s" % (self.tmp_dir, "php7210")
os.mkdir(php_extracted_dir)
call(["tar", "-C", php_extracted_dir, "-zxvf", php_tar_file_save_location])
# compile PHP
php_source_dir = "%s/%s" % (php_extracted_dir, "php-7.2.10")
configure_command = "cd %s && ./configure --prefix=%s " \
"--enable-bcmath " \
"--enable-calendar " \
"--enable-mbstring " \
"--with-curl " \
"--with-gd " \
"--with-mysql " \
"--with-pdo-mysql " \
"--with-sqlite3" \
% (php_source_dir, self.php_mac_binary_dir)
call(configure_command, shell=True)
make_command = "cd %s && make && make install" % php_source_dir
call(make_command, shell=True)
return True
def compile_php_linux(self):
# remove the old binary
if os.path.exists(self.php_linux_binary_dir):
shutil.rmtree(self.php_linux_binary_dir)
# create a random tmp directory
if os.path.exists(self.tmp_dir):
shutil.rmtree(self.tmp_dir)
os.mkdir(self.tmp_dir)
# download the latest version of PHP
phpTarFile = "%s/%s" % (self.tmp_dir, "php7210.tar.gz")
call(["wget", "http://us1.php.net/get/php-7.2.10.tar.gz/from/this/mirror", "-O", phpTarFile])
phpDir = "%s/%s" % (self.tmp_dir, "php7210")
os.mkdir(phpDir)
call(["tar", "-C", phpDir, "-zxvf", phpTarFile])
# compile PHP
phpSourceDir = "%s/%s" % (phpDir, "php-7.2.10")
configureCommand = "cd %s && ./configure --prefix=%s " \
"--enable-bcmath " \
"--enable-calendar " \
"--enable-mbstring " \
"--with-curl " \
"--with-gd " \
"--with-mysql " \
"--with-pdo-mysql " \
"--with-sqlite3" \
% (phpSourceDir, self.php_linux_binary_dir)
call(configureCommand, shell=True)
makeCommand = "cd %s && make && make install" % (phpSourceDir)
call(makeCommand, shell=True)
return True
def compile_nightrain_windows(self):
self.clean_unncessary_files()
spec_path = "--specpath=%s/%s" % (self.build_dir, "specs")
application_icon = "--icon=%s/%s" % (self.resources_dir, "icon.ico")
# fixme When using the -w option, the final executable causes error
call(["pyinstaller.py", "--clean", "-y", "-F", spec_path, application_icon, "-n", "nightrain", "Application.py"],
shell=True)
self.clean_unncessary_files()
def compile_nightrain_linux(self):
self.clean_unncessary_files()
spec_path = "--specpath=%s/%s" % (self.build_dir, "specs")
call(["pyinstaller", "--clean", "-y", "-F", spec_path, "-n", "nightrain", "Application.py"])
self.clean_unncessary_files()
def compile_nightrain_mac(self):
self.clean_unncessary_files()
spec_path = "--specpath=%s/%s" % (self.build_dir, "specs")
application_icon = "--icon=%s/%s" % (self.resources_dir, "icon.ico")
call(["pyinstaller.py", "--clean", "-w", "-y", "-F", spec_path, application_icon, "-n", "nightrain", "Application.py"])
self.clean_unncessary_files()
def make_dir(self, path):
if not os.path.exists(path):
try:
os.mkdir(path)
print "Successfully created: %s" % path
return True
except:
print "Could not create %s" % path
return False
else:
return False
def move_file(self, source, destination):
if os.path.exists(source):
try:
shutil.move(source, destination)
print "Successfully moved %s to %s" % (source, destination)
return True
except:
print "Could not move %s to %s" % (source, destination)
return False
else:
return False
def copy_file(self, source, destination):
success_msg = "Successfully copied %s to %s" % (source, destination)
failure_msg = "Could not copy %s to %s" % (source, destination)
if os.path.exists(source) and os.path.isdir(source):
try:
shutil.copytree(source, destination)
print success_msg
return True
except:
print failure_msg
return False
elif os.path.exists(source) and os.path.isfile(source):
try:
shutil.copyfile(source, destination)
print success_msg
return True
except:
print failure_msg
return False
else:
return False
def copy_resources(self, custom_output_dir=None):
items = [
"www",
"icon.png",
"LICENSE"
]
for item in items:
if item == "icon.png" and (self.is_windows() or self.is_mac()):
continue
source = "%s/%s" % (self.resources_dir, item)
if not custom_output_dir:
destination = "%s/%s" % (self.output_dir, item)
else:
destination = "%s/%s" % (custom_output_dir, item)
if os.path.exists(source):
error = "Could not copy item %s" % (item)
success = "Successfully copied %s to %s" % (source, destination)
if os.path.isfile(source):
try:
shutil.copyfile(source, destination)
print success
except:
print error
return False
else:
try:
shutil.copytree(source, destination)
print success
except:
print error
return False
else:
print "%s does not exist" % (item)
return False
def copy_php_windows(self):
destination = "%s/%s/%s" % (self.output_dir, "lib", "php")
if os.path.exists(self.php_windows_binary_dir):
try:
shutil.copytree(self.php_windows_binary_dir, destination)
print "Successfully copied %s to %s" % (self.php_windows_binary_dir, destination)
return True
except:
print "Could not copy %s to %s" % (self.php_windows_binary_dir, destination)
return False
else:
return False
def copy_php_mac(self, destination_dir):
if not self.copy_file(self.php_mac_binary_dir, destination_dir):
return False
return True
def copy_php_linux(self):
destination = "%s/%s/%s" % (self.output_dir, "lib", "php")
if os.path.exists(self.php_linux_binary_dir):
try:
shutil.copytree(self.php_linux_binary_dir, destination)
print "Successfully copied %s to %s" % (self.php_linux_binary_dir, destination)
return True
except:
print "Could not copy %s to %s" % (self.php_linux_binary_dir, destination)
return False
else:
return False
def copy_php_ini_linux(self):
src = "%s/%s" % (self.resources_dir, "php.ini")
destination = self.get_php_ini_dest()
try:
shutil.copyfile(src, destination)
print "Successfully copied %s to %s" % (src, destination)
return True
except:
return False
def copy_php_ini_windows(self):
php_ini_src = "%s\\%s" % (self.php_windows_binary_dir, "php.ini-production")
php_ini_dest = self.get_php_ini_dest()
if os.path.exists(php_ini_src):
try:
shutil.copyfile(php_ini_src, php_ini_dest)
print "Successfully copied %s to %s" % (php_ini_src, php_ini_dest)
# replace configs
php_ini_configs = [
'; extension_dir = "ext"',
';extension=php_gd2.dll',
';extension=php_mbstring.dll',
';extension=php_sqlite3.dll'
]
for config in php_ini_configs:
config_uncommented = config.replace(";", "").strip()
Settings.Settings.replace(php_ini_dest, config, config_uncommented)
print "Replaced %s with %s in %s" % (config, config_uncommented, php_ini_dest)
return True
except:
return False
else:
print "Could not find %s" % php_ini_src
def copy_php_ini_mac(self, dest):
source = "%s/settings.ini" % self.resources_dir
return self.copy_file(source, dest)
def clean_dist(self):
if os.path.exists(self.output_dir):
shutil.rmtree(self.output_dir)
def clean_unncessary_files(self):
if os.path.exists(self.tmp_dir):
shutil.rmtree(self.tmp_dir)
if os.path.exists(self.build_dir):
shutil.rmtree(self.build_dir)
def remove_file(self, file_path):
if os.path.exists(file_path):
shutil.rmtree(file_path)
def get_php_ini_dest(self):
if self.is_linux() or self.is_mac():
return "%s/%s/%s/%s/%s" % (self.output_dir, "lib", "php", "bin", "php.ini")
elif self.is_windows():
return "%s/%s/%s/%s" % (self.output_dir, "lib", "php", "php.ini")
else:
return False
def get_settings_ini_dest(self):
return "%s/%s" % (self.output_dir, "settings.ini")
def download_file(self, download_link, where_to_save_file_including_file_name):
print "Downloading %s" % download_link
urllib.urlretrieve(download_link, where_to_save_file_including_file_name)
print "Finished downloading %s" % download_link
print "File saved to %s" % download_link

Add time stamp to end of file name before upload to ftp

I am using the following function to upload mp4 file to ftp
def run(self):
while True:
status = "Failed"
#logger.debug("Queue size: %s" %(str(self.queue.qsize())))
(env, pfile) = self.queue.get()
logger.debug("Thread %s Received %s and %s" %(str(self.threadID), pfile, env))
metaName = "%s/%s.evs.xml" %(self.config[env]["upload_folder"], pfile)
mediaName = "%s/%s.mp4" %(self.config[env]["upload_folder"], pfile)
mediaName2 = "%s.mp4" %(pfile,)
logger.info("Thread %s - Uploading metadata to %s FTP: %s" %(str(self.threadID), env, metaName))
try:
ur = uploadFTPMP(metaName, env)
status = "Success"
except:
logger.debug("Thread %s - Uploading of metadata %s to %s failed" %(str(self.threadID), metaName, env))
uploadComplete(pfile, status, env)
if status == "Success":
logger.info("Thread %s - Sleeping to allow cms to pick up xml" %(str(self.threadID)))
time.sleep(90)
logger.info( "Thread %s - Uploading mediafile %s to %s" %(str(self.threadID), mediaName, env))
ur = uploadFTP(mediaName, env)
status = "Success"
filename = os.path.basename(mediaName)
http_client.HTTPConnection.debuglevel = 1
logging.basicConfig(level=logging.INFO)
logging.basicConfig()
logging.getLogger().setLevel(logging.INFO)
requests_log = logging.getLogger("requests.packages.urllib3")
requests_log.setLevel(logging.INFO)
requests_log.propagate = True
url = 'http://www.webdev.com/web/home/testPOST'
headers = {'content-type': 'application/json'}
payload = {'mediaName': mediaName2 ,'status': 'sucsses'}
r = requests.post(url, data=json.dumps(payload), headers=headers)
r.text
r.status_code
r.connection.close()
uploadComplete(pfile, status, env)
logger.info("Thread %s - Upload completed with status %s" %(str(self.threadID), status))
self.queue.task_done()
I'm trying to modify the mp4 file before up, time stamp to end of the file so the file name will be video-%H%M%S.mp4 then it will be uploaded.
Then, when I perform the post request, as you can see, it sends 2 parameters now, I need to add 3rd parameter which is the new name with time stamp. Any tips to achieve this logic?
Here is my ftp function also.
def uploadFTPMP(filepath, env):
global config
ftpsrv = config[env]["active"]
ftpusr = config[env]["ftpuser"]
ftppwd = config[env]["ftppass"]
filename = os.path.basename(filepath)
try:
ftp = ftplib.FTP(ftpsrv)
ftp.login(ftpusr, ftppwd)
except:
logger.error("Ftp connection error has occurred")
raise
else:
f = open(filepath, "r")
cmd = "STOR %s" %(filename)
out = ftp.storbinary(cmd, f)
f.close()
ftp.quit()
return out
You should pass the datetime to the filename.
import datetime
medianame = 'somefile_{timestamp}.mp4'.format(
timestamp=datetime.datetime.now().isoformat()
)
The datetime can also be formatted as you require e.g. datetime.datetime.now().strftime('%Y-%m-%d_%H%M'). The strftime() documentation has a list of accepted formatting directives that can be used.

Making a module use functions and variables defined within the main program

I'm making an IRC bot for my network. To make the code cleaner, I am defining functions in modules. All these modules are in a folder called "plugins". One module say calls the function sendMsg and fails because it's trying to run a function defined in the main program. I also want to have this module to be able to access variables defined in the main program after the program has started.
import socket
import time
import re
from plugins.say import *
host = "irc.somenetwork.net"
port = 6667
nick = "ircbot"
channels = "##bottesting"
s = socket.socket()
def connect():
s.connect((host, port))
s.send("NICK %s\r\n" % nick)
s.send("USER %s %s nul :%s\r\n" % (nick, nick, nick))
time.sleep(3)
s.send("JOIN %s\r\n" % channels)
time.sleep(3)
def sendMsg(chan, msgSend):
s.send("PRIVMSG %s :%s\r\n" % (chan,msgSend))
# print "Sending message \"%s\" to channel/user \"%s\"" % (msgSend, chan)
def quitServ(quitMsg="m8bot"):
s.send("QUIT %s\r\n" % quitMsg)
connect()
while 1:
msgRaw = s.recv(1024)
print msgRaw
if msgRaw == "":
break
if "PING" in msgRaw:
print "Pong!"
PONG = msgRaw.split(' ')
PONG[0] = PONG[0].replace('PING','PONG')
PONG = ' '.join(PONG)
s.send("%s\r\n" % PONG)
if "PRIVMSG" in msgRaw:
# print "PRIVMSG detected"
user = ''.join(re.compile("(?<=:).{0,}(?=.{0,}!)").findall(msgRaw.split(' ')[0]))
channel = msgRaw.split(' ')[2]
command = (' '.join(msgRaw.split(' ')[3:]).replace(":","",1)).split(' ')[0]
msg = ''.join((' '.join(msgRaw.split(' ')[3:]).replace(":","",1)).split(' ')[1:]).replace("\r\n","")
if not "#" in channel:
channel = user
print "Nick: %s\nChannel: %s\nCommand: %s\nMsg: %s" % (user,channel,command,msg)
if ".quit" in command:
if msg:
quitServ(str(msg))
else:
quitServ()
if ".hello" in command:
# print "Attempting to send Hello World message."
sendMsg(channel, "Hello World!")
if ".say" in command:
say(msg)
quitServ()
This is my program. function say() is as follows:
def say(msg):
sendMsg(channel, "You said: %s" % msg)
I can see what the problem is, but I don't know how I would fix this. Feedback appreciated :)
-Nia
Try import __main__ in your say.py.
And then your say function should look something like this:
def say():
__main__.sendMsg(channel, "You said: %s" % msg)
But this is not a best solution. Just solution with less code changes.

Printing Ascii Text from using Telnet in Python 3.0

So I'm unable to actually print all of the information that I see after issuing a "help" command. Do i need to change the length of the skt.receive()? Or is there a way to simply print all of the data that comes through? It seems like there has to be a way to account for a data that you want to print of an unknown length? Or am I approaching this in the wrong way.
Thanks.
#!/usr/bin/python
host = '192.168.1.50'
port = 23
msg = "help\r"
msg2 = "y\r"
import socket
import sys
import time
try:
skt = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error, e:
print("Error creating socket: %s" % e)
sys.exit(1)
try:
skt.connect((host,port))
except socket.gaierror, e:
print("Address-related error connecting to server: %s" % e)
sys.exit(1)
except socket.error, e:
print("Error connecting to socket: %s" % e)
time.sleep(15)
skt.connect((host,port))
sys.exit(1)
try:
print(skt.send(msg))
skt.send('help\r')
print("SEND: %s" % msg)
except socket.error, e:
print("Error sending data: %s" % e)
sys.exit(1)
while 1:
try:
buf = skt.recv(50000000000)
if(len(buf)):
print(buf)
if 'AMX' in buf:
print("Length buff")
if 'AMX' in buf:
print(skt.send(msg))
#print("first wait")
#print("RECV: %s" % buf)
#time.sleep(9)
#print("second wait")
sys.exit(1)
except socket.error, e:
print("Error receiving data: %s" % e)
sys.exit(1)
if not len(buf):
break
sys.stdout.write(buf)
Have you considered using telnetlib, rather than re-inventing the wheel? :)
Example:
import telnetlib
HOST = "192.168.1.50"
tn = telnetlib.Telnet(HOST)
tn.write("help\n")
print tn.read_all()
So the telnetlib def makes things easier and streamlines the process. No sense in reinventing the wheel.

Categories