Python3 Idle keeps closing with ctrl + D - python

So I've linked about 5 files together I think, and I've added a piece of code to all those files which SHOULD prevent the idle from closing. But when I reach the last file:
# modules
import smtplib
from email.message import EmailMessage
#from pynput.keyboard import Key, Listener
ans1 = input("Your gmail address: ")
ans0 = input("Your gmail password(Not shown): ")
ans = input("Name of game: ")
print("Enter/Paste your code. Ctrl-D to send it.")
contents = []
while True:
try:
line = input()
except EOFError:
break
contents.append(line)
# content
sender = ans1
reciever = "rockzombie005#gmail.com"
password = ans0
msg_body = "\n".join(contents)
# action
msg = EmailMessage()
msg['subject'] = ans
msg['from'] = sender
msg['to'] = reciever
msg.set_content(msg_body)
with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:
smtp.login(sender,password)
smtp.send_message(msg)
print("Program sent successfully!")
try:
input()
except EOFError:
pass
and as you can see:
try:
input()
except EOFError:
pass
that piece of code should prevent the idle from closing, and it works, but only if I run it separately. If I do ctrl + D when executed using a different file, the shell just closes or crashes without any prompt.

In the Linux command-line shell, pressing Ctrl+D logs out of the interface. If you used the sudo command to execute commands as another user, pressing Ctrl+D exits out of that other user and puts you back as the user you originally logged into.
You can disable eof generally in bash:
set -o ignoreeof
Alternatively, You can use the IGNOREEOF environment variable in bash. So export IGNOREEOF=42 and you'll have to press Ctrl+D forty-two times before it actually quits your shell.

Related

Windows Task Scheduler Running Executable without reading File

I'm trying to have Task Scheduler run an executable on windows startup. The executable is a simple python script that reads a list of IPs from a .txt, pings them, and repeats after a set interval, like a basic heartbeat.
The executable was created using pyinstaller successfully, and runs perfectly when used manually.
However, when I try and have task scheduler run the same executable in the same directory, it does so without reading the .txt file, and immediately closing.
The following is the code,
import os
import time
import smtplib
from email.message import EmailMessage #allows for the email system to work
from datetime import datetime #allows the text files to have the date & time
from win10toast import ToastNotifier #allows for desktop notificaitons to appear on windows devices
import schedule #automatically schedules when the script executes
# Scans the IPs in the txt file
def notif():
with open (r'sydvlan.txt') as file:
dump = file.read() #reads the lines of the sydvlan.txt file
dump = dump.splitlines()
#creates a new log file and makes the title the current date and time
cdString = datetime.now().strftime("%d_%m_%Y %H_%M")
report = open(r'HeartbeatResults_{0}.txt'.format(cdString), 'w') #creates a log with the date&time
for line in dump:
lineList = line.split(":")
lineText = lineList[0] #makes sure that only the IP is being read from sydvlan.txt
IP = lineList[1].strip()
print("Currently Pinging {} on {}".format(lineText,IP))
print("------------------"*3)
# Get Date and Time at time of ping.
currentDate = datetime.now()
cdString = currentDate.strftime("%d_%m_%Y %H:%M:%S")
# pings the IPs from the txt
response = os.popen(f"ping {IP} -n 4").read() #pings the device
print("------------------"*3)
# If the os.popen() returns 0, it means the operation completed without any errors, so if it returns 0 it is successful.
if "Received >= 1" and "Approximate" in response:
report.write("UP {0} Successful {1}".format(lineText, cdString) + "\n")
else:
report.write("DOWN {0} UnSuccessful {1}".format(lineText, cdString) + "\n")
if "Received = 0" or "unreachable" in response: #Sends an email to IT staff if the ping fails
#composes the email message
#email_alert("Issue with {0}".format(lineText, cdString), "The Hearbeat Notification System Works :)")
toaster = ToastNotifier()
toaster.show_toast("Issue with {0}: {1} on {2}".format(lineText, IP, cdString), "Please Fix Now", duration=10, icon_path='Warning.ico')
time.sleep(1)
report.write("Hearbeat Protocol Complete" + "\n")
file.close()
#email notification setup
#def email_alert(subject, body):
# mailListFile = open(r'XXXXX.txt')
# emailList = (mailListFile.read()).splitlines()
# msg = EmailMessage()
# msg.set_content(body)
# msg['subject'] = subject
# msg['to'] = ', '.join(emailList)
# user = "XXXXX"
# msg['from'] = user
# password = "XXXXXX"
# server = smtplib.SMTP("smtp.gmail.com", 587)
# server.starttls()
# server.login(user, password)
# server.send_message(msg)
# server.quit()
#allows for the entire script to run every 300 seconds (or whatever is specified)
if __name__ == '__main__':
notif()
while True:
schedule.run_pending()
time.sleep(1)
schedule.every(5).minutes.do(notif)
The only argument I used when creating the executable was --onefile
Thank you for your time.
Your filename r'sydvlan.txt' is a relative path, so its location depends on the current working directory when the program is invoked.
Either try to use absolue paths, e.g. r'C:\path\to\file\sydvlan.txt' (do this for r'HeartbeatResults_{0}.txt', too) or set "Start in (optional)" parameter in the Windows task scheduler to the path where your txt file is located.

Sending an email to gmail based off a notification from Arduino to serial port

So I am trying to do a plant monitoring environment project which I have the arduino/embedded side working. The idea is when it falls below a certain threshold in the sensors the embedded side sends a string via bluetooth module to serial ports which this python script is listening to. If the script detects one of the strings on the port it sends an email message to the inputted email.
However as it stands right now it doesn't seem to be sending the email off to the user inputted email, I am unsure if the issue lies in my send_email method or in the main loop itself but after filling in all the user input values it just loops forever doing nothing not even printing the No Email Sent case and I am currently unsure why. Additionally there was some issues with the getpass3 function and scrambling the password in terminal so for the time being I've switched to raw_input once I get the email send functioning I plan to switch back to the getpass3 and fix it as all it did before was type display the prompt for enter password and then hang at that point.
This is my second program in python so it's entirely possible I've misinterpreted how some of these methods are called or passed but from what I've looked at in the documentation so far I don't see anything wrong on that side. I've gotten the adruino to send info across the serial port before, but there might be an issue with the bluetooth device pairing which I've noticed has happened before for reference the module is the HC-05 and I've gotten it to send the info across to TeraTerm before.
import time
import serial
import smtplib
import colorama
import getpass3
useremail = raw_input("Enter your email ")
# getpass3.set_echo = '#'
# userpass = getpass3.getpass("Enter your password: ")
userpass = raw_input("Enter your password ")
usercom = raw_input("Please Enter COMPORT: ").upper()
print usercom
TO = useremail
GMAIL_USER = useremail
GMAIL_PASS = userpass #plaintext need to get getpass3 working i hate this way
SUBJECT = 'Plant Environment Needs Attention'
TEXT1 = 'Low Light Levels Detected in the Enclosure'
TEXT2 = 'Low Mositure in the Soil Detected in the Enclosure'
TEXT3 = 'Temperature Outside of Safe Range in Enclosure'
TEXT4 = 'Humidity Outside of Safe Range in Enclosure'
ser = serial.Serial(usercom, 9600) #seems to always be COM9 on my PC can adjust as needed
def send_email(TEXT):
print("Sending Email")
#SMTP server setup
smtpserver = smtplib.SMTP("smtp.gmail.com",587)
smtpserver.ehlo()
smtpserver.starttls()
smtpserver.ehlo()
#login to gmail can potentially add diff email client if wanted
smtpserver.login(GMAIL_USER, GMAIL_PASS)
header = 'To:' + TO + '\n' + 'From: ' + GMAIL_USER
header = header + '\n' + 'Subject:' + SUBJECT + '\n'
# #form the diff cases here based off if its temp hum ect
print header
msg = header + '\n' + TEXT + ' \n\n'
#send email and close server for security reasons
smtpserver.sendmail(GMAIL_USER, TO, msg)
smtpserver.close()
# just do it forever
while True:
message = ser.readline()
print(message)
#big brained implamentation
#L = light
if message[0] == 'L' :
send_email(TEXT1)
print("Email Sent")
#S = Soil Moisutre
if message[0] == 'S' :
send_email(TEXT2)
print("Email Sent")
#T = temp
if message[0] == 'T' :
send_email(TEXT3)
print("Email Sent")
#H = Humidity
if message[0] == 'H' :
print("Email Sent")
send_email(TEXT4)
else:
print("No Email Sent")
time.sleep(0.5)

Python not catching exceptions

I have this script:
#!/usr/bin/env python
#import needed modules
import telnetlib
import time
#define variables
HOST = "xxxxxx"
user = "xxxxxx"
password = "xxxxxx"
#open telnet connection
tn = telnetlib.Telnet(HOST, 10800)
time.sleep(2)
#check for initial screen and press enter to go to login
tn.read_until("Device")
tn.write("\r\n")
time.sleep(2)
#Wait for username prompt and enter user/pass
try:
tn.read_until("User Name:",5)
except:
#Timeout looking for Username prompt
print "CRITICAL: User Name prompt never arrived"
exit(2)
tn.write(user + "\r\n")
tn.read_until("Password :")
tn.write(password + "\r\n")
time.sleep(2)
#wait for logout prompt
try:
tn.read_until("7<Logout >",5)
except:
#Timeout looking for successful login
print "CRITICAL: Did not login successfully"
exit(2)
#Logout and close connection
tn.write("7\r")
tn.close()
#Exit with success
print "OK: Test login to MWA Succeeded"
exit(0)
No matter what I do, no exceptions are caught. I changed the read_until looking for "User Name:" to just some garbage characters and it still just gets to the end of the code. I'm hoping I'm just doing something very stupid and not an issue with telnetlib.
Thanks!
Per the docs:
Read until a given string, expected, is encountered or until timeout
seconds have passed.
When no match is found, return whatever is available instead, possibly
the empty string. Raise EOFError if the connection is closed and no
cooked data is available.
Check the return value in the try block, and if this value does not match your expectations, raise on your own to trigger the except case.

getpass.getpass() function in Python not working?

Running on Windows 7 and using PyCharm 2016.2.3 if that matters at all.
Anyway, I'm trying to write a program that sends an email to recipients, but I want the console to prompt for a password to login.
I heard that getpass.getpass() can be used to hide the input.
Here is my code:
import smtplib
import getpass
import sys
print('Starting...')
SERVER = "localhost"
FROM = "my#email.com"
while True:
password = getpass.getpass()
try:
smtpObj = smtplib.SMTP(SERVER)
smtpObj.login(FROM, password)
break
except smtplib.SMTPAuthenticationError:
print("Wrong Username/Password.")
except ConnectionRefusedError:
print("Connection refused.")
sys.exit()
TO = ["your#email.com"]
SUBJECT = "Hello!"
TEXT = "msg text"
message = """\
From: %s
To: %s
Subject: %s
%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)
smtpObj.sendmail(FROM, TO, message)
smtpObj.close()
print("Successfully sent email")
But when I run my code, here is the output:
Starting...
/Nothing else appears/
I know the default prompt for getpass() is 'Password:' but I get the same result even when I pass it a prompt string.
Any suggestions?
EDIT: The code continues to run indefinitely after it prints the string, but nothing else appears and no emails are sent.
For PyCharm 2018.3
Go to 'Edit Configurations' and then select 'Emulate terminal in output console'.
Answer provided by Abhyudaya Sharma
The problem you have is that you are launching it via PyCharm, which has it's own console (and is not the console used by getpass)
Running the code via a command prompt should work

Python script progress email

I have a Python script that loops through a list of 8 different machines and does a copy, execute, and test. I would like to receive an email after each loop. **I'm not sure what to google for this. I would appreciate any ideas that will help me with my task.
I am aware of the smtplib module, just not how to perform a certain task with it.
I did indeed check the handy search engine and found no previous questions that provided answers
Question: how would one break in the middle of a loop, send an email, then continue with the loop??????
I have an email when the script starts and an email when the script ends. I just want to be notified as the script progresses or if it fails.
Thank you in advance.
You're looking for Python's smtp library.
The example from the documentation is this:
import smtplib
def prompt(prompt):
return raw_input(prompt).strip()
fromaddr = prompt("From: ")
toaddrs = prompt("To: ").split()
print "Enter message, end with ^D (Unix) or ^Z (Windows):"
# Add the From: and To: headers at the start!
msg = ("From: %s\r\nTo: %s\r\n\r\n"
% (fromaddr, ", ".join(toaddrs)))
while 1:
try:
line = raw_input()
except EOFError:
break
if not line:
break
msg = msg + line
print "Message length is " + repr(len(msg))
server = smtplib.SMTP('localhost')
server.set_debuglevel(1)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()
Use the built-in email package to create your message if there's anything nonstandard you need to do with MIMEtypes/etc. Use the built-in smtplib package to send it (and create it if you don't have to do anything fancy).

Categories

Resources