appending command name to files python3 - python-3.x

While learning through the network automation with python, I have created a script to capture the few network switch details with some sorts of commands. i have explicitely kept the commands in commands.txt and login credentilas in a file devices.json in a Jason format to pick it from and when i run this it works as expected by creating a file with command out details with time stamp.
What i Want: As i have commands.txt file which has diffrent commands, where i would like to have an idea of creating a separate file for each command which i have into commands.txt. as of now everything getting captured to a single file, desired example ..
prod-stvdx-sw_vcs_details.txt-Apr-10-2018:12:53
prod-stvdx-sw_vcs.txt-Apr-10-2018:12:53
prod-stvdx-sw_fabric_trunk.txt-Apr-10-2018:12:53
Below is the script version:
from __future__ import absolute_import, division, print_function
import json
import netmiko
import signal
import sys
import time
timestamp = time.strftime('%b-%d-%Y:%H:%M')
signal.signal(signal.SIGPIPE, signal.SIG_DFL) # IOError: Broken pipe
signal.signal(signal.SIGINT, signal.SIG_DFL) # KeyboardInterrupt: Ctrl-C
if len(sys.argv) < 3:
print('Usage: cmdrunner.py commands.txt devices.json')
exit()
netmiko_exceptions = (netmiko.ssh_exception.NetMikoTimeoutException,
netmiko.ssh_exception.NetMikoAuthenticationException)
#username, password = getPass.get_credentials()
with open(sys.argv[1]) as cmd_file:
commands = cmd_file.readlines()
with open(sys.argv[2]) as dev_file:
devices = json.load(dev_file)
for device in devices:
#device['username'] = username
#device['password'] = password
try:
print('~' * 79)
print('Connecting to device:', device['ip'])
connection = netmiko.ConnectHandler(**device)
filename = connection.base_prompt + '.txt' + '-' + timestamp
with open(filename, 'w') as out_file:
for command in commands:
out_file.write('++++ Output of ' + command + '\n\n')
out_file.write(connection.send_command(command) + '\n\n')
connection.disconnect()
except netmiko_exceptions as e:
print('Failed to ', device['ip'], e)
My commands.txt File:
$ cat commands.txt
show vcs details
show vcs
show fabric islports
show fabric isl
show fabric trunk
show logging raslog
show version
show ip int brief
Run
$ ./brocade_2.py commands.txt devices.json
-rw-r--r-- 1 moli moli 286K Apr 10 12:53 prod-stvdx-sw.txt-Apr-10-2018:12:53

I think if I understand correctly, you want to capture the output of each command in a separate file:
from __future__ import absolute_import, division, print_function
import json
import netmiko
import signal
import sys
import time
timestamp = time.strftime('%b-%d-%Y:%H:%M')
signal.signal(signal.SIGPIPE, signal.SIG_DFL) # IOError: Broken pipe
signal.signal(signal.SIGINT, signal.SIG_DFL) # KeyboardInterrupt: Ctrl-C
if len(sys.argv) < 3:
print('Usage: cmdrunner.py commands.txt devices.json')
exit()
netmiko_exceptions = (netmiko.ssh_exception.NetMikoTimeoutException,
netmiko.ssh_exception.NetMikoAuthenticationException)
#username, password = getPass.get_credentials()
with open(sys.argv[1]) as cmd_file:
commands = cmd_file.readlines()
with open(sys.argv[2]) as dev_file:
devices = json.load(dev_file)
for device in devices:
#device['username'] = username
#device['password'] = password
try:
print('~' * 79)
print('Connecting to device:', device['ip'])
connection = netmiko.ConnectHandler(**device)
for command in commands:
filename = connection.base_prompt +'-'+ command+'.txt' + '-' + timestamp
with open(filename, 'w') as out_file:
out_file.write('++++ Output of ' + command + '\n\n')
out_file.write(connection.send_command(command) + '\n\n')
connection.disconnect()
except netmiko_exceptions as e:
print('Failed to ', device['ip'], e)

Related

How to print LIVE output of paramiko on tkinter text

I a new to Python.
I am executing commands on a server and writing its output in a file and on tkinter text.
Code is given below.
Is there any way to write live output using tkinter?
Right now, after executing all commands a text window is popping up with the output. As I have written sessionoutput.mainloop() after for loop.
Please suggest any way to do it simultaneously (see channel is giving output and printing live output on tkinter text).
Eventually, I am going to create 2 sets of commands which will run in parallel. So I cannot just use the command line output, as the output of the 2 sessions will get mixed up when we use threads.
So I need a separate window to display the output.
import paramiko
import sys
import time
import tkinter
def connect_to_ssh():
hostname_ip = "1.1.1.1"
username = "admin"
password = "admin"
output_file = open("singlerunOutput.txt", "a+")
port = 22
#exception handling
i = 0
while True:
try:
ssh = paramiko.SSHClient()
ssh.load_system_host_keys()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname_ip, 22, username, password)
break
except paramiko.AuthenticationException:
print("Authentication failed when connecting to %s" % hostname_ip)
sys.exit(1)
except:
print("Could not SSH to %s, waiting for it to start" % hostname_ip)
i += 1
time.sleep(2)
if i == 30:
print("Could not connect to %s. Giving up" % hostname_ip)
sys.exit(1)
print("\n****** Connection Successful ******")
output_cmd_list = list()
cmd1 ="config vdom"
cmd2 ="edit Test"
cmd3 ="diag sniffer packet any 100 l"
cmd5 = "end"
output_cmd_list.append(cmd1)
output_cmd_list.append(cmd2)
output_cmd_list.append(cmd3)
output_cmd_list.append(cmd5)
sessionoutput = tkinter.Tk()
sessionoutput.wm_title("outputwindow")
sessionoutput.geometry("600x400") # w and h
sessionop_text = tkinter.Text(sessionoutput, height=600, width=400)
session_output_tab = tkinter.Scrollbar(sessionoutput)
session_output_tab.pack(side=tkinter.RIGHT, fill=tkinter.Y)
session_output_tab.config(command=sessionop_text.yview)
sessionop_text.pack(side=tkinter.LEFT, fill=tkinter.Y)
channel = ssh.invoke_shell()
for command in output_cmd_list:
channel.send(command + '\n')
time.sleep(3)
channel.send(chr(3)) # CTRL+C
outlines = channel.recv(10240).decode("ascii")
sessionop_text.insert(tkinter.END, outlines)
print(outlines)
output_file.write(outlines)
sessionoutput.mainloop()
channel.close()
ssh.close()
output_file.close()
if __name__ == '__main__':
connect_to_ssh()

trying to copy file cretead by postgresql copy to command using python

I'm trying to send an CSV file that I create using this command :
copy ( select 1 as a ,2 as b ,3 as c) to '/var/lib/pgsql/output.csv' with delimiter ',' csv header;
I'm able to create the file only at /var/lib/pgsql/ because of permission errors that I'm getting.
now I'm trying or to move to file to a different location as /home/user/Desktop/someFolder or directly attach it to the mail.
this is the code:
#!/usr/bin/env python
import os
import subprocess
import psycopg2
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
import shutil
def fetch_all_postgres(pgsql_conn):
cmd = """ copy ( select 1 as a ,2 as b ,3 as c) to '/var/lib/pgsql/output.csv' with delimiter ',' csv header; """
cur = pgsql_conn.cursor()
cur.execute(cmd)
pgsql_conn.commit()
def send_mail():
msg = MIMEMultipart('alternative')
msg['Subject'] = "yuval script"
msg['From'] = From
msg['To'] = To
msg['Cc'] = copy
source_files = '/var/lib/pgsql/output.csv'
destination_folder = "/home/user/Desktop/somefolder/output.csv"
# first try
# shutil.move("/var/lib/pgsql/output.csv", "/home/user/Desktop/somefolder/output.csv")
# second try
# subprocess.run("mv %s %s" % (source_files, destination_folder), shell=True)
# therd try
# os.system("mv /var/lib/pgsql/output.csv /home/user/Desktop/somefolder/output.csv")
file_name = "output.csv"
attachment = open(source_files, "rb")
p = MIMEBase('application', 'octet-stream')
p.set_payload(attachment.read())
encoders.encode_base64(p)
p.add_header('Content-Disposition', "attachment; filename= %s" % file_name)
msg.attach(p)
s = smtplib.SMTP('smtp.gmail.com', 587)
s.starttls()
s.login(From, Passdune)
s.sendmail(From, To, msg.as_string())
s.quit()
def main():
print("connecting to db...")
conn = psycopg2.connect(CONNECTION_STRING)
fetch_all_postgres(conn)
send_mail()
print("end")
if __name__ == '__main__':
main()
this is the error if I trying to set the path of the copy to command to a different folder other then /var/lib/pgsql
psycopg2.ProgrammingError: could not open file
"/home/yaodav/Desktop/output1.csv" for writing: Permission denied
HINT: COPY TO instructs the PostgreSQL server process to write a
file. You may want a client-side facility such as psql's \copy.
this is the error on all the mv/copy command that Im trying :
Permission denied: '/var/lib/pgsql/output1.csv
I also tried this and this
Using copy commands from psycopg2:
cur = con.cursor()
f = open('test.csv', 'w')
cur.copy_expert("copy ( select 1 as a ,2 as b ,3 as c) to stdout with delimiter ',' csv header", f)
f.close()
cat /home/aklaver/test.csv
a,b,c
1,2,3

Import variable from pythonscript --> solve caused TypeError

I've been trying to build a speech-recognition application with gtts. What I want to do now is to use a variable from another python script so I can update a tk Label. I tried to put my code in a structure of a class to access the variable. I've added a smaller program to showcase my problem.
(These programs are ment to be running at the same time)
I'am a beginner in Python so I hope you guys can teach me how to do it better. :)
Thank you in advance!!
Error:
S = SuperAssistant()
TypeError: __init__() missing 1 required positional argument: 'audio'
basic example that showcases my problem:
from try_access_var import myfunction
print(myfunction.audio)
Then in my other pyscript called try_access_var:
def myfunction():
audio = 1
(My program where I want to implement the Solution I might get)
`from gtts import gTTS
import speech_recognition as sr
from playsound import playsound
import os
import re
import webbrowser
from tkinter import *
import smtplib
import requests
import sys
import subprocess
from subprocess import Popen
import time
import datetime as dt
from datetime import timedelta
import keyboard
import mouse
import pyaudio
import tkinter as tk
from tkinter import filedialog, Text
import csv
Note that "Class SuperAssistant" belongs to the code
class SuperAssistant:
def __init__(self):
self.audio = audio
def talkToMe(self):
"speaks audio passed as argument"
#SuperAssistant.audio = audio
print(self.audio)
tts = gTTS(text=audio, lang='en')
tts.save("good.mp3")
#os.system("cd C://Users//johan//OneDrive - Departement Bildung, Kultur und Sport Kanton Aargau-7988362-Kantonsschule Zofingen//DATA_SHAR//desktopAssistant-master")
#os.system("python -i C://Users//johan//OneDrive - Departement Bildung, Kultur und Sport Kanton Aargau-7988362-Kantonsschule Zofingen//DATA_SHAR//desktopAssistant-master//tkinter_samentha_tricks.py")
#os.system("python -i tkinter_samentha_tricks.py")
#force it to have no console
DETACHED_PROCESS = 0x00000008
subprocess.Popen("python -i tkinter_samentha_tricks.py") #creationflags=DETACHED_PROCESS)
while playsound("good.mp3"):
pass
os.remove("good.mp3")
#print(audio)
#for line in audio.splitlines():
# os.system("say " + audio)
#use the system's inbuilt say command instead of mpg123
#text_to_speech = gTTS(text=audio, lang='en')
#text_to_speech.save('audio.mp3')
#os.system('mpg123 audio.mp3')
def myCommand(self, x):
"listens for commands"
r = sr.Recognizer()
#mic_version= open("C:/Users/johan/OneDrive - Departement Bildung, Kultur und Sport Kanton Aargau-7988362-Kantonsschule Zofingen/DATA_SHARE/desktopAssistant-master/choose_mic_text.txt", "r")
#mic_integer=mic_version
#mic = sr.Microphone(device_index=mic_integer)
with sr.Microphone() as source:
print('Ready...')
r.pause_threshold = 1
r.adjust_for_ambient_noise(source, duration=1)
audio = r.listen(source)
if x == 1:
try:
command = r.recognize_google(audio).lower()
#talkToMe('You said: ' + command + '\n')
#add silent mode. for now: print only
print('You said: ' + command + '\n')
#loop back to continue to listen for commands if unrecognizable speech is received
except sr.UnknownValueError:
print('Your last command couldn\'t be heard')
command = SuperAssistant.myCommand(1);
return command
if x == 2:
try:
command02 = r.recognize_google(audio).lower()
#talkToMe('You said: ' + command + '\n')
#add silent mode. for now: print only
print('You said: ' + command02 + '\n')
#loop back to continue to listen for commands if unrecognizable speech is received
except sr.UnknownValueError:
print('Your last command couldn\'t be heard')
command02 = SuperAssistant.myCommand(2);
return command02
if x == 3:
try:
command03 = r.recognize_google(audio).lower()
#talkToMe('You said: ' + command + '\n')
#add silent mode. for now: print only
print('You said: ' + command03 + '\n')
#loop back to continue to listen for commands if unrecognizable speech is received
except sr.UnknownValueError:
print('Your last command couldn\'t be heard')
command03 = SuperAssistant.myCommand(3);
return command03
if x == 4:
try:
command04 = r.recognize_google(audio).lower()
#talkToMe('You said: ' + command + '\n')
#add silent mode. for now: print only
print('You said: ' + command04 + '\n')
#loop back to continue to listen for commands if unrecognizable speech is received
except sr.UnknownValueError:
print('Your last command couldn\'t be heard')
command04 = SuperAssistant.myCommand(4);
return command04
if x == 5:
try:
command05 = r.recognize_google(audio).lower()
#talkToMe('You said: ' + command + '\n')
#add silent mode. for now: print only
print('You said: ' + command05 + '\n')
#loop back to continue to listen for commands if unrecognizable speech is received
except sr.UnknownValueError:
print('Your last command couldn\'t be heard')
command05 = SuperAssistant.myCommand(5);
return command05
if x == 6:
try:
command06 = r.recognize_google(audio).lower()
#talkToMe('You said: ' + command + '\n')
#add silent mode. for now: print only
print('You said: ' + command06 + '\n')
#loop back to continue to listen for commands if unrecognizable speech is received
except sr.UnknownValueError:
print('Your last command couldn\'t be heard')
command06 = SuperAssistant.myCommand(6);
return command06
def time_greeting():
if 12 > dt.datetime.now().hour:
SuperAssistant.talkToMe('Good morning sir.')
elif 12 == dt.datetime.now().hour:
SuperAssistant.talkToMe('It is high noon, hope you are ready for your duel!')
elif (12 < dt.datetime.now().hour) and (18 > dt.datetime.now().hour):
SuperAssistant.talkToMe('Good afternoon sir.')
elif 18 < dt.datetime.now().hour:
SuperAssistant.talkToMe('Good evening sir.')
def time_bye():
if 12 > dt.datetime.now().hour:
SuperAssistant.talkToMe('wish you a nice morning sir.')
elif 12 == dt.datetime.now().hour:
SuperAssistant.talkToMe('wish you a good lunce sir.!')
elif (12 < dt.datetime.now().hour) and (18 > dt.datetime.now().hour):
SuperAssistant.talkToMe('wish you a good afternoon sir.')
elif 18 < dt.datetime.now().hour:
SuperAssistant.talkToMe('wish you good evening sir.')
def welcome():
SuperAssistant.talkToMe('My systems are booting up. Systems successfully booted!')
SuperAssistant.time_greeting()
SuperAssistant.talkToMe('How should I call you? Please tell me your name.')
global name
name = SuperAssistant.myCommand(1)
SuperAssistant.talkToMe('Nice to meet you ' + name +'.')
file=open("C://Users//johan//OneDrive - Departement Bildung, Kultur und Sport Kanton Aargau-7988362-Kantonsschule Zofingen//DATA_SHARE//desktopAssistant-master//userprofiles.txt", "r")
with open("C://Users//johan//OneDrive - Departement Bildung, Kultur und Sport Kanton Aargau-7988362-Kantonsschule Zofingen//DATA_SHARE//desktopAssistant-master//userprofiles.txt", "r") as profiles:
for line in profiles:
if name in line:
pass
for profiles in file.readlines():
print(profiles)
if name in profiles:
SuperAssistant.talkToMe('welcome back.')
file.close()
else:
SuperAssistant.talkToMe('Should I create a new profile?')
profilcreation=myCommand(2)
if 'yes' in profilcreation:
#questions to ask to create new profil
SuperAssistant.talkToMe('I am going to ask you some questions...')
SuperAssistant.talkToMe('What is your favorite color?')
question01_profilcreation=myCommand(3)
SuperAssistant.talkToMe('What is your favorid food?')
question02_profilcreation=myCommand(3)
SuperAssistant.talkToMe('When were you born?')
question03_profilcreation=myCommand(3)
file=open("C:/Users/johan/OneDrive - Departement Bildung, Kultur und Sport Kanton Aargau-7988362-Kantonsschule Zofingen/DATA_SHARE/desktopAssistant-master/userprofiles.txt", "a")
file.write('\n'+'['+'"'+name+'"'+','+'"'+question01_profilcreation+'"'+','+'"'+question02_profilcreation+'"'+','+'"'+question03_profilcreation+'"'+']')
elif 'no' in profilcreation:
SuperAssistant.talkToMe('profilcreation denied')
file.close()
return name
def load(element):
with open("C://Users//johan//OneDrive - Departement Bildung, Kultur und Sport Kanton Aargau-7988362-Kantonsschule Zofingen//DATA_SHARE//desktopAssistant-master//userprofiles.txt", "r") as profiles:
for line in profiles:
if name in line:
hole_item=line
#hole_item.append(line)
#profil_item=hole_item[element]
profil=hole_item.split(",")
print(profil)
profiles.close()
return profil[element]
all_the_lines = profiles.readlines()
items = []
for i in all_the_lines:
items.append(i)
print(items)
def assistant(command):
"if statements for executing commands"
global name
global check
if 'samantha' in command:
if (check == 0):
check = 1
SuperAssistant.welcome()
else:
SuperAssistant.talkToMe("What can I do for you")
command02 = SuperAssistant.myCommand(2)
if 'open reddit' in command02:
reg_ex = re.search('open reddit (.*)', command02)
url = 'https://www.reddit.com/'
if reg_ex:
subreddit = reg_ex.group(1)
url = url + 'r/' + subreddit
webbrowser.open(url)
print('Done!')
elif 'open youtube' in command02:
reg_ex = re.search('open website (.+)', command02)
print(command02)
song_title=command02[12:]
print(song_title)
url='https://www.youtube.com/results?search_query='+song_title
webbrowser.open(url)
talkToMe('Done!')
command03 = SuperAssistant.myCommand(3)
if 'play' in command03:
keyboard.press_and_release('tab','tab')
keyboard.press_and_release('enter')
command04 = SuperAssistant.myCommand(4)
if 'stop' in command04:
keyboard.press_and_release('space')
command04 = SuperAssistant.myCommand(4)
elif 'continue' in command04:
keyboard.press_and_release('space')
command04 = myCommand(4)
elif 'exit' in command03:
talkToMe('exit')
command = SuperAssistant.myCommand(1)
elif 'help' in command02:
talkToMe('I\'ve got some information for you.')`
This here is my code at the end of the function/class:
if __name__ == "__main__":
S = SuperAssistant()
S.talkToMe('I am ready for your command')
#loop to continue executing multiple commands
while True:
SuperAssistant.assistant(SuperAssistant.myCommand(1))
the code of the smaller program (show tk window) I opened with subprocess.Popen(....)
#importing the class/function
from desktopAssistant_wakeup import SuperAssistant
from tkinter import *
#printing out imported variable (if classes are used: object)
print(#way to print audio)
SuperAssistent does not have a class attribute named audio. For this you would have to set it somewhere in your class. For example, you could do something like SuperAssistent.audio = audio in talkToMe.
Is it on purpose that you use class methods only and do not instantiate SuperAudio? If that is not the case you should add a constructor and add self as first arguments of all methods that are not class methods.
I suggest to go through an introduction for Python classes/objects like this one on w3schools if that is the case.
Update:
Here is an example for setting and accessing class and instance attributes with split up files for script and class definition:
example.py:
class Foo():
class_attribute = 'class attribute: initial value'
def __init__(self):
self.instance_attribute = \
'instance attribute ({:X}): initial value'.format(id(self))
def do_something(self = None):
Foo.class_attribute = 'class_attribute: modified value'
if self is not None:
self.instance_attribute = \
'instance attribute ({:X}): modified value'.format(id(self))
script.py
#!/usr/bin/env python3
from example import Foo
a = Foo()
b = Foo()
print(Foo.class_attribute)
print(a.instance_attribute)
print(b.instance_attribute)
print('\nChanging attributes..\n')
Foo.do_something()
a.do_something()
b.do_something()
print(Foo.class_attribute)
print(a.instance_attribute)
print(b.instance_attribute)
Executing script.py gives the following output (note that IDs change between machines and executions:
class attribute: initial value
instance attribute (7F640ACF56A0): initial value
instance attribute (7F640AC2AB50): initial value
Changing attributes..
class_attribute: modified value
instance attribute (7F640ACF56A0): modified value
instance attribute (7F640AC2AB50): modified value

Best way to check the PDF file is corrupt using python

I try to check the PDF files are corrupted in windows environment and come up with following python code.
Just want to check is it the best way to check corrupted PDF files or is there any other easy way?
Note: C:\Temp\python\sample-map (1).pdf is the corrupted PDF file
Here is the sample code
import os
import subprocess
import re
from subprocess import Popen, PIPE
def checkFile(fullfile):
proc=subprocess.Popen(["file", "-b", fullfile], shell=True, stdout=PIPE, stderr=PIPE, bufsize=0)
# -b, --brief : do not prepend filenames to output lines
out, err = proc.communicate()
exitcode = proc.returncode
return exitcode, out, err
def searchFiles(dirpath):
pwdpath=os.path.dirname(os.path.realpath(__file__))
print("running path : %s" %pwdpath )
if os.access(dirpath, os.R_OK):
print("Path %s validation OK \n" %dirpath)
listfiles=os.listdir(dirpath)
for files in listfiles:
fullfile=os.path.join(dirpath, files)
if os.access(fullfile, os.R_OK):
code, out, error = checkFile(fullfile)
if str(code) !="0" or str(error, "utf-8") != "" or re.search("^(?!PDF(\s)).*", str(out,'utf-8')):
print("ERROR " + fullfile+"\n################")
else:
print("OK " + fullfile+"\n################")
else:
print("$s : File not readable" %fullfile)
else:
print("Path is not valid")
if __name__ == "__main__":
searchFiles('C:\Temp\python')
sample output :
$ "C:/Program Files (x86)/Python37-32/python.exe" c:/Users/myuser/python/check_pdf_file.py
running path : c:\Users\myuser\python
Path C:\Temp\python validation OK
OK C:\Temp\python\Induction Guide.pdf
################
ERROR C:\Temp\python\sample-map (1).pdf
################
OK C:\Temp\python\sample-map.pdf
################
I think you can use PyPDF2 module.
pip install pypdf2
The code is as follows.
from PyPDF2 import PdfFileReader
import os
def checkFile(fullfile):
with open(fullfile, 'rb') as f:
try:
pdf = PdfFileReader(f)
info = pdf.getDocumentInfo()
if info:
return True
else:
return False
except:
return False
def searchFiles(dirpath):
pwdpath = os.path.dirname(os.path.realpath(__file__))
print("running path : %s" %pwdpath )
if os.access(dirpath, os.R_OK):
print("Path %s validation OK \n" %dirpath)
listfiles = os.listdir(dirpath)
for f in listfiles:
fullfile = os.path.join(dirpath, f)
if checkFile(fullfile):
print("OK " + fullfile + "\n################")
else:
print("ERROR " + fullfile + "\n################")
else:
print("Path is not valid")
if __name__ == "__main__":
searchFiles('C:\Temp\python')
I tried to match your coding style.
I think this code can also be used on MacOS or Linux.

Only write when serial device outputs data

I am trying to make a data-logger than writes the output from a serial device that only outputs once per minute. I need it to have a time stamp on the output. The code I have so far will log the output but it keeps logging blanks with a timestamp in-between the device's output. How do I get it to only write a line with the timestamp when the device has output?
#!/usr/bin/env python
Log data from serial port
import argparse
import serial
import datetime
import time
import os
timestr = time.strftime("%Y%m%d")
Tstamp = time.strftime("%Y/%m/%d %H:%M ")
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("-d", "--device", help="device to read from", default="/dev/ttyUSB0")
parser.add_argument("-s", "--speed", help="speed in bps", default=9600, type=int)
args = parser.parse_args()
outputFilePath = os.path.join(os.path.dirname(__file__),
datetime.datetime.now().strftime("%Y-%m-%d") + ".csv")
with serial.Serial(args.device, args.speed) as ser, open(outputFilePath,'w') as outputFile:
print("Logging started. Ctrl-C to stop.")
try:
while True:
time.sleep(1)
x = (ser.read(ser.inWaiting()))
data = x.decode('UTF-8')
outputFile.write(Tstamp + " " + data + '\n')
outputFile.flush()
except KeyboardInterrupt:
print("Logging stopped")
Sorry for the poor formatting I am not sure how to make it look right on here.
By adding if x!= "" and indenting properly I got it to work. Now I just need ot fix it to append the file and not overwrite it.
#!/usr/bin/env python
# Log data from serial port
import argparse
import serial
import datetime
import time
import os
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("-d", "--device", help="device to read from", default="/dev/ttyUSB0")
parser.add_argument("-s", "--speed", help="speed in bps", default=9600, type=int)
args = parser.parse_args()
outputFilePath = os.path.join(os.path.dirname(__file__),
datetime.datetime.now().strftime("%Y-%m-%d") + ".csv")
with serial.Serial(args.device, args.speed) as ser, open(outputFilePath,'w') as outputFile:
print("Logging started. Ctrl-C to stop.")
try:
while True:
time.sleep(1)
x = (ser.read(ser.inWaiting()))
data = x.decode('UTF-8')
if data !="":
outputFile.write(time.strftime("%Y/%m/%d %H:%M ") + " " + data )
outputFile.flush()
except KeyboardInterrupt:
print("Logging stopped")

Resources