How can I stop getting 2 different print results under same condition - python

newbie here. I want to get only one result when condition met but couldn't figure out how to do that.
current_threshold = (max_bid_val - min_ask_val) * 100 / min_ask_val
if (current_threshold > threshold) :
alert_message = "Buy " + coin_list[i] + " on " + min_ask_place + " website for " + str(
min_ask_val) + " price and Sell on " + max_bid_place + " for " + str(max_bid_val) + " price."
alert_message_paribu = "Buy " + coin_list[i] + " on " + min_ask_place + " website for " + str((
min_ask_val * paribu_dic[symbol_usdt_tl][
'highestBid'])) + " price and Sell on " + max_bid_place + " for " + str(max_bid_val) + " price."
if 'paribu' in min_ask_place :
print(alert_message_paribu)
start_alert(alert_message_paribu)
telegram_send.send(messages=[alert_message_paribu])
time.sleep(10)
else : #if min_ask_place is not paribu I need to get results as alert_message
alert_message = "Buy " + coin_list[i] + " on " + min_ask_place + " website for " + str(
min_ask_val) + " price and Sell on " + max_bid_place + " for " + str(max_bid_val) + " price."
print(alert_message)
start_alert(alert_message)
telegram_send.send(messages=[alert_message])
time.sleep(10)
any idea or suggestions? sorry if it's too ignorant. thanks

Looks like you have two print statements where there is a condition that allows both to run. Does it print twice if 'paribu' is not in min_ask_place? maybe move the second print under the else.

Related

What's a more efficient way of appending more items to a string depending on a list's length?

This is what I have right now.
What I would like is for the string to concatenate more depending on the length of the "top_line". So if the top line has 1 item, the "full_top_line" and "full_second_line" and "full_dashes_line" also only add 1 item
if len(top_line) == 1:
full_top_line = top_line[0]
full_second_line = second_line[0]
full_dashes_line = dash[0]
if len(top_line) == 2:
full_top_line = top_line[0] + " " + top_line[1]
full_second_line = second_line[0] + " " + second_line[1]
full_dashes_line = dash[0] + " " + dash[1]
if len(top_line) == 3:
full_top_line = top_line[0] + " " + top_line[1] + " " + top_line[2]
full_second_line = second_line[0] + " " + second_line[1] + " " + second_line[2]
full_dashes_line = dash[0] + " " + dash[1] + " " + dash[2]
if len(top_line) == 4:
full_top_line = top_line[0] + " " + top_line[1] + " " + top_line[2] + " " + top_line[3]
full_second_line = second_line[0] + " " + second_line[1] + " " + second_line[2] + " " + second_line[3]
full_dashes_line = dash[0] + " " + dash[1] + " " + dash[2] + " " + dash[3]
if len(top_line) == 5:
full_top_line = top_line[0] + " " + top_line[1] + " " + top_line[2] + " " + top_line[3] + " " + top_line[4]
full_second_line = second_line[0] + " " + second_line[1] + " " + second_line[2] + " " + second_line[3] + " " + second_line[4]
full_dashes_line = dash[0] + " " + dash[1] + " " + dash[2] + " " + dash[3] + " " + dash[4]
You can use list comprehension with join() method instead
full_top_line = " ".join([top_line[i] for i in range(len(top_line))])
full_second_line = " ".join([second_line[i] for i in range(len(top_line))])
full_dashes_line = " ".join([dash[i] for i in range(len(top_line))])

How to add attachments from Flask to win32com?

Hi I am having trouble attaching flask uploads to Outlook,
I need to attach uploads from flask to outlook.
Thanks
''' f = rq.files['filesattach']
msg.HTMLBody = str("<br> <br>Hi, the follow data are attached to this email <br>").title() + "\n \n" + "<br> Date Request Sent to Permit Coordinator: " + dateReq + "\n" + "<br>WO #: "+ wo+ " \n" + "<br>Date Needed: " + dateNeed + "\n" +"<br>SR: "+ sr + "\n" + "<br>TCF: " +tcf + "\n" + "<br>Munplicity: "+ mun + "\n" + "<br>Political Sub: " + polSub + "\n" + '<br>Address: '+ address + "\n" + '<br>Cross Street: ' + cross + "\n" + '<br>Description: '+ desc + "\n" + "<br>Permit Type: " + permitType
msg.Subject = "WO " + wo +" "+ permitType+" "+"Permit Form"
msg.Display()
shell.AppActivate("Outlook")
shell.SendKeys("%s", 0)
saved = f.save(secure_filename(f.filename))
return "Message sent"
else:
return render_template(permitForm)'''
uploaded_files = rq.files.getlist("filesattach")
for i in uploaded_files:
file = os.path.realpath(str(i.filename))
msg.attachments.Add(file)

I can't see what is triggering the invalid Syntax error

I am currently trying to replicate a packet sniffer in python that can parse udp, tcp, and ICPM packets.
As it is now no other compiler errors show except an invalid syntax error.
#packet sniffer for linux in python
import socket, sys
from struct import*
#A function that converts a string of 6 characters of ethernet address into dash seperated hex string
def ethernet_address (string):
new_String = "%.2x:%.2x:%.2x:%.2x:%.2x:%.2x" % (ord(string(0)), ord(string(1)), ord(string(2)), ord(string(3)), ord(string(4)), ord(string(5)))
return new_String
#Section that creates the socket
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.ntohs(0x0003))
except socket.error as msg:
print ("Socket could not be created, Error : ")
print (msg)
sys.exit()
#recieve a packet
while True:
packet = sock.recvfrom(60000)
#packet string from tuple
packet = packet[0]
#parse ethernet header
ether_length = 14
ether_Header = packet[:ether_length]
ether = unpack('!6s6sh', ether_Header)
ether_protocol = socket.ntohs(ether[2])
print ("Destination MAC: " + ethernet_address(packet[0:6]) + "Source MAC: " + ethernet_address(packet[6:12]) + " Protocol: " + str(ether_protocol))
#This section handles parsing IP packets
if ether_protocol == 8:
#Parse the IP header
#take the first 20 character from the header
ip_header = packet[ether_length:20 + ether_length]
#now unpack
iph = unpack('!BBHHHBBH4s4s', ip_header)
version_ihl = iph[0]
version = version_ihl >> 4
ihl = version_ihl & 0xf
iph_length = ihl * 4
ttl = iph[5]
protocol = iph[6]
source_address = socket.inet_ntoa( iph[8] )
destination_address = socket.inet_ntoa( iph[9] )
print("Version: " + str(version) + " IP header length: " + str(ihl) + " TTL: " + str(ttl) + " Protocol: " + str(protocol + " Source Address: " + str(source_address) + " Destination Address: " + str(destination_address) )
#This section handles parsing TCP packets
if protocol == 6 : #This is the line with the error******************************************
num = iph_length + ether_length
tcp_header = packet[ num:num+20]
#unpack
tcph = unpack('!HHLLBBHHH', tcp_header)
source_port = tcph[0]
destination_port = tcph[1]
sequence = tcph[2]
acknowledgment = tcph[3]
doff_reserve = tcph[4]
tcph_length = doff_reserve >> 4
print("Source Port: " + str(source_port) + " Destination Port: " + destination_port + " Sequence: " + sequence + " Acknowledgment: " + str(acknowledgment) + " TCP header length: " + str(tcph_length))
h_size = ether_length + iph_length + tcph_length * 4
data_size = len(packet) - h_size
#get data
data = packet[h_size:]
print ("Data: "+ data)
#This section Handles parsing ICMP packets
elif protocol == 1:
u = iph_length + ether_length
icmph_length = 4
icmp_header = packet[u:u+20]
#unpack
icmph = unpack('!BBH', icmp_header)
icmp_type = icmph[0]
code = icmph[1]
checksum = icmph[2]
print("Type: " + str(icmp_type) + " Code: " + str(code) + " Checksum: " + str(checksum))
h_size = ether_length + iph_length + icmph_length
data_size = len(packet) - h_size
#retrive data
data = packet[h_size]
print("Data: " + data)
#This section handles parsing UDP
elif protocol == 17:
u = iph_length +ether_length
udph_length = 8
udp_header = packet[u:u+8]
#now unpack them
udph = unpack('!HHHH', udp_header)
src_port = udph[0]
dest_port = udph[1]
length = udph[2]
checksum = udph[3]
print("Source Port: " + str(src_port) + " Destination Port: " + str(dest_port) + " Length: " + str(length) + " Checksum: " + str(checksum) )
h_size = ether_length + iph_length + udph_length
data_size = len(packet) - h_size
#get data
data = packet[h_size]
print("Data: " + data)
else:
print("Protocol is something other than UDP, ICMP, or TCP")
print
The error is caused by the line:
if protocol == 6 :
Visual Studio says that this is a syntax error, but I'm of how because it is written just like every other if statement and they don't have a syntax error warning. What is the error if there is one?
I believe you are missing a bracket. print("Version: " + str(version) + " IP header length: " + str(ihl) + " TTL: " + str(ttl) + " Protocol: " + str(protocol + " Source Address: " + str(source_address) + " Destination Address: " + str(destination_address) )) should work.
Note: I added a bracket at the end but that might not be where it should be added for your code to function as intended despite removing the error. It seems print("Version: " + str(version) + " IP header length: " + str(ihl) + " TTL: " + str(ttl) + " Protocol: " + str(protocol) + " Source Address: " + str(source_address) + " Destination Address: " + str(destination_address) ) is likely what you want.
The error is found in the line above:
print("Version: " + str(version) + " IP header length: " + str(ihl) + " TTL: " + str(ttl) + " Protocol: " + str(protocol + " Source Address: " + str(source_address) + " Destination Address: " + str(destination_address) )
Specifically, the error comes from ... str(protocol + ..., which should be ... str(protocol) + ....
You have an unmatched parenthesis on the previous line:
print("Version: " +
str(version) +
" IP header length: " +
str(ihl) +
" TTL: " +
str(ttl) +
" Protocol: " +
str(protocol +
" Source Address: " +
str(source_address) +
" Destination Address: " +
str(destination_address)
)
You probably want something like this:
print("Version: " +
str(version) +
" IP header length: " +
str(ihl) +
" TTL: " +
str(ttl) +
" Protocol: " +
str(protocol) +
" Source Address: " +
str(source_address) +
" Destination Address: " +
str(destination_address)
)
Also, consider using " ".join(iterable) to join strS with spaces. Concatenation is inefficient (not an issue here) and difficult to read (definitely an issue here).

using a variable from a json.load in another function

I am using an API for receiving TTN data from a device. i have created a function "def on_message(mqttc, obj, msg):", using a json.loads(msg.payload.decode('utf-8')) to receive mqtt data.
I want to pick the variable "node_data" and use in def devdata(). but it seems that i do not get anything but None.
import paho.mqtt.client as mqtt
import json
import pybase64
import binascii
APPEUI = "0018B24441524632"
APPID = "adeunis_fieldtester"
PSW = "ttn-account-v2.vuQczD1bmPoghhaKjlIHR-iHovHIbYMpfWSKosPAGaU"
# Call back functions
# gives connection message
def on_connect(mqttc, mosq, obj, rc):
print("Connected with result code:" + str(rc))
# subscribe for all devices of user
mqttc.subscribe('+/devices/+/up')
# gives message from device
def on_message(mqttc, obj, msg):
try:
x = json.loads(msg.payload.decode('utf-8'))
# metadata
app = x["app_id"]
device = x["dev_id"]
deveui = x["hardware_serial"]
port = x["port"]
confirmed = x["confirmed"]
counter = x["counter"]
payload_fields = x["payload_raw"]
datetime = x["metadata"]["time"]
gateways = x["metadata"]["gateways"]
frequency = x["metadata"]["frequency"]
modulation = x["metadata"]["modulation"]
data_rate = x["metadata"]["data_rate"]
air_time = x["metadata"]["airtime"]
coding_rate = x["metadata"]["coding_rate"]
for gw in gateways:
gateway_id = gw["gtw_id"]
timestamp = gw["timestamp"]
time = gw["time"]
channel = gw["channel"]
gwrssi = gw["rssi"]
gwsnr = gw["snr"]
# decoding the payload_field
payload_r = (pybase64.b64decode(payload_fields + "="))
# decoding the Payload_r to Byte-Ascii string
payload_h = binascii.hexlify(payload_r)
# Byte to tekst
node_data = (payload_h.decode("utf-8)")) #this is the variable i would like to use in devdata()
# Printing data, + str(payload_fields) + ", "
print(str(app) + ", " + str(device) + ", " + str(deveui) + ", " + str(port) + ", " + str(counter) + ", "
+ str(node_data) + ", " + str(modulation) + ", " + str(datetime) + ", " + str(frequency) + ", "
+ str(confirmed) + ", " + str(data_rate) + ", " + str(air_time) + ", " + str(coding_rate) + ", "
+ str(gateway_id) + ", " + str(timestamp) + ", " + str(time) + "," + str(channel) + ", "
+ str(gwrssi) + ", " + str(gwsnr))
return node_data #return data for use in devdata()
except Exception as e:
print(e)
pass
def devdata():
node_data = on_message() # trying to use this as the Variable
temperatur = int(node_data[2:4], 16)
print("temperatur =", temperatur)
`

print the result of a scapy function in tkinter

a=lb + "(IP(src='" + SrcIP + "', dst='" + DestIP + "')/TCP(sport=" + SrcPort + ", dport=" + DestPort + ",flags='"+P+""+S+""+A+""+U+""+F+""+R+"'), timeout=" + Timeout + ")"
p=eval(a)
p.show()
tkMessageBox.showinfo(title = "the configuration and results", message = "The configuration is:\nFlags:"+psh+"\n"+syn+"\n"+ack+"\n"+urg+"\n"+fin+"\n"+rst+"\nSource IP:"+SrcIP + "\nDestination IP: " + DestIP + "\nSource Port: " +SrcPort+ "\nDestination port: " + DestPort + "\nTimeout: " +Timeout+"\nSend/Received method: "+lb+"\t")
How can i put the result of p.show() in tkMessageBox.showinfo?
I don't think you can, as the .show() method only uses print statements.

Categories