I'm new in python.
I've found a simple TCP Server's code and it works.
The problem is: i'm not able to make a if...elif...else works.
I think it's a mistake of value's type.
Here's my code (the program always do the else part):
while 1:
data = clientsocket.recv(1024)
tokens = data.split(' ',1)
command = tokens[0]
if not command:
break
else:
if command == 1:
try:
camera.start_preview()
time.sleep(10)
camera.stop_preview()
finally:
camera.close()
elif command == 2:
print "Something"
elif command == 3:
print "something else"
else:
print data
print tokens[0]
print command
clientsocket.close()
It give me the result of the last else which is :
2
2
2
Or the number I send. Thanks in advance for your responses !
command is a string, not an integer; you are comparing:
>>> '2' == 2
False
Instead, use:
...
tokens = data.split(' ', 1)
try:
command = int(tokens[0])
except ValueError:
break
if command == 1:
...
Related
I am implementing the scenario in which i have multiple if,elif,else loops.My problem is when the condition met ,its coming out of the program and exits the program .
Expected Behavior - After successful completion it should not exit but rather again show me the options to select .Only after pressing something like cntrl+c it should exit out the program.
class Manager:
def __init__(self):
self.not_useful_tests = []
self.sdsf
def sdsf(self):
try:
input = raw_input()
if input == 'x':
self.not_useful_tests.append(0)
else:
if input == 1:
verify = self.ABC()
return verify
if input == 2:
verify = self.xyz()
return verify
if input == 3:
verify = self.hyg()
return verify
if input == 4:
verify = self.fgh()
return verify
if input == 5:
verify = self.qwe()
return verify
except KeyboardInterrupt as e:
print "Exception caught : " + str(e)
return None
How to achieve this beahvior ? What to add in the code so as to achieve the task ?
To repeat something while some condition is true, use a while loop:
while True:
input = raw_input()
if input == 1:
return 'some value'
if input == 2:
return 'some other value'
If you don't want to return a function result, but rather want to continue execution outside of the loop, i.e. 'break out of the loop' use break:
while True:
input = raw_input()
if input == 1
print('doing something')
break
if input == 2
print('doing something else')
break
print('Continuing here')
And if that's what you want, you can also set a condition to end the loop like this:
result = None
while result is None:
input = raw_input()
if input == 1:
result = 'x'
if input == 2:
result = 'y'
print('will continue here if result has a value')
I wrote simple app that allows to ping machines in local network of my school's computer lab and reboot/turn them all off, or one by one. App works well, but it contains large block of elif statements assigned to specified machines in the lab (there are 18 computers):
def shutdown_all():
with open(os.devnull, "wb"):
for computer in range(1, 19):
ip = "pracownia{0}".format(computer)
subprocess.call('shutdown -s -t 0 /m \\\\%s' % ip)
print("\nTask complete\n")
def shutdown_selected(ip):
with open(os.devnull, "wb"):
machine = "pracownia{0}".format(ip)
subprocess.call('shutdown -s -t 0 /m \\\\%s' % machine)
print("\nTask complete\n")
while True:
mode = input()
if mode == 'exit':
break
elif mode == "shutdown -all":
shutdown_all()
elif mode == "shutdown -ip 1":
shutdown_selected(1)
elif mode == "shutdown -ip 2":
shutdown_selected(2)
elif mode == "shutdown -ip 3":
shutdown_selected(3)
...
else:
print("Wrong mode. Type valid command.")
Is it possible to simplify the instruction and reduce the entire block to one elif statement allowing the user to input which computer he wants to ping/reboot/shutdown?
Same as previous answer but using a regex to parse as the IPs can be 1-2 digits.
import re
mode = input()
if mode == 'exit'
break
elif mode == 'shutdown -all'
shutdown_all()
elif mode[:12] == 'shutdown -ip':
match = re.search(r'\d+', mode)
if match:
ip = match.group()
shutdown_selected(ip)
A common way to reduce complexity of large if-else trees is to use dictionaries. However, you will offload the comeplexity to somewhere else. For example this:
options = dict(foo = foo, bar = bar, foobar = foobar)
options.get(input("Enter an option"), print('Input is not an option'))
This example shows that you have three different functions for three different option keywords. The method get will look for the option in the dictionary else it will print and error message.
With regard to your code I would offload the complexity to one function as such:
def shutdown(command):
computers = set(str(i) for i in range(1,19))
with open(os.devnull, "wb"):
selecComputers = set(command.split(' ')[2:]) # or use regex
if len(selectComputers) > 0:
computers = computers.intersection(selectComputers)
for computer in computers:
ip = "pracownia{0}".format(computer)
subprocess.call('shutdown -s -t 0 /m \\\\%s' % ip)
print("\nTask complete\n")
while True:
mode = input()
if mode == 'exit':
break
elif 'shutdown' in mode:
shutdown(mode)
else:
print("Wrong mode. Type valid command.")
Could you not do something like:
mode = input()
if mode == 'exit'
break
elif mode == 'shutdown -all'
shutdown_all()
elif mode[:12] == 'shutdown -ip':
shutdown_selected(int(mode[-1:]))
You can add a bit to that last elif statement to make sure they are typing something that will work for your function - is that what you needed?
I understand the error but I'm trying to add an if statement to it.
def repeat():
message = input("command: ").split(" ")
if len(message) == 2: #if there is a first parameter
cmd,param = message #add it to the message
elif len(message) == 3: #if there is a first and second parameter
cmd,param,param2 = message #add it to the message
else: #if there is no first and second parameter
cmd = message #add just the command to the message
if cmd == "local":
if len(message) == 2 or len(message) == 3: #if there is a first or second parameter
print("error: no first or second parameter in command 'local'") #error
repeat()
else: #if there are no parameters
print("test") #execute the command
repeat()
else:
print("unrecognized command")
repeat()
repeat()
Edit: When I add a second parameter to the command 'local' it returns the error on line 11, but when I do not add a first or second parameter it prints "unrecognized command" used on line 17.
Your code is written not so nice and you should formulate your question better, but I have fixed the error anyway.
def repeat():
message = input("command: ").split(" ")
#correction starts here
lenght = len(message)
param = False
param2 = False
if lenght == 1:
cmd = message[0]
elif lenght == 2:
cmd = message[0]
param = message[1]
elif lenght == 3:
cmd = message[0]
param = message[1]
param2 = message[2]
else:
repeat()
#correction ends here
if cmd == "local":
if param: #if there is at least one parameter
print("error: no first or second parameter in command 'local'") #error
else: #if there are no parameters
print(message) #execute the command
repeat()
if cmd == "print":
if param2: #if there is a second parameter
print("error: no second parameter in command 'print'") #error
elif param: #if there is only one parameter
print(message) #print only the first parameter (example: print test would output 'test')
repeat()
repeat()
I think it's a very easy thing to do but im still searching for an answer.
I have a Python script running which looks like this:
Waiting for argument:_________
Is there an easy way how i can start the script and automatically put some arguments in it?
I really don't understand u but i think u want something like
import os, sys
#def some_other_functions
def cmd():
try:
com = raw_input('Waiting for argument:_________ ')
#Or u can pass values as sys.args
#like com = sys.argv[1]
while len(com) == 0:
com = raw_input('Waiting for argument:_________ ')
if len(com) != 0:
print os.system(com)
if str(com) == 'exit':
sys.exit()
print '\nContinuer executing other commands or write --exit to quite the program\n'
while True:
com = raw_input('Waiting for argument:_________ ')
if len(com) == 0:
print 'Entered nothing'
if str(com) == 'exit':
sys.exit()
else:
print os.system(com)
except Exception, e:
print str(e)
cmd()
When the Condition matches, It is printing the proper output as expected. But when the condition does not match the "if not found" part is not working.
here If condition checks the username and password both. If it satisfies, It executes the code below it, But when It does not match, It displays blank , I mean there is no Invalid Login printed , though It should get printed
passwd = {}
actual_user = {}
found = False
for row in prsnobj.result:
actual_user[row[0]] = row[1]
for i in range(1, 100):
passwd[row[0]] = row[2]
for i in range(1, 100):
if login == actual_user[i] and password == passwd[i]:
found = True
print "WELCOME !!"
if not found:
print "<h4>Invalid Login</h4>"
You can write this without a flag, using for/else:
for u, p in zip(actual_user.values(), passwd.values()):
if login == u and password == p:
print "WELCOME !!"
break
else:
print "<h4>Invalid Login</h4>"
But it may be better to use a dictionary:
logindb = {row[1]:row[2] for row in prsnobj.result}
if login in logindb and logindb[login] == password:
print "WELCOME !!"
else:
print "<h4>Invalid Login</h4>"
The relevant part of your code could be more simple expressed as this:
if a == 1:
found = True
if not found:
print "not found"
The problem with this is that you never set found to false. Even if a is not equal to 1, found is still true from the last time you found something.
So the solution is something like this:
found = False
if a == 1:
found = True
if not found:
print "not found"
for row in prsnobj.result:
logindb = {row[1]:row[2]}
#print logindb
if login in logindb and logindb[login] == password:
print "Welcome"
break
else:
print "Invalid"
break