I want to test if a condition is met for my python script to throw an exception.
I want to test if a variable is set. And if it contains the right value. Here is how my exception is written now:
try:
aws_account = input(colored("Enter the name of the AWS account you'll be working in: ", 'yellow'))
except:
print("That is not a valid Company AWS account.")
else:
I also want to test in the try: statement if the user input is in the format of: company-${aws_account}. Such as company-lab, company-stage, company-prod, etc.
How can I test if aws_account contains the correct value in the try: statement?
Related
I have a file which contains extracted data in the form of python variables.
I expect this data to always come in form of 2 variables(check, output_check).
The problem is that there are cases in which data is either incomplete(just the check variable) or data could not be extracted(meaning no variable at all).The contents of the file will always be different based on the data it extracted.
Here is an example of a file:
check_1 = "Warning, the check has failed"
output_check_1 = "Here is a more detailed result."
check_2 = "Warning, the check has failed"
#There is no output_check_2 variable
#There is no check_3 at all
Next up, a function will generate a report based on the data from the file:
def create_report(check, output_check):
if check.startswith("Warning"):
print(check)
if output_check:
print(output_check)
else:
print("Sorry, couldn't get a more detailed result")
else:
print("Check was successful.")
#Let's call the function
create_report(check_1, output_check_1) #Works
create_report(check_2, output_check_2) #-> NameError because in this case output_check_2 does not exist
create_report(check_3, output_check_3) #-> NameError because none of the arguments exist
As a fix, I came up with the following:
try:
create_report(check_2, output_check_2)
except NameError:
output_check_2 = ""
try:
create_report(check_2, output_check_2)
except NameError:
print("Error - data could not be extracted from the server!")
This way, if argument 2 (output_check_2) is missing I will just receive the result of the check without detailed data and if both arguments are missing(check_3, output_check_3) I am going to receive an error stating that the data could not be extracted at all.
The thing is that I find my "fix" rather barbaric and I am looking for a cleaner way in which to have the same result given that the function will be called many times during execution.
Edit: The variables come from an extraced_data.py file which I import at the start of the script. Unfortunately, I have no access to the script which generated the variables in the fist place thus encountering this issue.
Assuming there's no way to fix how the data is stored*, you could use getattr to deal with the missing data. I'm assuming that you're doing something like this to import:
from dataScript import *
Change that to this:
import dataScript
Then you can do:
check1 = getattr(dataScript, "check1", None) # Will default to None if it doesn't exist
if check1 is not None:
create_report(check_1, getattr(dataScript, "output_check1", None))
Or, if you're on Python 3.8+ and the check variable will never be an empty string:
if check1 := getattr(dataScript, "check1", None):
create_report(check_1, getattr(dataScript, "output_check1", None))
If you have an arbitrary number of these variables, you may need to use a loop. Something like:
for i in range(MAX_VARS):
n = i + 1
if check := getattr(dataScript, f"check{n}", None):
create_report(check_, getattr(dataScript, f"output_check{n}", None))
Where MAX_VARS is the highest variable that you're expecting.
* The input format here is really the issue though. Using a Python script as a database that only sometimes has the correct data seems like the real problem. My solution above is just a workaround.
You could also pass (*argv) instead of (check, output_check). This allows you to pass any number of arguments into your function.
def create_report(*argv):
if argv[0].startswith("Warning"): # argv[0] is your 'check' variable
print(argv[0])
if len(argv) > 1:
print(argv[1]) # argv[1] is your output_check variable
else:
print("No more info.")
else:
print("Check successful")
All you have to do is to change create_report function.
def create_report(check, output_check):
if not check:
print("Error - data could not be extracted from the server!")
return
if not output_check:
output_check = ""
if check.startswith("Warning"):
print(check)
if output_check:
print(output_check)
else:
print("Sorry, couldn't get a more detailed result")
else:
print("Check was successful.")
Now you can just call the function without try-except block.
I find myself in need of a bot for following users on twitter.
When I say user I don't refer to a follower but to a random user that I will find with "Cursor". I'm trying to modify my twitter bot for liking on the timeline for a specific search into one that follows the users for that search. What I don't know how to implement is how do I exactly target a user from the timeline to "create_friendship()"? I'm not targeting a specific user so I don't want to have to specify the 'Id' or the "screen_name" etc.
Looking in Tweepy documentation I wasn't able to find a solution, maybe is under my nose but I'm a newbie and I could use some help.
This is the code for the twitter bot I use for liking tweets.
import tweepy
import time
auth = tweepy.OAuthHandler('','')
auth.set_access_token('','')
api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True)
search = "The searc"
nrTweets = 100
for tweet in tweepy.Cursor(api.search, search).items(nrTweets):
try:
print('User succesfully followed')
tweet.favorite() #in here i should be able to create a friendship as i like
time.sleep(60)
except tweepy.TweepError as e:
print(e.reason)
except StopIteration:
break
How can I turn this bot in one that follow people in the same fashion in which I like tweets? (for a search with a specific keyword)
This is how I resolved if anyone cares.
# Write a function named collatz() that has one parameter named number. If
# number is even, then collatz() should print number // 2 and return this value.
# If number is odd, then collatz() should print and return 3 * number + 1
# Then write a program that lets the user type in an integer and that keeps
# calling collatz() on that number until the function returns the value 1.
# Add try and except statements to the previous project to detect whether the
# user types in a noninteger string. Normally, the int() function will raise a
# ValueError error if it is passed a noninteger string, as in int('puppy'). In the
# except clause, print a message to the user saying they must enter an integer.
try:
number = int(input(("Enter an integer number ")))
def collatz():
global number
if number % 2 == 0:
print(int(number/2))
number = (number/2)
elif number % 2 == 1:
print(int(3*number+1))
number = (3*number+1)
else:
return
while number != 1:
collatz()
except:
print("man, an integer number please! ")
I'm trying to write the automation for the login field. I wanted to test if the username field is clicked and not entered any info and proceed to next field will generate an error message saying "*This field is required"
def test_UserNameValidate(self):
self.driver.getElement("id", "user").click()
self.driver.getElement("id", "password").click()
try:
user_input = self.driver.getElement("id","user")
if not (user_input):
self.driver.getElement("css", "div > div.formErrorContent").text == "*This field is required"
print("pass")
except ValueError as e:
print("e:", e)
When I run this code I don't get the print message saying Pass. So I think it is not going to the try or if condition.
Look at your line of code:
if not (user_input)
if there is a user_input object, then this will never evaluate to true. You're probably wanting to look at
if (user_input.getAttribute("value").equals(""))
am developing a python application . I have validated customer id from database. Means if the entered custid is present in database, i am raising an exception. In exception class i am printing the message . So far it is printing the message. But i am not sure how to get control back to the statement where i am taking the input.
main app
Custid=input("enter custid)
Validate_custid(Custid)
Print(Custid)
validate_custid module
From connections import cursor
From customExceptions import invalidcustidException
Def validate_custid(custid):
Cursor.execute("select count(custid) from customer where custid=:custid",{"custid":custid})
For row in cursor:
Count=row[0]
If Count==0:
Raise invalidcustidException
So far its printing the message in exception.now i want my program to take custid as input whenever this exception occurs. The process should iterate until user enters valid custid.
You should use a try-except block with else statement:
while True:
custid = input('Input custom Id: ')
try:
# Put your code that may be throw an exception here
validate_custid(custid)
except InvalidcustidException as err:
# Handle the exception here
print(err.strerror)
continue # start a new loop
else:
# The part of code that will execute when no exceptions thrown
print('Your custom id {} is valid.'.format(custid))
break # escape the while loop
Take a look at here: https://docs.python.org/3.4/tutorial/errors.html#handling-exceptions
You'll want a try except block.
try:
# portion of code that may throw exception
except invalidcuspidError:
# stuff you want to do when exception thrown
See https://docs.python.org/2/tutorial/errors.html for more.
What you are trying to do is called exception handling. I think the Python docs explain this better than me, so here you go: https://docs.python.org/2/tutorial/errors.html#handling-exceptions
Hi How to identify more than one value in the particular method.For example my method will take two values to send some balance(eg: amount and account number). I did for one value and I am getting errors if method has more than one value
url='http://www.testfire.net/bank/ws.asmx?WSDL'
client = Client(url)
print client
for method in client.wsdl.services[0].ports[0].methods.values():
print "the existing methods in webservice are:" +method.name
while True:
try:
s = raw_input("Enter the name of the method you want to scan: ")
name= getattr(client.service,s)
break
except suds.MethodNotFound as e:
print "Please enter a valid method."
value=raw_input("enter a value for method: ")
result=name(value)
print result
Pls provide suggestions