printing output in python to txt file - python

wrote a simple program and would like to print the output to a text file. I'm trying the following at the very top of my script:
python SagicorPremiumCalculator2.py > textfile.txt
But this is giving me a syntax error in idle. How is my syntax incorrect?
python SagicorPremiumCalculator2.py > textfile.txt
python SagicorPremiumCalculator2.py > textfile.txt
import openpyxl, os, sys
wb = openpyxl.load_workbook('example.xlsx')
Millar_sheet = wb.get_sheet_by_name('Millar')
client = []
output = []
print(os.getcwd())
for rowOfCellObjects in Millar_sheet['A2':'AA13']:
for cellObj in rowOfCellObjects:
#if cellObj.value != None:
#print(cellObj.coordinate, cellObj.value)
client.append(cellObj.value)
#print(client[2]) #client name
print(client[0]) #policy number
print(client[9]) #license plate
#output.append(client[0]) #1
#output.append(client[9]) #2
if client[12] != "Not Applicable":
float(client[12])
print('S.I. = ' + '$' + str("%0.2f" % client[12]))
#output.append("%0.2f" % client[12]) #3
else:
print('S.I. ' + client[12])
print('Basic = ' + '$' + str("%0.2f" % client[13]))
#output.append("%0.2f" % client[13])#3
if client[14] != None:
print('Loading = ' + str(100*client[14]) + '%')
else:
print('No Loading')
val = client[13]
if client[14] == None:
val = client[15] #if there is no loading percentage, val becomes subtotal
else:
val += (val*client[14]) # a = a + b, adds 150 to 1000
print('Subtotal = ' + '$' + str("%0.2f" % val))#good
if client[16] != None:
ATD = val*client[16] #discount amount
print('ATD = ' + str(100*client[16]) + '%, -$' + str("%0.2f" % ATD))
val -= (val*client[16])
print('$' + str("%0.2f" % val))
if client[17] != None:
val -= (val*client[17])
SP = val*client[17] #Discount amount
print('SP = ' + str(100*client[17]) + '%, -$' + str("%0.2f" % SP))
print('$' + str("%0.2f" % val))
if client[18] != None:
val = (val+client[18])
PAB = client[18]
print('PAB = +$' + str(client[18]))
print('$' + str("%0.2f" % val))
if client[19] != None:
NCD = val*client[19]
val -= (val*client[19])#discount amount
print('NCD = ' + str(100*client[19]) +'%, -$' + str("%0.2f" % NCD))
print('$' + "%0.2f" % val)
if client[20] != None:
val = (val+client[20])
print('W/S = +$' + str(client[20]))
print('$' + "%0.2f" % val)
if client[21] != None:
val = (val+client[21])
print('LOU = $' + str(client[21]))
print('$' + "%0.2f" % val)
if val < 750: #Applies minimum premium if val is under 750
print("Minimum premium applied")
val = 750
print('Pre-tax Premium is ' + '$' + str("%0.2f" % val)) #good
if client[23] == 0: #Client over 65, not being charged tax
print('According to Sagicor speadsheet, client over 65')
else:
PreTax = val*0.06
val = (PreTax+val)
print('Premium Tax = +$' + str("%0.2f" % PreTax)) #good
print('$' + "%0.2f" % val)
if client[25] != None:
print('RS = +$' + str(client[25]))
val = (val+client[25])
print('Total = $' + str("%0.2f" % val))
#if val == client[26]:
#print('Sagicor\'s total agrees with calculated total - top')
#else:
#print('Premium does not agree - top')
else:
print('Roadside assistance NOT included')
print('Total = $' + str("%0.2f" % val))
#if val == client[26]:
#print('Sagicor\'s total agrees with calculated total - bottom')
#else:
#print('Premium does not agree - bottom')
client = []
output = []
print('--- END OF ROW ---')

If you want to write the output of your script in a file I see two options.
The first one is to handle the writing in the python script :
#!/usr/bin/python
#I am here assuming that you use a Unix-like system (i.e. Not Windows )
file = open('textfile.txt','w')
... some code ...
file.write(myData +'\n')
#Don't forget to close the file at the end of the script
file.close()
N.B: the 'w' option creates the file if it not exists, but it aslo delete previous version of the file. If you want to add lines at the end of an existing file, you should use 'a' instead.
The '\n' is just here to create a new line.
The other option is the following : Simple use print statament in your script
#My Script
... some code ...
print MyData
and then, run your script in a shell not in IDLE with the following command :
python SagicorPremiumCalculator2.py > textfile.txt
If you are running Windows, you should definitely use the first option (because I am not sure the bash-style commands works in cmd ).
I hope this helps !

Related

Is there a shorter way to increment bd_address in python?

I wrote a python's function to increment BT device BD_ADDR by any value but my function can only work up to xx:xx:xx:xx:FE:FF. For example, original BD_ADDR = AA:BB:CC:DD:EE:FF --> incremented by 1 BD_ADDR = AA:BB:CC:DD:EF:00. Also is there a shorter way to do this without all if statements? any suggestions will be appreciated.
Below is the script:
def ba_incr(mac,incr):
old_bytes = mac[12:].split(":")
if (old_bytes[0] != "00"):
if (old_bytes[0] != "01" and old_bytes[0] != "0F"):
old_hex = str(old_bytes[0] + old_bytes[1])
incr_hex = hex(int(str(int(old_hex, base=16) + incr)))[2:]
new_bytes = str(incr_hex[:2]) + ":" + str(incr_hex[2:])
elif (old_bytes[0] == "0F" and old_bytes[1] == "FF") :
old_hex = str(old_bytes[0] + old_bytes[1])
incr_hex = hex(int(str(int(old_hex, base=16) + incr)))[2:]
new_bytes = str(incr_hex[:2]) + ":" + str(incr_hex[2:])
else:
old_hex = str(old_bytes[0] + old_bytes[1])
incr_hex = hex(int(str(int(old_hex, base=16) + incr)))[2:]
#print ("incremented hex",incr_hex)
new_bytes = "0" + str(incr_hex[:1]) + ":" + str(incr_hex[1:])
elif (old_bytes[0] == "00" and old_bytes[1] == "FF"):
old_hex = old_bytes[1]
#print ("old hex:",old_hex)
incr_hex = hex(int(str(int(old_hex, base=16) + incr)))[2:]
#print ("incremented hex:",incr_hex)
new_bytes = "01" + ":" + str(incr_hex[1:])
elif (old_bytes[0] == "00" and old_bytes[1][:1] == "0") and old_bytes[1][1:] != "F":
old_hex = old_bytes[1]
#print ("old hex:",old_hex)
incr_hex = hex(int(str(int(old_hex, base=16) + incr)))[2:]
#print ("incremented hex:",incr_hex)
new_bytes = old_bytes[0] + ":0" + str(incr_hex)
elif (old_bytes[0] == "00" and old_bytes[1] != "FF"):
old_hex = old_bytes[1]
#print ("old hex:",old_hex)
incr_hex = hex(int(str(int(old_hex, base=16) + incr)))[2:]
#print ("incremented hex:",incr_hex)
new_bytes = old_bytes[0] + ":" + str(incr_hex)[:2]
print ("mac after:", mac[:12] + new_bytes.upper())
You can probably try something like this:
Remove the ':' from the mac address
Convert the mac address to integer
Increment the integer value
Convert the integer to hex string
Insert back the ':' at the appropriate positions
Sample code that worked for me (for simplicity I am incrementing by 1). You may need to modify it to handle corner cases.
s = 'AA:BB:CC:DD:EE:FF'
s = s.replace(':', '')
val = int(s, 16)
val = val + 1
incr_s = hex(val)
incr_s = incr_s[2:].upper()
incr_s = ':'.join(incr_s[i:i+2] for i in range(0, len(incr_s), 2))
print(s)
print(incr_s)
Output:
AABBCCDDEEFF
AA:BB:CC:DD:EF:00

decrease time execution of a python code

how can i decrease the time execution of this code:
tab_voyelle is a table of 2669433 different words
for elem in tab_voyelle:
words_match = []
elem = elem.strip()
Tab_elem_out = CheckImpli(elem,tab_voyelle)
if len(Tab_elem_out) != 0:
MonFichINImpli = open('/home/user/Bureau/MesTravaux/MatchingCorpus/in_imply_result.txt','w')
for i in range(len(Tab_elem_out)):
MonFichINImpli.write(elem + ' ' + Tab_elem_out[i] + '\n')
MonFichINImpli.close()
subprocess.call(['java', '-jar', '/home/user/Bureau/MesTravaux/MatchingCorpus/dist/ImpliMorphVer4.jar','-i', 'in_imply_result.txt','-o','Result_Impli.txt'])
words_match = MatchingArabicWords('Result_Impli.txt','in_imply_result.txt')
if len(words_match) != 0 :
MonFichierResultat.write('<mot id="'+elem+'">'+'\n')
for valeur in words_match:
valeur = valeur.strip()
MonFichierResultat.write('<val>'+valeur+'</val>'+'\n')
t = tab_voyelle[tab_voyelle.index(valeur)]
del tab_voyelle[tab_voyelle.index(valeur)]
MonFichierResultat.write('</mot>' + '\n')
if len(words_match) == 0:
MonFichierResultat.write('<mot id="'+elem+'">'+'\n'+'<val></val>\n'+'</mot>' + '\n')
MonFichierResultat.write('</matching>' + '\n')
MonFichierResultat.close()

python error could not convert string to float

We are getting this below error while migrating the data from slack channel to a file, when we execute the script for fetching the data for one day, it executing perfectly.
But when we execute the script for 2 months data, it gives 10 days data in separate file but getting throwing an error on particular date. It might be possible that the source data on slack is bit different from expected
Traceback (most recent call last):
File "C:\Users\Slack SCript\script.py", line 218, in <module>
main()
File "C:\Users\Slack SCript\script.py", line 201, in main
parse(message['text'])
File "C:\Users\Slack SCript\script.py", line 114, in parse
size = float(elements[1])
ValueError: could not convert string to float:
As per the source data we found that some value is 0 maybe the error we got because of this value. is there any way to skip or continue future.
from slackclient import SlackClient
import time
import os
import sys
import datetime
from dateutil.relativedelta import relativedelta
servers = ("fd2a", "ff1a", "hh3b", "kw1a", "kw1b", "lo8a", "os5a", "os5b", "sg2a", "sg2b", 'sy1a', 'va1a', 'va1b')
types = ("", "nfs", "cluster")
currser = "d"
currtype = ""
used = {}
total = {}
available = {}
ts = 0
dir_name = "data"
def savedata(dir_path, filename, data):
f = open(dir_path + filename, "w") # opens file with name of "test.txt"
print(dir_path + filename)
f.write(data)
f.close()
def reset_data():
print("datareset")
for i in range(0, len(servers)):
for j in range(0, len(types)):
used[servers[i] + types[j]] = 0
total[servers[i] + types[j]] = 0
available[servers[i] + types[j]] = 0
def write_data(ts):
datastr = ''
global used
global total
ttotaltotalsum = 0
for j in range(0, len(types)):
datastr += types[j] + '\n'
datastr += "Name\t" + "Region\t" + "total(TB)\t" + "used(TB)\t" + "available(TB)\t" + "Used(%)\n"
for i in range(0, len(servers)):
tused = used[servers[i] + types[j]]
ttotal = total[servers[i] + types[j]]
ttotaltotalsum += ttotal
if (ttotal != 0):
datastr += (
servers[i][0:len(servers[i]) - 1] + "\t\t" +
servers[i][len(servers[i]) - 1] + "\t\t" +
"{:.1f}".format(ttotal / 1024) + " \t\t" +
"{:.1f}".format(tused / 1024) + " \t\t" +
"{:.1f}".format((ttotal - tused) / 1024) +"\t\t"+
"{:.1f}".format(tused / ttotal * 100) + " \t\t" +
" \n")
print("..")
if (ttotaltotalsum > 0):
hour= datetime.datetime.fromtimestamp(int(ts)).hour
day= datetime.datetime.fromtimestamp(int(ts)).day
month= datetime.datetime.fromtimestamp(int(ts)).month
year=datetime.datetime.fromtimestamp(int(ts)).year
if hour < 12:
savedata("data/", "Storage-Update-M-" +
str(day) + "-" +
str(month) + "-" +
str(year) + ".txt", datastr)
else:
savedata("data/", "Storage-Update-E-" +
str(day) + "-" +
str(month) + "-" +
str(year) + ".txt", datastr)
def parse(text):
global currser
global currtype
global used
global total
global available
global ts
content = text.split("\n")
for line in content:
line = line[:len(line)]
if line.__contains__("Netapp Cluster"):
for server in servers:
if line.__contains__(server):
currser = server
for type in types:
if line.__contains__(type):
currtype = type
# print(line)
if line.__contains__("Total available capacity"):
# print(line)
# print ("contains","Total available capacity------")
elements = line.split(":")
# print (elements)
size = float(elements[1])
# print(size)
total[currser + currtype] += size
# print(size,"TOTAL capacity",total)
elif line.__contains__("size provisioned"):
# print(line)
# print("contains", "Total LUN size provisioned------- ")
elements = line.split(":")
# print(elements)
size = float(elements[1])
# print(size)
used[currser + currtype] += size
# print(size, "Used", used)
# print( currser)
# print( currtype)
# print( used)
# print(total)
# print(available)
return (used, total)
def make_dir(dir_name):
if not os.path.exists(dir_name):
os.makedirs(dir_name)
def main():
slack_token = ""
channel_name = ''
time_on_last_message = time.time()
channel_id = ""
ts = 0.000
threshmins = 20
channels_call = SlackClient(slack_token).api_call("channels.list")
print(channels_call)
print(channels_call.keys())
for channel in channels_call["channels"]:
if channel["name"] == channel_name:
channel_id = channel["id"]
print(channel)
make_dir(dir_name)
print(channel_id)
reset_data()
time_since_last_update = time.time() - time_on_last_message
print("Waiting for new data....", time.time() - time_on_last_message)
if time_since_last_update > threshmins * 60:
write_data(ts)
reset_data()
sc = SlackClient(slack_token)
date_after_month = datetime.datetime.now() + relativedelta(months=-6)
date_after_month=date_after_month.timestamp()
while True:
breakflag=0
data = sc.api_call(
"channels.history",
channel=channel_id,
oldest=date_after_month,
count=1000,
)
if (data['ok'] == True):
messages = data['messages']
for message in reversed(messages):
# print(message['ts'])
if float(message['ts']) > ts:
print("difference=", float(message['ts']) - ts)
if float(message['ts']) - ts > (threshmins * 60):
print("greater diffrrece>reset................")
write_data(ts)
print(ts)
reset_data()
time_on_last_message = time.time()
ts = float(message['ts'])
parse(message['text'])
if (data["has_more"] == True):
print("has more")
date_after_month=message['ts']
else:
breakflag=1
else:
print("No data returned or error")
time.sleep(1) # in Seconds
if(breakflag==1):
break
main()
Based on the error message, elements[1] is empty. And Python cannot convert an empty string to float:
>>> float("")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: could not convert string to float:
The elements[1] element is a string that can't be parsed to a float. The easiest way would be to attach a debugger and investigate what is being parsed. Then change your code to parse it better.
The second easiest way would be to binary search for the record that makes it fail and fix your code to parse it better.
The totally absolutely preferred way would be to, when you found what the case was that your code didn't support, you would write a test that proves that that case was added:
def test_parse_xyz():
assert [("blablabla", None)] == parse(["blablabla: -certainly_not_a_float"])
These tests can automatically be detected by e.g. pytest:
$ pytest parser.py

pythonw.exe has stopped working

I'm implementing Kosaraju’s two-pass algorithm that can calculate strongly connected components in a directed graph.
I can get the correct result with small input data, but when the input data is larger
(70M txt, warning!! this text file has the size of nearly 70M
,using a downloading software with this url to download this large file. If you don't have a downloading software, you can copy this url in your brower http://pan.baidu.com/s/1i5Hmf5N
and download it),
it shows "pythonw.exe has stopped working" after about 1 hour. Python should run to get the correct answer.
How can I fix it? Is there some memory problem?Please do me a favor.
Here is the large data result:
My code is here:
import time
import datetime
import sys
start = time.time()
print datetime.datetime.now()
with open('test.txt') as f:
#SCC
#a = [[int(x) for x in ln.split()] for ln in f]
data_set_u = []
data_set_v = []
for ln in f:
#print ln
#print type(ln)
#print len(ln)
if len(ln) >1:
u,v = ln.split()
u = int(u)
v = int(v)
data_set_u.append(u)
data_set_v.append(v)
f.close()
print 'open file time: '+ str(time.time() - start) + 's'
print datetime.datetime.now()
sys.setrecursionlimit((max(data_set_u+data_set_v)+ len(data_set_u))*100)
def DFS_Loop():
num = max(data_set_u+data_set_v)
start_time_DFS_Loop = time.time()
global t
t = 0
global s
s = None
global visited
visited = [False]* num
global leader
leader = [None] * num
global f
f = [None] * num
for i in range(num,0,-1):
#print i
#print (i in visited)
#if (i in visited)==False:
if visited[i-1] == False:
s = i
#print s
DFS(i)
print 'end with func DFS_Loop() time: '+ str(time.time() - start_time_DFS_Loop)+ 's'
print 'end with func DFS_Loop() whole time: '+ str(time.time() - start)+ 's'
#print data_set_u
#print data_set_v
def DFS(node):
start_time_DFS = time.time()
global t
visited[node-1] = True
#print visited
#print visited
leader[node-1] = s
#print leader
arc = []
arc = [data_set_v[i] for i,x in enumerate(data_set_u) if x==node]
#print arc
for i in arc:
#print arc
#print i
if visited[i-1]==0:
#print i
DFS(i)
t+=1
#print t
f[node-1] = t
#print f
print 'end with func DFS time: '+ str(time.time() - start_time_DFS)+ 's'
print 'end with func DFS whole time: '+ str(time.time() - start)+ 's'
DFS_Loop()
print 'DFS_Loop time: '+ str(time.time() - start)+ 's'
##reverse tail and head data
##
##
rev_u,rev_v = data_set_v,data_set_u
new_u = [None] * (len(rev_u))
new_v = [None] * (len(rev_v))
#print rev_v
#print rev_u
for i,val in enumerate(f):
#rev_u[rev_u.index(i+1)] = val
#print i+1,val
#rev_v[rev_v.index(i+1,0,len(rev_v))] = val
#print rev_v
#print i,val
for i_v,val_v in enumerate(rev_v):
if val_v == i+1:
#print val_v
new_v[i_v] = val
for i_u,val_u in enumerate(rev_u):
if val_u == i+1:
#print i_u,val_u
new_u[i_u] = val
#print new_u
#print new_v
data_set_u = new_u
data_set_v = new_v
#print data_set_u
#print data_set_v
print 'reverse data time: '+ str(time.time() - start)+ 's'
DFS_Loop()
print 'DFS_Loop time: '+ str(time.time() - start)+ 's'
#print leader
##calculate repeated times appearancing in leader list
##
##
count_list = [0]*len(leader)
indices = [0]*len(leader)
#for i_lea,val_lea in enumerate(leader):
i_count_list = 0
while len(leader) > 0:
#print i_lea,val_lea
count_list[i_count_list] = leader.count(leader[0])
#print 'count_list: '+ str(count_list)
indices = [i for i, x in enumerate(leader) if x == leader[0]]
#print 'indices: '+ str(indices)
for i in xrange(len(indices)):
#print 'leader before del: '+ str(leader)
del leader[leader.index(leader[0])]
#print 'leader after del: '+ str(leader)
#print 'leader: '+ str(leader)
i_count_list = i_count_list+1
#print 'i_count_list: ' + str(i_count_list)
print 'calc time: '+ str(time.time() - start)+ 's'
sorted_count_list = sorted(count_list, key=int, reverse=True)
print sorted_count_list[0:5]
print datetime.datetime.now()
Here is the small test file:
1 4
2 8
3 6
4 7
5 2
6 9
7 1
8 5
8 6
9 7
9 3
Here is the correct partial result of small test file:
calc time: 0.121000051498s
[3, 3, 3, 0, 0]
2017-01-19 08:07:44.802000

Skyscanner API CSV file

I am new to python and I am trying to run this code,which I found on github ,but it does not work, is something wrong with the code?Or is it my fault? I am always getting the
"no data found"
message.
skyscanner.py :
#!/usr/bin/python
"""The script obtains prices and flight information for a given
input (departure, arrival airports and date), outputs this
data to the console and writes it to a csv file."""
__author__ = "Ingvaras Merkys"
import json
import urllib2
import re
import sys
import time
# Global vars:
AUTOSUGGEST_URL = "http://www.skyscanner.net/dataservices/geo/v1.0/autosuggest/uk/en/"
# e. g. http://www.skyscanner.net/dataservices/geo/v1.0/autosuggest/uk/en/edinb
SKYSCANNER_URL = "http://www.skyscanner.net/flights/"
# e. g. http://www.skyscanner.net/flights/vno/edi/130419
ROUTEDATA_URL = "http://www.skyscanner.net/dataservices/routedate/v2.0/"
# e. g. http://www.skyscanner.net/dataservices/routedate/v2.0/a00765d2-7a39-404b-86c0-e8d79cc5f7e3
SUGGESTIONS_URL = "http://www.skyscanner.net/db.ashx?ucy=UK&lid=en&ccy=GBP"
# e. g. http://www.skyscanner.net/db.ashx?ucy=UK&lid=en&ccy=GBP&fp=KAUN&tp=EDIN&dd=20130410
def main(argv):
input_from = argv[0].replace(" ", "%20").replace("\"", "")
input_to = argv[1].replace(" ", "%20").replace("\"", "")
date = argv[2].replace("/", "")
place_id_from, place_id_to, name_from, name_to = get_codes(input_from, input_to)
# testjuly = map (lambda x: len(x) == 1 and '13070'+x or '1307'+x, [ str(i+1) for i in range(31) ])
# for date in testjuly:
session_key = get_session_key(place_id_from, place_id_to, date)
for attempt in range(3):
# if script is run repeatedly sometimes an empty html is returned
try:
response = urllib2.urlopen(ROUTEDATA_URL + session_key)
html = response.read()
data = json.loads(html)
except ValueError:
f = open("error.log", "a")
f.write(ROUTEDATA_URL + session_key + "\n")
f.write("Returned:\n" + html + "\n")
time.sleep(1)
else:
break
else:
sys.exit(1)
query = data['Query']
if data['Stats']['OutboundLegStats']['TotalCount'] == 0:
print "No flights found from", name_from, "to", name_to
return 0
#show_suggestions(query['OriginPlace'], query['DestinationPlace'], date)
#sys.exit(2)
stations = data['Stations']
quotes = data['Quotes']
carriers = data['Carriers']
cheapest_price = data['Stats']['ItineraryStats']['Total']['CheapestPrice']
print "Results for flight from", name_from, "to", name_to
print "Outbound date:", re.split('T', query['OutboundDate'])[0]
print "Cheapest Journey:", cheapest_price, "RMB"
return cheapest_price
# f = open(place_id_from + '-' + place_id_to + '-' + date + '.csv','w')
# for leg in data['OutboundItineraryLegs']:
# leg_price = get_leg_price(leg['PricingOptions'], quotes)
# depart_time = leg['DepartureDateTime'].replace("T", " ")
# arrive_time = leg['ArrivalDateTime'].replace("T", " ")
# duration = leg['Duration']
# carrier_names = get_carrier_names(leg['MarketingCarrierIds'], carriers)[1]
# print "\n\tPrice:", leg_price, "GBP"
# print "\tDeparting:", depart_time
# print "\tArriving:", arrive_time
# print "\tDuration:", duration/60, "h", duration%60, "min"
# print "\tCarriers:", carrier_names
# print "\t# of stops: ", leg['StopsCount']
# stop_ids = leg.get('StopIds', [])
# stop_ids_string = ", ".join([ get_station_name(stop_id, stations) for stop_id in stop_ids ])
# print "\t\t", stop_ids_string
# row = str(leg_price) + "\t" + depart_time + "\t" + arrive_time + "\t" + str(duration) + "\t" + carrier_names + "\t" + stop_ids_string
# f.write(row + "\n")
# Functions
def get_codes(input_from, input_to):
"""Returns place id codes and names, e. g. ("EDI", "KUN", "Edinburgh", "Kaunas")"""
try:
i = 0
autosuggest_json_from = json.load(urllib2.urlopen(AUTOSUGGEST_URL + input_from))
if len(autosuggest_json_from[0]['PlaceId']) == 4:
# for cases where the first result is abstract (e. g. Glasgow (Any))
i = 1
place_id_from = autosuggest_json_from[i]['PlaceId']
name_from = autosuggest_json_from[i]['PlaceName']
j = 0
autosuggest_json_to = json.load(urllib2.urlopen(AUTOSUGGEST_URL + input_to))
if len(autosuggest_json_to[0]['PlaceId']) == 4:
j = 1
place_id_to = autosuggest_json_to[j]['PlaceId']
name_to = autosuggest_json_to[j]['PlaceName']
except IndexError:
print "No code found for:"
print input_from, "AND/OR", input_to
sys.exit(3)
return (place_id_from, place_id_to, name_from, name_to)
def get_session_key(place_id_from, place_id_to, date):
"""Returns a session key for a given query, on failure exits
NB. distant or past dates cause failures"""
response = urllib2.urlopen(SKYSCANNER_URL + place_id_from + "/" + place_id_to + "/" + date)
html = response.read()
regex = ur'"SessionKey":"(.+?)"'
# e. g. "SessionKey":"a00765d2-7a39-404b-86c0-e8d79cc5f7e3"
try:
session_key = re.findall(regex, html)[0]
except IndexError:
print "No data found for this date"
sys.exit(4)
return session_key
def show_suggestions(from_id, to_id, date):
"""Prints alternative departure airports"""
suggest_places_string = ""
suggestions_json = json.load(urllib2.urlopen(SUGGESTIONS_URL + "&fp=" + from_id + "&tp=" + to_id + "&dd=20" + date))
try:
suggest_places = suggestions_json['rs']
for place in suggest_places:
if place['fpid'] != from_id:
suggest_places_string += place['fan'] + ", "
if suggest_places_string[:-2] != "":
print "Try airports: ", suggest_places_string[:-2]
except (KeyError, IndexError):
print "Suggestions unavailable"
def get_station_name(station_id, stations):
"""Returns the name of the (intermediate) station,
e. g. "London Heathrow" """
for station in stations:
if station['Id'] == station_id:
return station['Name']
return ""
def get_leg_price(pricing, quotes):
"""Returns lowest leg price"""
prices = []
for price in pricing:
prices.append(get_quote_price(price['QuoteIds'], quotes))
return min(prices)
def get_quote_price(quote_ids, quotes):
"""Finds quotes by quote id and returns their price sum"""
price = 0;
for quote_id in quote_ids:
for quote in quotes:
if quote['Id'] == quote_id:
price += quote['Price']
return price
def get_carrier_names(carrier_ids, carriers):
"""Returns a tuple (list, string) with carrier names
e.g. (["airBaltic", "KLM"], "airBaltic, KLM")"""
carrier_names = []
carrier_names_string = ""
for carrier_id in carrier_ids:
carrierName = get_carrier_name(carrier_id, carriers)
carrier_names.append(carrierName)
carrier_names_string += carrierName + ", "
return (carrier_names, carrier_names_string[:-2])
def get_carrier_name(carrier_id, carriers):
"""Returns carrier name by id"""
for carrier in carriers:
if carrier['Id'] == carrier_id:
return carrier['Name']
return ""
if __name__ == "__main__":
if len(sys.argv) == 4:
main(sys.argv[1:])
else:
print "Enter arguments in this way:\n"
print "python skyscanner.py {departure airport} {arrival airport} {departure date (yy/mm/dd)}\n\n"
print "e. g. python skyscanner.py \"glasgow prestwick\" kaunas 13/07/21\n"
sys.exit()
These endpoints are not supported as external APIs, they are used by the site itself. They can/do change without notice and some require a level of "state" to operate.
However, we do have an API that would allow you access to the same auto-suggest / flight data that the site is driven from. More details can be found at http://business.skyscanner.net

Categories