I try search some mail,but it does not work, my code:
`
conn = imaplib.IMAP4_SSL('imap.qq.com',993)
# login
try:
conn.login(config.MAIL_ADDRESS, config.MAIL_PASSWORD)
except Exception as err:
print 'connect fail: ',err
conn.select("inbox")
typ, data = conn.search(None,'(SUBJECT "test")')
print"UID list length is %i" % len(string.split(data[0]))`
run this code, it can print all mails. It seems search does not work.
I do not know where is wrong.I use python 2.7
Related
I'm trying to print a text a text file from a webserver in a python program but I am receiving errors. Any help would be greatly appreciated, here is my code:
import RPi.GPIO as GPIO
import urllib2
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(5,GPIO.OUT)
true = 1
while(true):
try:
response = urllib2.urlopen('http://148.251.158.132/k.txt')
status = response.read()
except urllib2.HTTPError, e:
print e.code
except urllib2.URLError, e:
print e.args
print status
if status=='bulbion':
GPIO.output(5,True)
elif status=='bulbioff':
GPIO.output(5,False)
By your comments, it appears your error: "SyntaxError: Missing parentheses in call to print", is caused by excluding parentheses/brackets in your print statements. People usually experience these errors after they update their python version, as the old print statements never required parentheses. The other error: "SyntaxError: unindent does not match any outer indentation level", is because your print statement on line 16 is one space behind all of your other statements on that indentation level, you can fix this problem by moving the print statement one space forward.
Changing your code to this should fix the problems:
import RPi.GPIO as GPIO
import urllib2
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(5,GPIO.OUT)
true = 1
while(true):
try:
response = urllib2.urlopen('http://148.251.158.132/k.txt')
status = response.read()
except urllib2.HTTPError, e:
print (e.code)
except urllib2.URLError, e:
print (e.args)
print (status)
if status=='bulbion':
GPIO.output(5,True)
elif status=='bulbioff':
GPIO.output(5,False)
Hope this helps!
My requirement is to capture logs for a particular http request sent to server from project server log file. So have written two function and trying to execute them parallel using multiprocessing module. But only one is getting executed. not sure what is going wrong.
My two functions - run_remote_command - using paramiko module for executing the tail command on remote server(linux box) and redirecting the output to a file. And send_request - using request module to make POST request from local system (windows laptop) to the server.
Code:
import multiprocessing as mp
import paramiko
import datetime
import requests
def run_remote_command():
basename = "sampletrace"
suffixname = datetime.datetime.now().strftime("%y%m%d_%H%M%S")
filename = "_".join([basename, suffixname])
print filename
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
ssh.connect(hostname='x.x.x.x',username='xxxx',password='xxxx')
except Exception as e:
print "SSH Connecting to Host failed"
print e
ssh.close()
print ssh
tail = "tail -1cf /var/opt/logs/myprojectlogFile.txt >"
cmdStr = tail + " " + filename
result = ''
try:
stdin, stdout, stderr = ssh.exec_command(cmdStr)
print "error:" +str( stderr.readlines())
print stdout
#logger.info("return output : response=%s" %(self.resp_result))
except Exception as e:
print 'Run remote command failed cmd'
print e
ssh.close()
def send_request():
request_session = requests.Session()
headers = {"Content-Type": "application/x-www-form-urlencoded"}
data = "some data "
URL = "http://X.X.X.X:xxxx/request"
request_session.headers.update(headers)
resp = request_session.post(URL, data=data)
print resp.status_code
print resp.request.headers
print resp.text
def runInParallel(*fns):
proc = []
for fn in fns:
p = mp.Process(target=fn)
p.start()
proc.append(p)
for p in proc:
p.join()
if __name__ == '__main__':
runInParallel(run_remote_command, send_request)
Output: only the function send_request is getting executed. Even I check the process list of the server there is no tail process is getting created
200
Edited the code per the #Ilja comment
I just wrote a simple webscraping script to give me all the episode links on a particular site's page. The script was working fine, but, now it's broke. I didn't change anything.
Try this URL (For scraping ) :- http://www.crunchyroll.com/tabi-machi-late-show
Now, the script works mid-way and gives me an error stating, ' Element not found in the cache - perhaps the page has changed since it was looked up'
I looked it up on internet and people said about using the 'implicit wait' command at certain places. I did that, still no luck.
UPDATE : I tried this script in a demote desktop and it's working there without any problems.
Here's my script :-
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import os
import time
from subprocess import Popen
#------------------------------------------------
try:
Link = raw_input("Please enter your Link : ")
if not Link:
raise ValueError('Please Enter A Link To The Anime Page. This Application Will now Exit in 5 Seconds.')
except ValueError as e:
print(e)
time.sleep(5)
exit()
print 'Analyzing the Page. Hold on a minute.'
driver = webdriver.Firefox()
driver.get(Link)
assert "Crunchyroll" in driver.title
driver.implicitly_wait(5) # <-- I tried removing this lines as well. No luck.
elem = driver.find_elements_by_xpath("//*[#href]")
driver.implicitly_wait(10) # <-- I tried removing this lines as well. No luck.
text_file = open("BatchLink.txt", "w")
print 'Fetching The Links, please wait.'
for elem in elem:
x = elem.get_attribute("href")
#print x
text_file.write(x+'\n')
print 'Links have been fetched. Just doing the final cleaning now.'
text_file.close()
CleanFile = open("queue.txt", "w")
with open('BatchLink.txt') as f:
mylist = f.read().splitlines()
#print mylist
with open('BatchLink.txt', 'r') as inF:
for line in inF:
if 'episode' in line:
CleanFile.write(line)
print 'Please Check the file named queue.txt'
CleanFile.close()
os.remove('BatchLink.txt')
driver.close()
Here's a screenshot of the error (might be of some help) :
http://i.imgur.com/SaANlsg.png
Ok i didn't work with python but know the problem
you have variable that you init -> elem = driver.find_elements_by_xpath("//*[#href]")
after that you doing some things with it in loop
before you finishing the loop try to init this variable again
elem = driver.find_elements_by_xpath("//*[#href]")
The thing is that the DOM is changes and you loosing the element collection.
I have the following code:
import paramiko
import time
import re
import sys
import random
import fileinput
ip_address = raw_input("Enter a valid WAP IP: ")
#Open SSHv2 connection to devices
def open_ssh_conn(ip):
try:
#Logging into device
session = paramiko.SSHClient()
#AutoAddPolicy
session.set_missing_host_key_policy(paramiko.AutoAddPolicy())
#Passing the necessary
session.connect(ip, username = 'myUsername', password = 'myPassword')
#Start an interactive shell session on the switch
connection = session.invoke_shell()
#Commands
connection.send("enable\n")
time.sleep(1)
connection.send("show version\n")
time.sleep(1)
#Checking command output for IOS syntax errors
output = connection.recv(65535)
#Checking command output for IOS Syntax errors
if re.search(r"% Invalid input detected at", output):
print "* There was at least one IOS syntax error on device %s" % ip
else:
print "\nDONE for device %s" % ip
#Test for reading command output
print output + "\n"
#Closing the connection
session.close()
except paramiko.AuthenticationException:
print "* Invalid username or password. \n* Please check
the username/password file or the device configuration!"
print "* Closing program...\n"
#Calling the SSH function
open_ssh_conn(ip_address)
How can I test multiple credential without getting kick out of the program when an exception is caught?
for example, try this new credentials:
session.connect(ip, username = 'myNewUsername', password = 'myNewPassword')
I figured it out! I created a nested list with the credentials:
list = [['username1', 'password1'], ['username2', 'password2'], \
['username3', 'password3']]
Then, created a for loop and put my code inside:
for elem in list:
my code...
# this is the connect line:
session.connect(ip, username = elem[0], password = elem[1])
That did it!!!!
Ok, I've tried to resolve this with a couple of different libraries. I'm working on a script to look at thousands of sites and kick out specific items on the pages. I need to be able to reset the connection so that the script will continue without losing any data. I've tried catching the error and waiting but that doesn't seem to fix it as it eventually causes the script to error completely out. I get the error on the below snippet of code in my status check module.
def status(url): #checks the response code
try:
req=urllib2.urlopen(url)
response=req.getcode()
return response
except urllib2.HTTPError, e:
return e.code
print e.code
except urllib2.URLError, e:
print e.args
return e.args
But before trying this I used the below as instead of urrlib2
parsedurl = urlparse(url)
conn = httplib.HTTPConnection(parsedurl.netloc)
conn.request('HEAD',parsedurl.path)
response = conn.getresponse()
return response.status