Error when calling Executable from Tkinter - python

I have a Executable named learn after compiling my program vv.c in linux.I am using Tkinter (python-Tk) for making My GUI.But When running my executable code.It reached a error message "sh :1 : learn :not found " where -t -c -b are parametes passing to executable.
else:
if self.binaryFeature == 0:
cmd = "learn" + "-t " + self.type + " -c "\
+ self.C + " " + self.e2.get() + " " + self.e3.get()
else:
cmd = "learn" + "-t " + self.type + " -c "\
+ self.C + " -b 1 " + self.e2.get()\
+ " " + self.e3.get()
output_string = commands.getoutput(cmd)
self.text.insert(INSERT, output_string+"\n","CprogramOutput")
is it any error in commands for executing ?please help me ..thanks

You need to put a space before "-t":
cmd = "learn" + " -t " + self.type + " -c "\
+ self.C + " " + self.e2.get() + " " + self.e3.get()
currently the shell evaluates the command as learn-t rather than learn -t.

Related

Below piece of code is not deleting records but the records are deleted from the query when run manually

def complete_stage_purge_process(self, target_cnxn, stage_table, process_cd):
self.logger.debug(datetime.now())
self.logger.debug('complete_stage_purge_process')
delete_dt = datetime.today() - timedelta(days=30)
delete_dt = str(delete_dt)
run_pk_sql = "select run_pk from " + schemaName.PROCESS.value + "." + tableName.RUN_LOG.value + " where " + ProcessRunlog.ETL_MODIFIED_DTM.value + " <= '" + delete_dt + "' and " + \
ProcessRunlog.PROCESS_PK.value + " = (select " + ProcessRunlog.PROCESS_PK.value + " from " + schemaName.PROCESS.value + "." + \
tableName.PROCESS.value + " where " + \
Process.PROCESS_CODE.value + " = '" + process_cd + "') "
delete_sql = "delete from " + schemaName.STAGE.value + "." + stage_table + " where run_pk in (" + run_pk_sql + ")"
print(delete_sql)
print(target_cnxn)
try:
trgt_cursor = target_cnxn.cursor()
trgt_cursor.execute(delete_sql)
self.logger.debug("deletes processed successfully ")
except:
self.logger.exception('Error in processing deletes')
raise
But when added commit after trgt_cursor.execute(delete_sql) then below error is thrown. Could someone please help on how to handle this
AttributeError: 'psycopg2.extensions.cursor' object has no attribute 'commit'

Layer not found errors from scapy

I'm trying to sniff packets using scapy and keep getting the following error and not sure how to fix it.
Here is the code and the error:
from scapy.layers.inet import IP, TCP, UDP
from scapy.all import *
import socket
import datetime
def sniff_packets(pkt):
time = datetime.datetime.now()
# classifying packets into TCP
if pkt.haslayer(TCP):
# classyfying packets into TCP Incoming packets
if socket.gethostbyname(socket.gethostname()) == pkt[IP].dst:
print(str("[") + str(time) + str("]") + " " + "TCP-IN:{}".format(
len(pkt[TCP])) + " Bytes" + " " + "SRC-MAC:" + str(pkt.src) + " " + `enter code here`"DST-MAC:" + str(
pkt.dst) + " " + "SRC-PORT:" + str(pkt.sport) + " " + "DST-PORT:" + str(
pkt.dport) + " " + "SRC-IP:" + str(pkt[IP].src) + " " + "DST-IP:" + str(
pkt[IP].dst))
if socket.gethostbyname(socket.gethostname()) == pkt[IP].src:
print(str("[") + str(time) + str("]") + " " + "TCP-OUT:{}".format(
len(pkt[TCP])) + " Bytes" + " " + "SRC-MAC:" + str(pkt.src) + " " + `enter code here`"DST-MAC:" + str(
pkt.dst) + " " + "SRC-PORT:" + str(pkt.sport) + " " + "DST-PORT:" + str(
pkt.dport) + " " + "SRC-IP:" + str(pkt[IP].src) + " " + "DST-IP:" + str(
pkt[IP].dst))
# classifying packets into UDP
if pkt.haslayer(UDP):
if socket.gethostbyname(socket.gethostname()) == pkt[IP].src:
# classyfying packets into UDP Outgoing packets
print(str("[") + str(time) + str("]") + " " + "UDP-OUT:{}".format(
len(pkt[UDP])) + " Bytes " + " " + "SRC-MAC:" + str(pkt.src) + " " + `enter code here`"DST-
MAC:" + str(
pkt.dst) + " " + "SRC-PORT:" + str(pkt.sport) + " " + "DST-PORT:" + str(
pkt.dport) + " " + "SRC-IP:" + str(pkt[IP].src) + " " + "DST-IP:" + str(
pkt[IP].dst))
if socket.gethostbyname(socket.gethostname()) == pkt[IP].dst:
# classyfying packets into UDP Incoming packets
print(str("[") + str(time) + str("]") + " " + "UDP-IN:{}".format(
len(pkt[UDP])) + " Bytes " + " " + "SRC-MAC:" + str(pkt.src) + " " + `enter code here`"DST-MAC:" + str(
pkt.dst) + " " + "SRC-PORT:" + str(pkt.sport) + " " + "DST-PORT:" + str(
pkt.dport) + " " + "SRC-IP:" + str(pkt[IP].src) + " " + "DST-IP:" + str(
pkt[IP].dst))
#wrpcap("test.pcap", )
if __name__ == '__main__':
sniff(prn=sniff_packets)
Traceback (most recent call last):
File "C:\Users\tathi\CYBR-260-FINAL\final1.py", line 48, in <module>
sniff(prn=sniff_packets)
File "C:\Users\tathi\venv\lib\site-packages\scapy\sendrecv.py", line 1263, in sniff
sniffer._run(*args, **kwargs)
File "C:\Users\tathi\venv\lib\site-packages\scapy\sendrecv.py", line 1210, in _run
session.on_packet_received(p)
File "C:\Users\tathi\venv\lib\site-packages\scapy\sessions.py", line 108, in
on_packet_received
result = self.prn(pkt)
File "C:\Users\tathi\CYBR-260-FINAL\final1.py", line 28, in sniff_packets
if socket.gethostbyname(socket.gethostname()) == pkt[IP].src:
File "C:\Users\tathi\venv\lib\site-packages\scapy\packet.py", line 1344, in __getitem__
raise IndexError("Layer [%s] not found" % name)
IndexError: Layer [IP] not found
It looks like the pkt does not have the key IP in it. You can check the existence of the key by checking if IP in pkt and then proceed with your other code.
def sniff_packets(pkt):
if not IP in pkt:
return
... # Code that checks for IP value in pkt
Or, you can check any domain-specific function like pkt.haslayer that does the equivalent.
def sniff_packets(pkt):
if not pkt.haslayer(IP):
return
... # Code that checks for IP value in pkt

unexpected EOF while looking for matching `'': What does this mean?

these are the error messages I am receiving from the terminal when I run add_user.py
sh: -c: line 0: unexpected EOF while looking for matching `''
sh: -c: line 1: syntax error: unexpected end of file
After some reading online I am led to believe that these errors are thrown when I am missing a matching parenthesis or quotation mark?I have looked through the file several times but since it has been a few hours, I might just be looking straight over the error. If it is not a missing quotation mark or parenthesis, please explain what might be causing the issue so I can fix it. Thanks to all who help!
import csv
import os
filename = "/root/Downloads/linux_users.csv"
def create_username(aList):
if (len(aList) < 2):
print("INVALID RECORD")
else:
tokens = list(aList[2])
username = tokens[0].lower() + aList[1].lower()
return username
with open(filename) as f_handle:
csv_reader = csv.reader(f_handle)
next(csv_reader)
userList = []
groupList = []
recordCopy = []
rep = 0
tick = True
for record in csv_reader:
if (record[7] == ""):
record.remove(record[7])
for data in record:
if (data == ""):
print("ERROR: MISSING INFORMATION. USER ID: " + record[0] + " HAS NOT BEEN ADDED")
tick = False
if ((record[6] not in groupList) and (tick == True)):
groupList.append(record[6])
if (tick == True):
username = create_username(record)
if (username in userList):
username += str(rep)
rep += 1
userList.append(username)
recordCopy.append(record)
else:
tick = True
for group in groupList:
os.system("groupadd " + group)
print("GROUP: " + group + " HAS SUCCESSFULLY BEEN CREATED")
i = 0
for record in recordCopy:
if (record[5] == "ceo"):
os.system("adduser " + userList[i] + " -g " + record[6] +
" -d /home/" + record[5] + " -s /bin/csh -u " + record[0] + " -p password")
os.system("passwd -e " + userList[i])
else:
os.system("adduser " + userList[i] + " -g " + record[6] +
" -d /home/" + record[5] + " -s /bin/bash -u " + record[0] + " -p password")
os.system("passwd -e " + userList[i])
i += 1
print("USER: " + record[0] + " HAS SUCCESSFULLY BEEN ADDED")

Need to use a variable in os.system with espeak and aplay commands in python

I want my raspberry pi to speak this print command
print label + " is " + spos + " and the distance is " + str(distance) + "cm"
which has three variables in it.
And this is the command i use in shell that i need to use in python
$espeak -s110 "label + " is " + spos + " and the distance is " + str(distance) + "cm"" --stdout | aplay -D sysdefault:CARD=2
I've tried it with os.system because i'm not familiar with subprocess commands.
os.system('espeak -s110 "'label' + is + 'spos' + and the distance is + 'str(distance)' + cm" --stdout | aplay -D sysdefault:CARD=2')
I'm getting an invalid sytax error. I've tried every version of it and couldn't make it work.
This should give you what you're looking for:
cmd = 'espeak -s110 "{0} is {1} and the distance is {2} cm" --stdout | aplay -D sysdefault:CARD=2'.format(label, spos, str(distance))
os.system(cmd)

Calling one module into another module

I have two python modules called main.py and black.py :
Main.py content as follows :
import os,sys,string,time
import subprocess,commands,re
import random
import black
class bcolors:
BOLD = '\033[1m'
UNBOLD = '033[0m'
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
def disable(self):
self.BOLD = ''
self.UNBOLD = ''
self.HEADER = ''
self.OKBLUE = ''
self.OKGREEN = ''
self.WARNING = ''
self.FAIL = ''
self.ENDC = ''
def print_menu():
#subprocess.call("tput clear")
print " "
#print bcolors.OKBLUE + (35 * '-') + bcolors.OKBLUE
print bcolors.OKBLUE + '\t\t\t\t' + (52 * '*') + bcolors.OKBLUE
print ("\t\t\t\t\t\tM A I N - M E N U")
print '\t\t\t\t' + (52 * '*')
print ("\t\t\t\t 0. Enter POD Name(s).")
print ("\t\t\t\t 1. QUIT")
print '\t\t\t\t' + (52 * '*') + bcolors.ENDC
is_valid=0
while not is_valid:
try :
choice = int ( raw_input('Enter your choice [0-24] : ') )
is_valid = 1
except ValueError, e :
print ("'%s' is not a valid integer." % e.args[0].split(": ")[1])
return choice
########## M A I N #####################
rUser=commands.getoutput("id -un").strip()
if rUser != "oracle":
print bcolors.FAIL + " Login as mc_admin to run the script. Exiting .." + bcolors.ENDC
exit ()
else:
os.system("tput clear")
choice = print_menu()
###################
global podList #
podList = None #
###################
while choice >= 0 and choice < 1:
if choice == 0:
pPODName()
black.blackout()
and black.py content as follows:
def blackout():
def pPODName():
global podList
podList = str(raw_input('Enter pipe separated list of PODS : ')).upper().strip()
if podList:
try:
cmd = "/fsnadmin/f516478/romeshar/myfolder/PodDetails.sh -p " + "\"" + podList + "\""
prodP = commands.getoutput(cmd).strip()
if prodP:
print bcolors.FAIL + "Production Pods [Status: Customer Active|Dev Post Provisioning|Cloud Ops Provisioning]: \n" + bcolors.OKBLUE + prodP + bcolors.ENDC
cmd = "/fsnadmin/f516478/romeshar/myfolder/PodDetails.sh -t " + "\"" + podList + "\""
stagP = commands.getoutput(cmd).strip()
if stagP:
print bcolors.FAIL + "Stage/Test Pods [Status: Customer Active|Dev Post Provisioning|Cloud Ops Provisioning]: \n" + bcolors.OKBLUE + stagP + bcolors.ENDC
cmd = "/fsnadmin/f516478/romeshar/myfolder/PodDetails.sh -d " + "\"" + podList + "\""
devP = commands.getoutput(cmd).strip()
if devP:
print bcolors.FAIL + "Dev/Upgrade Pods [Status: Customer Active|Dev Post Provisioning|Cloud Ops Provisioning]: \n" + bcolors.OKBLUE + devP + bcolors.ENDC
cmd = "/fsnadmin/f516478/romeshar/myfolder/PodDetails.sh -i " + "\"" + podList + "\""
intstgP = commands.getoutput(cmd).strip()
if intstgP:
print bcolors.FAIL + "Internal Staging Pods [Status: Customer Active|Dev Post Provisioning|Cloud Ops Provisioning]: \n" + bcolors.OKBLUE + intstgP + bcolors.ENDC
cmd = "/fsnadmin/f516478/romeshar/myfolder/PodDetails.sh -r " + "\"" + podList + "\""
prtnP = commands.getoutput(cmd).strip()
if prtnP:
print bcolors.FAIL + "Partner Pods [Status: Customer Active|Dev Post Provisioning|Cloud Ops Provisioning]: \n" + bcolors.OKBLUE + prtnP + bcolors.ENDC
cmd = "/fsnadmin/f516478/romeshar/myfolder/PodDetails.sh -s " + "\"" + podList + "\""
stbyP = commands.getoutput(cmd).strip()
if stbyP:
print bcolors.FAIL + "DR/Standby Pods [Status: Customer Active|Dev Post Provisioning|Cloud Ops Provisioning]: \n" + bcolors.OKBLUE + stbyP + bcolors.ENDC
cmd = "/fsnadmin/f516478/romeshar/myfolder/PodDetails.sh -u " + "\"" + podList + "\""
unalloP = commands.getoutput(cmd).strip()
if unalloP:
print bcolors.FAIL + "Unallocated Pods [Status: Dev Post Provisioning|Cloud Ops Provisioning]: \n" + bcolors.OKBLUE + unalloP + bcolors.ENDC
cmd = "/fsnadmin/f516478/romeshar/myfolder/PodDetails.sh -l " + "\"" + podList + "\""
trlP = commands.getoutput(cmd).strip()
if trlP:
print bcolors.FAIL + "Trial Pods [Status: Customer Active|Dev Post Provisioning|Cloud Ops Provisioning]: \n" + bcolors.OKBLUE + trlP + bcolors.ENDC
except OSError:
print bcolors.FAIL + "Could not invoke Pod Details Script. " + bcolors.ENDC
podList = vPodName(podList)
print bcolors.FAIL + "\nYou Have Entered PodList as: " + podList + "\n" + bcolors.ENDC
uResp = str(raw_input('Do You Want To Continue [YES|Y|NO|N] : ')).upper().strip()
#if uResp == "NO" or uResp == "N":
if uResp != "YES" and uResp != 'Y':
pPODName ()
if __name__ == '__main__':
blackout()
I want black.py module to be called in main.py but when I am running main.py I am getting the following error:
[oracle#localhost tmp]$ ./main.py
****************************************************
M A I N - M E N U
****************************************************
0. Enter POD Name(s).
1. QUIT
Enter your choice [0-24] : 0
Traceback (most recent call last):
File "./main.py", line 131, in <module>
pPODName()
NameError: name 'pPODName' is not defined
pPODName has not been defined as far as main.py can tell.
Firstly
pPODName is defined within another function, so only that function is aware of it. This is referred to as being in local scope. Basically anything defined within a function is only accessible to that function, and nothing else.
For an example:
def test():
def test_local():
return 3
return test_local()
Running the function test gives you
>>> test()
3
However running the function test_local
>>> test_local()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'test_local' is not defined
Secondly
Secondly, when importing modules, you need to either qualify them with the module name, like you have done with black.blackout(), of you need to use:
from black import *
Although personally I don't like that, it makes it hard to see where methods are coming from.
Fix
For main.py to be able to call pPODName, it must be defined within the module as a whole, e.g.:
def blackout()
#do stuff here
def pPODNAME()
#do other stuff here
#note the indentation level is the same as blackout
and you must call it with
black.pPODName()
From main.py
You have some programming hierarchy level mistake
why pPODName is inner function of blackout ?
and has James said- if you are using outer and inner function the outer needs to call the inner.
I suggest you to use regular function in black.py
blackout function does nothing except containing the pPODName so you don't need it
Shlomy

Categories

Resources