I was reading about the subprocess module and have gotten very confused. Under my search function, I wanted to use subprocess.check_output to return a printed error message of my chosing when grep failed to find the users input in the text file. How would I go about doing this? Using Python 2.7
import subprocess
def menu():
usr = raw_input("Press 1 if you are creating a new entry, press 2 for search or 3 to exit")
if usr == '1':
collect()
if usr == '2':
search()
if usr == '3':
sys.exit()
if usr == '4':
subprocess.call(['vim', '-c', '10', 'book.txt'])
def search():
inp = raw_input("Please enter a name:")
subprocess.call(['rgrep', '-e', inp])
search()
def collect():
def do_global():
global name, ac, number
name = raw_input("Name")
ac = raw_input("Area Code")
if subprocess.call(['rgrep', '-e', inp]) != 0: # rgrep failed
print("error message of your choosing")
To find out what exit status grep may produce, see its man page
Related
What I'm trying to do is get the position of the users input so if they recall a command it will return the value but it doesn't work for some reason idk why I've tried everything I know please help.
#new file
#new untitled file
args = []
newcommands = []
import time,random,os,sys
commands = ["help","version","python"]
while True:
command = input(">")
if command not in commands:
print("That command does not exist")
if command == "help":
print(commands)
if command == "version":
print("Version = 0.0.1")
if command == "python":
print("Type exit to exit the python interperter")
os.system("python")
if command == "DM ME A COMMAND":
pass
if command == "New":
if len(newcommands) != 5:
name = input("Enter a name: ")
text= input("Enter text for the function: ")
q = newcommands.append(name)
args.append(text)
if q == newcommands.index(0):
print(args.index(0))
if q == newcommands.index(1):
print(args.index(1))
if q == newcommands.index(2):
print(args.index(2))
if q == newcommands.index(3):
print(args.index(3))
if q == newcommands.index(4):
print(args.index(4))
if q == newcommands.index(5):
print(args.index(5))
i dont know what are you trying to do but seems your logic is more than i could understand
because you try to enter New command which is not on the list it means it will never execute the if condition for the "New"
and if that's not all you also try to get command line args which will never given by the user.
so basically please give the description of you question
I'm working on a project, and I got a bit stuck. I want the user the of the program to be able to call a function. But it must be easy for the user to call it. For example
def definition():
print("This is a function")
command = input("> ")
if command == definition:
definition()
else:
print("")
in this function I want the user not to write the () in the input. But I want the user just to be able to write 'definition' to call the function. Does anyone have any clue how to do this?
You are missing the quotes from around definition, therefore trying to compare an undeclared variable with an inputted string which will always equate to false.
Try:
def definition():
print("This is a function")
command = input("> ")
if command == 'definition':
definition()
else:
print("")
You are mixing up the function name (callable object in you code) and the name from your input.
For your problem I would use a dictionary of function names for the keys and function references for the value
def function1():
print ('calling function1')
def function2():
print ('calling function2')
def function3():
print ('calling function3')
functions = {}
functions['function1'] = function1
functions['function2'] = function2
functions['function3'] = function3
name = input('Enter the function name:\n')
if name in functions:
functions[name]()
else:
print ('Invalid function name. Use one of: ')
for key in functions.keys():
print (' - ' + key)
Just one command "definition"
def definition():
print("This is a function")
command = input("> ")
if command == "definition":
definition()
else:
print("Wrong command !")
More commands and functions
def definition():
print("This is definition function")
def modify():
print("This is modify function")
func = {"definition":definition, "modify":modify}
command = input("> ").strip().lower()
if command in func:
func[command]()
else:
print("Wrong command !")
You will have to implicitly define the conditions with if statement..
For ease of user you can do like this:
def definition():
#your function here
if __name__=='__main__':
print ("Choose your option:\n1. Definition")
choice = int(input("Enter choice: "))
if choice == 1:
definition ()
Try this
whitelist_funcs = ['definition', 'something else']
command = input("> ")
if command in whitelist_funcs:
exec(f"{command}()")
else:
print("")
This question already has answers here:
How can I break out of multiple loops?
(39 answers)
Python - `break` out of all loops [duplicate]
(4 answers)
Closed 8 years ago.
Hello i have this login that i am trying to make and when i get to the command screen if i want to exit out of the program i type "exit", but the problem is i have it in a double while loop and don't know how to break out of both. Here is an example of the code:
a = 0
b = 0
loginatt = 0
while a == 0:
if loginatt == 4:
print "Too many tires!"
break
password = raw_input("Password: ")
if password == "test":
b = 1
while b == 1:
command = raw_input("command: ")
if command == "exit":
break
else:
loginatt += 1
print "error, login failed!"
this part of the code won't break out of the double while loop:
command = raw_input("command: ")
if command == "exit":
break
break will only leave one level of looping. You could try resetting your outer loop variable:
if command == "exit":
a = 1
break
However, it might be better to break your code up a bit:
def access_control(correct_pass="test", attempts=4):
"""Control access to the supplied function func."""
for _ in range(attempts):
password = raw_input("Password: ")
if password == correct_pass:
get_commands()
break
else:
print "Incorrect password."
else:
print "Too many tries."
def get_commands():
"""Take user input until they enter 'exit'."""
while True:
command = raw_input("Command: ")
if command == "exit":
break
You can now call access_control to enter the password; if correct, you will be passed on to get_commands:
>>> access_control()
Password: test
Command: exit
>>>
or
>>> access_control()
Password: foo
Incorrect password.
Password: bar
Incorrect password.
Password: baz
Incorrect password.
Password: python
Incorrect password.
Too many tries.
>>>
There is no keyword to break from more than one loop. You can try the following:
wantToBreak = False
while b == 1:
command = raw_input("command: ")
if command == "exit":
wantToBreak = True
break
if wantToBreak:
break
It utilizes a boolean variable which indicates whether the flow should be interrupted (break more levels).
Generally variable names like a and b aren't very explicit. Also your login functionality is independent of your command functionality, hence why not seperate both?
#! /usr/bin/python2.7
def login(maxTries = 4):
while maxTries:
password = raw_input('Password: ')
if password == 'test':
return True
maxTries -= 1
print 'Too many tries.'
return False
def runCommand():
while True:
command = raw_input('Command: ')
if command == 'exit': break
print 'processing command', command
if login(): runCommand()
Instead of breaking when finding the command exit you can also use an iterator with a sentinel:
def runCommand():
for command in iter(lambda: raw_input('Command: '), 'exit'):
print 'processing command', command
Below is the output that I receive, and below that is my code. Any reasons why I'm getting this memory reference? BTW - indentation is correct in my program but I had difficulty posting it in stackoverflow
>>>Welcome to the Main Menu, Richard.
>>>Please select from the following options:
>>>(1)Punch In
>>>(2)Punch Out
>>>(3)Exit
>>>(type 1, 2, or 3)
>>><__main__.PunchCard instance at 0x7f5c2b799ea8>
And the code
import xlrd
import sys
data = xlrd.open_workbook('data.xls')
sheetname = data.sheet_names()
employee_sheet = data.sheet_by_index(0)
uid_list = [c.value for c in employee_sheet.col(0)]
last_list = [c.value for c in employee_sheet.col(1)]
first_list = [c.value for c in employee_sheet.col(2)]
username_list = [c.value for c in employee_sheet.col(3)]
password_list = [c.value for c in employee_sheet.col(4)]
class PunchCard:
def idle_screen(self):
sys.stderr.write("\x1b[2J\x1b[H")
print "Press Enter to start PunchClock"
raw_input()
return self.user_login()
def user_login(self):
sys.stderr.write("\x1b[2J\x1b[H")
userinput = raw_input("Please enter your username.\n> ")
if userinput in username_list:
user_index = username_list.index(userinput)
self.user_first = first_list[user_index]
user_password = raw_input("Welcome %s, please enter your password.\n> " % self.user_first)
else:
print "That is an incorrect username."
raw_input("Press enter to re-enter your username.")
return self.user_login()
if user_password == password_list[user_index]:
return self.main_menu()
else:
sys.stderr.write("\x1b[2J\x1b[H")
print "You have entered an incorrect password.\nPress enter to try again, or type QUIT to return to previous menu."
raw_input()
return self.user_login()
def main_menu(self):
sys.stderr.write("\x1b[2J\x1b[H")
print "Welcome to the Main Menu, %s.\nPlease select from the following options:\n (1)Punch In\n (2)Punch Out\n (3)Exit\n\n(type 1, 2, or 3)" % self.user_first
menu_input = raw_input(self)
if menu_input == '1':
print "punched in"
raw_input("You clocked in at XX. Press enter to continue.")
return self.main_menu()
elif menu_input == '2':
print "punched out"
raw_input("You clocked out at XX. Press enter to continue.")
return self.main_menu()
elif menu_input == '3':
return self.idle_screen()
else:
return self.main_menu()
s = PunchCard()
s.idle_screen()
Ok, based on your comment, I'll answer in more detail then. But please note, I am providing an example based on the your code (there are better ways to achieve the same result, but you'll just have to bite down and read the docs).
The high-level flow of your application is the following infinite loop: idle screen -> user login -> main menu -> idle screen. So this should be expressed directly:
s = PunchCard()
while True:
s.idle_screen()
s.user_login()
s.main_menu()
Then, idle_screen should simply wait for input and return (exit method):
def idle_screen(self):
sys.stderr.write("\x1b[2J\x1b[H")
print "Press Enter to start PunchClock"
raw_input()
# method returns to caller at this point
user_login() should loop until a valid login occurs and return (exit method):
def user_login(self):
While True:
sys.stderr.write("\x1b[2J\x1b[H")
userinput = raw_input("Please enter your username.\n> ")
if userinput in username_list:
user_index = username_list.index(userinput)
self.user_first = first_list[user_index]
user_password = raw_input("Welcome %s, please enter your password.\n> " % self.user_first)
else:
print "That is an incorrect username."
raw_input("Press enter to re-enter your username.")
continue # start of the beginning of the loop again
if user_password == password_list[user_index]:
return # exit method
else:
sys.stderr.write("\x1b[2J\x1b[H")
print "You have entered an incorrect password.\nPress enter to try again, or type QUIT to return to previous menu."
raw_input()
# do nothing here (will loop again)
# Note your prompt mentions "QUIT" but you don't handle it ;)
# Current logic means the login loop continues until a valid login occurs
Finally, main_menu loops until the user quits and the method returns (and everything starts over with the top-level loop):
def main_menu(self):
While True:
sys.stderr.write("\x1b[2J\x1b[H")
print "Welcome to the Main Menu, %s.\nPlease select from the following options:\n (1)Punch In\n (2)Punch Out\n (3)Exit\n\n(type 1, 2, or 3)" % self.user_first
menu_input = raw_input(self)
if menu_input == '1':
print "punched in"
raw_input("You clocked in at XX. Press enter to continue.")
elif menu_input == '2':
print "punched out"
raw_input("You clocked out at XX. Press enter to continue.")
elif menu_input == '3':
return
Hope that helps.
But still, bite down and read the docs :)
How would I write a Python program that would always be looking for user input. I think I would want to have a variable equal to the input and then something different would happen based on what that variable equaled. So if the variable were "w" then it would execute a certain command and keep doing that until it received another input like "d" Then something different would happen but it wouldn't stop until you hit enter.
If you want to constantly look for an user input you'll need multithreading.
Example:
import threading
import queue
def console(q):
while 1:
cmd = input('> ')
q.put(cmd)
if cmd == 'quit':
break
def action_foo():
print('--> action foo')
def action_bar():
print('--> action bar')
def invalid_input():
print('---> Unknown command')
def main():
cmd_actions = {'foo': action_foo, 'bar': action_bar}
cmd_queue = queue.Queue()
dj = threading.Thread(target=console, args=(cmd_queue,))
dj.start()
while 1:
cmd = cmd_queue.get()
if cmd == 'quit':
break
action = cmd_actions.get(cmd, invalid_input)
action()
main()
As you'll see this, will get your messages a little mixed up, something like:
> foo
> --> action foo
bar
> --> action bar
cat
> --> Unknown command
quit
That's beacuse there are two threads writing to stdoutput at the same time. To sync them there's going to be need of lock:
import threading
import queue
def console(q, lock):
while 1:
input() # Afther pressing Enter you'll be in "input mode"
with lock:
cmd = input('> ')
q.put(cmd)
if cmd == 'quit':
break
def action_foo(lock):
with lock:
print('--> action foo')
# other actions
def action_bar(lock):
with lock:
print('--> action bar')
def invalid_input(lock):
with lock:
print('--> Unknown command')
def main():
cmd_actions = {'foo': action_foo, 'bar': action_bar}
cmd_queue = queue.Queue()
stdout_lock = threading.Lock()
dj = threading.Thread(target=console, args=(cmd_queue, stdout_lock))
dj.start()
while 1:
cmd = cmd_queue.get()
if cmd == 'quit':
break
action = cmd_actions.get(cmd, invalid_input)
action(stdout_lock)
main()
Ok, now it's better:
# press Enter
> foo
--> action foo
# press Enter
> bar
--> action bar
# press Enter
> cat
--> Unknown command
# press Enter
> quit
Notice that you'll need to press Enter before typing a command to enter in "input mode".
from http://www.swaroopch.com/notes/Python_en:Control_Flow
#!/usr/bin/python
# Filename: while.py
number = 23
running = True
while running:
guess = int(input('Enter an integer : '))
if guess == number:
print('Congratulations, you guessed it.')
running = False # this causes the while loop to stop
elif guess < number:
print('No, it is a little higher than that.')
else:
print('No, it is a little lower than that.')
else:
print('The while loop is over.')
# Do anything else you want to do here
print('Done')
Maybe select.select is what you are looking for, it checks if there's data ready to be read in a file descriptor so you can only read where it avoiding the need to interrupt the processing (well, in the example it waits one second but replace that 1 with 0 and it'll work perfectly):
import select
import sys
def times(f): # f: file descriptor
after = 0
while True:
changes = select.select([f], [], [], 1)
if f in changes[0]:
data = f.readline().strip()
if data == "q":
break
else:
print "After", after, "seconds you pressed", data
after += 1
times(sys.stdin)
if you want to get input repeatedly from user;
x=1
while x==1:
inp = input('get me an input:')
and based on inp you can perform any condition.
You can also use definitions, say, something like this:
def main():
(your main code)
main()
main()
though generally while loops are much cleaner and don't require global variables :)