I have a class called Config with an object called "ip_list". There are two lists called ip_list1 and ip_list2. What I want to do is iterate though one of the ip lists based on a user selection. A simple version of my code is here:
ip_list1 = ['192.168.1.1', '192.168.1.2', '192.168.1.3', '192.168.1.4']
ip_list2 = ['192.168.1.5', '192.168.1.6', '192.168.1.7', '192.168.1.8']
class Config:
def __init__(self):
self.ip_list = ""
list = int(input("Chose ip list: ")
if list == 1:
Config.ip_list = "ip_list1"
elif list == 2:
Config.ip_list = "ip_list2"
else:
print(f"{list} is an invalid choice")
for ip in Config.ip_list:
<do something>
This obviously doesn't work or I wouldn't be asking the question :)
It iterates through each letter of the actual string "ip_listx". How do I get it to point to the list and not just use the string?
You have a few issues with the code:
list is a data structure in python. Try renaming the variable from list to something else like foo.
You're using int() to handle taking an input but there's a syntax error because you forgot to include the trailing bracket for int().
It should be foo = int(input("Choose ip list: ")).
Sample:
ip_list1 = ['192.168.1.1', '192.168.1.2', '192.168.1.3', '192.168.1.4']
ip_list2 = ['192.168.1.5', '192.168.1.6', '192.168.1.7', '192.168.1.8']
class Config:
def __init__(self):
self.ip_list = ""
foo = int(input("Chose ip list: "))
if foo == 1:
Config.ip_list = "ip_list1"
elif foo == 2:
Config.ip_list = "ip_list2"
else:
print(f"{foo} is an invalid choice")
for ip in Config.ip_list:
print(ip)
if __name__ == "__main__":
c = Config()
I want user enter IP subnet which is formatted x.x.x.x/y. But if user enters anything different this format, there should be warning as below. But below code is not working as I want.
What is your suggestion?
def test():
while True:
val = raw_input("enter IP:")
try:
IP=ipaddress.ip_network(str(val),True)
except:
if val == "":
print " Enter subnet:"
else:
print " IP should be formatted X.X.X.X/Y"
test()
I have this function in python:
def Alex():
print ("Numele si prenumele: Alex Popescu.")
print ("Varsta: 27 ani.")
print ("Salariu: €1750 ")
print ("Post: Tirist.")
if __name__ == '__main__':
Alex()
When I'm calling the function, python doesn't print the function CODE AND COMMAND LINE
Value returned by input is always string even if someone type only digits like '1'.
actiune = input('Ce actiune doriti sa faceti?(1-4): ')
if actiune == '1':
def Alex():
print ("Numele si prenumele: Alex Popescu.")
print ("Varsta: 27 ani.")
print ("Salariu: €1750 ")
print ("Post: Tirist.")
if __name__ == '__main__':
Alex()
The problem is that input returns a string, and you compare that string with an integer in the code in the picture. actinue = int(actinue) should fix it. Alternatively you might compare it with "1" instead of 1.
I have Python code like:
x = sys.argv[1]
y = sys.argv[2]
i = sofe_def(x,y)
if i == 0:
print "ERROR"
elif i == 1:
return str(some_var1)
else:
print "OOOps"
num = input("Chose beetwen {0} and {1}".format(some_var2, some_var3))
return str(num)
After I must execute this script in shell script and return string in shell variable, like:
VAR1="foo"
VAR2="bar"
RES=$(python test.py $VAR1 $VAR2)
Unfortunately it doesn't work. The way by stderr, stdout and stdin also doesn't work due to a lot of print and input() in code. So how I can resolve my issue? Thank you for answer
That isn't even valid Python code; you are using return outside of a function. You don't wan't return here, just a print statement.
x, y = sys.argv[1:3]
i = sofe_def(x,y)
if i == 0:
print >>sys.stderr, "ERROR"
elif i == 1:
print str(some_var1)
else:
print >>sys.stderr, "OOOps"
print >>sys.stderr, "Choose between {0} and {1}".format(some_var2, some_var3)
num = raw_input()
print num
(Note some other changes:
Write your error messages to standard error, to avoid them being captured as well.
Use raw_input, not input, in Python 2.
)
Then your shell
VAR1="foo"
VAR2="bar"
RES=$(python test.py "$VAR1" "$VAR2")
should work. Unless you have a good reason not to, always quote parameter expansions.
Just use print instead of return - you bash snippet expects result on STDOUT.
I have the following function:
def handleRequest(self, command, ident, ip, duration=0):
if not re.match("^[0-9]+$", ident) or not re.match("^[0-9.]+$", ip) or \
(duration and not re.match("^[0-9]+$", duration)):
print ("Unknown command")
return
if command == "DOTHIS":
reactor.callInThread(self.func, ident, "./DOTHIS.sh", ip, 0, command)
elif command == "DOTHAT":
reactor.callInThread(self.func, ident, "./DOTHAT.sh", ip, 0, command)
elif command == "DOTHAT":
reactor.callInThread(self.func, ident, "./DOTHING.sh", ip, duration, command)
elif command == "DOMORETHINGS":
reactor.callInThread(self.func, ident, "./DOMORETHINGS.sh", ip, duration, command)
else:
print ("Unknown command")
return
I use this function to execute certain scripts on my server.
My problem is the correct syntaxis of the to be executed commands (DOTHIS, DOTHAT etc.)
It must have something to do with regex.
The commands can have several parameters (e.g. DOTHIS 127.0.0.1).
No matter how I query the command, the result is always "Unknown Command".
Could anyone give me an example of a command with the right syntaxis (including a couple of parameters).
Thanks!
in handleRequest what are you sample inputs ?
i.e for command, ident?
assuming ip='127.0.0.1', duration ='10'
FYI, This condition always make the output False if the string contains just number.
(duration and not re.match("^[0-9]+$", duration))
This assumes all arguments are strings, but this should work:
import re
def handleRequest(self, command, ident, ip, duration=0):
returnEarly = 0
if not re.match("^\d+$", ident):
print ("Invalid ident")
returnEarly = 1
if not re.match("^[\d.]+$", ip):
print ("Invalid ip")
returnEarly = 1
if (duration and not re.match("^\d+$", duration)):
print ("Invalid Duration")
returnEarly = 1
if returnEarly:
return
if command == "DOTHIS":
print ("DOTHIS")
elif command == "DOTHAT":
print ("DOTHAT")
elif command == "DOTHING":
print ("DOTHING")
elif command == "DOMORETHINGS":
print ("DOMORETHING")
else:
print ("Unknown command")
handleRequest("", "DOTHIS", "11", "127.0.0.1", "10") # works
handleRequest("", "BADCOMMAND", "11", "127.0.0.1", "10") # fails on command
handleRequest("", "DOTHIS", "11C", "127.0.0B.1", "A10") # fails on arguments
I used the "\d" regex shortcut in python for numbers, I also made each check explicit so if it does fail you know why. If you are passing in arguments that are not strings you can use str(argX) to convert it to a string before checking. I used python 2.7 to test this.
EDIT:
I should also point out, that I lazily did not make this method part of a class, and just passed in the empty string for self.
re.match("^[0-9.]+$", number)
matches all strings that contain only numbers.
So you should be able to do:
def handleRequest(self, command = '0', ident = '0', ip = '0', duration='0'):
use help('re') to find out about what the characters mean.