reportPath = "C:\\Test\\"
oApp = win32com.client.Dispatch("Outlook.Application")
nSpace = oApp.GetNamespace("MAPI")
nSpace.Logon()
oInbox = nSpace.GetDefaultFolder(win32com.client.constants.olFolderInbox)
oItems = oInbox.Items
for i in range(oItems.Count):
oMsg = oItems.Item(i+1)
oMsg.SaveAs(reportPath+str(i)+".msg", Outlook.OlSaveAsType.olMSG)
oMsg.SaveAs fails as "Outlook.OlSaveAsType.olMSG" parameter invalid.
What is its equivalent in win32com?
Please help
Try to pass a numeric value (olMSG = 3) instead. Or just remove the second parameter, it is optional.
Thanks #Eugene Astafiev for driving it. Finally it worked. Steps following.
OlSaveAsType = {
"olTXT": 0,
"olRTF": 1,
"olTemplate": 2,
"olMSG": 3,
"olDoc": 4,
"olHTML": 5,
"olVCard": 6,
"olVCal": 7,
"olICal": 8
}
&
oMsg.SaveAs("C:\\Test\\1.msg", OlSaveAsType['olMSG'])
Related
I want the user to type in a name, then I want to proceed by using specific values based on that input. My current solution is this:
model = input("Attacking Model:")
unit = float(input("How many " + str(model) +"'s:"))
if model == "Warrior":
bal_Shot = unit * 3
bal_Skill = (4/6)
bal_Str = 5
bal_AP = 2
bal_Dam = 1
elif model == 'Ravener':
bal_Shot = unit * 5
bal_Skill = (4/6)
bal_Str = 5
bal_AP = 2
bal_Dam = 1
However, once I start adding more model names it is going to start to look messy, and I'm assuming there is a more efficient way to do this.
Another solution I have played around with is creating a list for each, then attempting to set the variables to an index of a user inputted list.
model = input("Attacking Model:")
warrior=[3, (4/6), 5, 2, 1]
ravener=[5, (4/6), 5, 2, 1]
bal_Shot = model[0]
bal_Skill = model[1]
bal_Str = model[2]
bal_AP = model[3]
bal_Dam = model[4]
print(bal_Shot)
But when I do this, it is just returning the letter of the input based on index.
Is it possible to return the correct values based on user input?
It looks like you are making a confusion between a variable value and a variable name. If the variable named model contains the value warrior, it does not mean that you can use model[0] and expect python to interpret it as warrior[O]. I see two possible solutions to your problem.
If you know enough about object-oriented programming, I suggest you make the warrior and ravener two instances of the same class (maybe Character). You can then have a list of all your characters that you can iterate on and check if the character type is the same as the value of your model variable entered by the user.
If not, you can select the correct variable using the value entered by the user with vars() that returns a dictionary of all variables in scope (among other things). See this post this post for more information.
A good approach is to use dict:
model = input("Attacking Model:")
objects = {"warrior":
{"ball_shot": 3,
"ball_Skill": (4/6)
},
"ravener":{
"ball_shot": 5,
"ball_Skill": (4/6)
}}
if model in objects.keys():
print(objects[model])
else:
print("Attacking model doesn't exist !")
You can display the result as you wish.
Use a dictionary: you can select which fighter it is:
model = input("Attacking Model:")
fighters = {"warrior": [3, (4/6), 5, 2, 1],
"ravener": [5, (4/6), 5, 2, 1]}
bal_Shot = fighters[model][0]
bal_Skill = fighters[model][1]
bal_Str = fighters[model][2]
bal_AP = fighters[model][3]
bal_Dam = fighters[model][4]
print(bal_Shot)
Note: If the input is bad, you can use a try/except block:
try:
bal_Shot = fighters[model][0]
bal_Skill = fighters[model][1]
bal_Str = fighters[model][2]
bal_AP = fighters[model][3]
bal_Dam = fighters[model][4]
except:
model = input("Attacking Model:")
bal_Shot = fighters[model][0]
bal_Skill = fighters[model][1]
bal_Str = fighters[model][2]
bal_AP = fighters[model][3]
bal_Dam = fighters[model][4]
You could put your ẁarrior and ravener lists into a dictionary, then you can simply get the corresponding values with a dictionary lookup:
model = input("Attacking Model:")
lookup = {
"warrior": [3, 4 / 6, 5, 2, 1]
"ravener": [5, 4 / 6, 5, 2, 1]
}
bal_Shot = lookup[model][0]
bal_Skill = lookup[model][1]
bal_Str = lookup[model][2]
bal_AP = lookup[model][3]
bal_Dam = lookup[model][4]
print(bal_Shot)
It might make sense to check whether the entered model name actually exists in the lookup dictioary, else you'll get a KeyError if the user enters a model name that doesn't exist in the ´ĺookup`:
model = input("Attacking Model: ")
lookup = {
"warrior": [3, 4 / 6, 5, 2, 1]
"ravener": [5, 4 / 6, 5, 2, 1]
}
while model not in lookup: # equivalent to "while model not in lookup.keys()"
model = input("The model name you entered does not exist - please try again: )
bal_Shot = lookup[model][0]
bal_Skill = lookup[model][1]
bal_Str = lookup[model][2]
bal_AP = lookup[model][3]
bal_Dam = lookup[model][4]
print(bal_Shot)
Use nested dictionary:
Class = { 'Warrior':
{'bal_Shot': 3, 'bal_skill': (5/6), 'bal_str': 5, 'bal_AP': 2, 'bal_Dam': 1},
'Ravener':
{'bal_Shot': 5, 'bal_skill': (4/6), 'bal_str': 5, 'bal_AP': 2, 'bal_Dam': 1}
}
model = input("Attacking Model: ")
if model in Class:
unit = float(input("How many " + str(model) + "'s: "))
bal_Shot = unit * Class[model]['bal_Shot']
print(f'{model} {bal_Shot = }')
else:
print('Invalid Attacking Model')
# Attacking Model: Warrior
# How many Warrior's: 2
# Warrior bal_Shot = 6.0
# Attacking Model: Ravener
# How many Ravener's: 3
# Ravener bal_Shot = 15.0
# Attacking Model: Narator
# Invalid Attacking Model
I will be implementing multiprocessing so that the loops are occurring at the same time, but how can I make it so at the end of each iteration, I can obtain the value of westernEurope.cases and easternEurope.cases so that I can add them together
westernEurope = Region("Western Europe", 1000, 0, 0, 8, 4, 4, 0)
while westernEurope.deaths < westernEurope.population:
westernEurope.infection()
if westernEurope.cases > westernEurope.population:
westernEurope.cases = westernEurope.population
print("Infections:", westernEurope.cases)
westernEurope.death()
if westernEurope.deaths > westernEurope.population:
westernEurope.deaths = westernEurope.population
print("Deaths:", westernEurope.deaths)
#where i want to return the value of westernEurope.cases
time.sleep(0.1)
easternEurope = Region("Eastern Europe", 1000, 0, 0, 8, 4, 4, 0)
while easternEurope.deaths < easternEurope.population:
easternEurope.infection()
if easternEurope.cases > easternEurope.population:
easternEurope.cases = easternEurope.population
print("Infections:", easternEurope.cases)
easternEurope.death()
if easternEurope.deaths > easternEurope.population:
easternEurope.deaths = easternEurope.population
print("Deaths:", easternEurope.deaths)
# where i want to return the value of easternEurope.cases
time.sleep(0.1)
print(easternEurope.cases + westernEurope.cases)
IMHO there is no need for multiprocessing. With a generator, your problem can be solved in an even more elgant way.
# where i want to return the value of easternEurope.cases
yield region.cases
Full code:
def desease(region: Region):
while region.deaths < region.population:
region.infection()
if region.cases > region.population:
region.cases = region.population
print("Infections:", region.cases)
region.death()
if region.deaths > region.population:
region.deaths = region.population
print("Deaths:", region.deaths)
# where i want to return the value of easternEurope.cases
yield region.cases
time.sleep(0.1)
easternEurope = Region("Eastern Europe", 1000, 0, 0, 8, 4, 4, 0)
westernEurope = Region("Western Europe", 2000, 0, 0, 8, 4, 4, 0)
eastDesease = desease(easternEurope)
westDesease = desease(westernEurope)
for eastCases, westCases in zip(eastDesease, westDesease):
print(eastCases, westCases)
I'm trying to use a function to generate a dictionary with some variable fields according to the arguments that I give to the function. The idea is to try multiple configurations and obtain different dictionaries.
I have a function already but it looks non pythonic and it looks very hardcoded.
def build_entry(prefix=None,
field_a=None,
field_b=None,
quantity_a=None,
quantity_b=None,
):
fields = {}
if prefix is not None:
fields['prefix'] = prefix
if field_a is not None:
fields['field_a'] = field_a
if field_b is not None:
fields['field_b'] = field_b
if quantity_a is not None:
fields['quantity_a'] = quantity_a
if quantity_b is not None:
fields['quantity_b'] = quantity_b
return fields
The idea is to call the function like this:
fields = build_entry(*config)
Input: [26, 0, None, None, 20]
Output: {'prefix': 26, 'field_a': 0, 'quantity_b': 5}
Input: [20, 5, None, None, None]
Output: {'prefix': 20, 'field_a':5}
Input: [None, None, 0, 5, None]
Output: {'field_b': 0, 'quantity_a':5}
Any idea how to make this function better or more pythonic? Or there is any function that already does this?
I'm using Python 2.7.
def build_entry(*values):
keys = ['prefix', 'field_a', 'field_b', 'quantity_a', 'quantity_b']
return { k: v for k, v in zip(keys, values) if v is not None}
And then called the same way:
In [1]: build_entry(*[26, 0, None, None, 20])
Out[1]: {'prefix': 26, 'field_a': 0, 'quantity_b': 20}
I think that you want something like this:
def build_entry(**kwargs):
return kwargs
if __name__ == '__main__':
print(build_entry(prefix=1, field_a='a'))
Outputs:
{'prefix': 1, 'field_a': 'a'}
I am adding some code to the preset code to check the time availability, which is if the meeting time can fit into the proposed time schedule. However, I keep getting the following error. Can anyone please give me some advices? Thanks so much for your time.
Preset codes:
from datetime import datetime
class Meeting:
def __init__(self, start_time, end_time):
self.start_time = start_time
self.end_time = end_time
My codes:
def check_availability(meetings, proposed_time):
meeting_start = Meeting.datetime.start_time.hour
meeting_end = Meeting.datetime.end_time.hour
ok_time = datetime.proposed_time.hour
if meeting_start < ok_time < meeting_end:
return True
else:
return False
meetings = [Meeting(datetime(2018, 8, 1, 9, 0, 0), datetime(2018, 8, 1, 11,
0, 0)), Meeting(datetime(2018, 8, 1, 15, 0, 0), datetime(2018, 8, 1, 16, 0,
0)), Meeting(datetime(2018, 8, 2, 9, 0, 0), datetime(2018, 8, 2, 10, 0, 0))]
print(check_availability(meetings, datetime(2018, 8, 1, 12, 0, 0)))
print(check_availability(meetings, datetime(2018, 8, 1, 10, 0, 0)))
Your code raises this exception:
AttributeError: type object 'Meeting' has no attribute 'datetime'
At this line:
meeting_start = Meeting.datetime.start_time.hour
Python is telling you that the Meeting class doesn't have an attribute named datetime. This is true: the Meeting class is a factory for making meeting objects (or instances), and these objects have start_time and end_time attributes, which are set by passing datetime instances to Meeting's __init__ method. These attributes can be accessed like this:
>>> meeting = Meeting(datetime(2018, 8, 1, 9, 0, 0), datetime(2018, 8, 1, 11,
0, 0))
>>> print(meeting.start_time)
2018-08-01 09:00:00
>>> print(meeting.end_time)
2018-08-01 11:00:00
Your check_availability function is being passed a list of meetings, so you need to loop over the list to check whether any of the meetings conflict with the proposed meeting time.
def check_availability(meetings, proposed_time):
# Loop over the list of meetings; "meeting"
# is the meeting that you are currently inspecting.
for meeting in meetings:
# if proposed_time is between meeting.start_time
# and meeting.end_time, return False
# If you get through the list without returning False
# then the proposed time must be ok, so return True.
Query
Balance.objects.filter(~Q(fax_date=F('paused_date')))
returns empty qs even though I do have objects that fit the condition "fax date field not equal to paused date". Is it possible to use ~Q and F together like that?
ran a test like this:
deals = Deal.objects.all()
balance_pre = Balance.objects.filter(~Q(fax_date=F('paused_date')), fax_date__isnull=False, reserved=False)
agr_nums = list(deals.filter(agr_name__isnull=False).values_list('agr_name', flat=True).distinct())
agrs_with_fax = 0
for agr_num in agr_nums:
try:
balance_agr = Balance.objects.get(number__icontains=agr_num)
if balance_agr.fax_date is not None and balance_agr.fax_date != balance_agr.paused_date and not balance_agr.reserved:
agrs_with_fax += 1
except Balance.DoesNotExist:
pass
agrs_with_fax2 = 0
for agr_num in agr_nums:
try:
balance_pre.get(number__icontains=agr_num)
agrs_with_fax2 += 1
except Balance.DoesNotExist:
pass
r = [agrs_with_fax, agrs_with_fax2, balance_agr.fax_date, balance_agr.paused_date, balance_agr.reserved]
r returned is
[55, 0, datetime.date(2018, 7, 11), None, False]
I don't see my error, both cycles should return same result.
I created a Balance model in a fresh project just to test that print(qs.query) will show you the generated query(not in all cases) in this case. I used also exclude as #daniel-roseman suggested to prove that they were equivalent. I hope this help you.
>>> from django.db.models import F, Q
>>> qs = Balance.objects.filter(~Q(fax_date=F('paused_date')))
>>> print(qs.query)
SELECT "so_balance"."id", "so_balance"."fax_date", "so_balance"."paused_date"
FROM "so_balance" WHERE NOT ("so_balance"."fax_date" =
("so_balance"."paused_date"))
>>> qs = Balance.objects.exclude(fax_date=F('paused_date'))
>>> print(qs.query)
SELECT "so_balance"."id", "so_balance"."fax_date", "so_balance"."paused_date"
FROM "so_balance" WHERE NOT ("so_balance"."fax_date" =
("so_balance"."paused_date"))