I am trying to upload some files to a website and so far I've tried everything I could find and nothing is working. The html input element won't let me sendKeys to it so I found this class to try and use it.
class SystemDialog:
RECURSION_LIMIT = 20
def __init__(self, application_pid, dialog_title=None):
self.__path_to_file = None
self.__recursions = 0
self.dialog_title = "Open" if dialog_title is None else dialog_title
self.accept_button = "&SaveButton" if self.dialog_title == "Save As" else "&OpenButton"
self.decline_button = "&CancelButton"
app = pywinauto.application.Application()
app.connect(process=application_pid)
self.dialog = app.window(title=self.dialog_title)
def __wait_for_dialog(self):
start = time.time()
while not self.dialog.exists() and (time.time() - start) <= 10:
time.sleep(1)
if not self.dialog.exists():
raise Exception("System Dialog did not show in 10 seconds")
def input_file_path(self, path_to_file):
self.__wait_for_dialog()
self.__path_to_file = path_to_file
if path_to_file is not None:
self.dialog.set_focus()
self.dialog.Edit.type_keys(self.__path_to_file)
return self
def accept(self):
if self.__recursions == SystemDialog.RECURSION_LIMIT:
raise Exception("Not able to accept the System dialog.")
self.__wait_for_dialog()
self.dialog.set_focus()
self.dialog[self.accept_button].click()
if self.dialog.exists():
self.__recursions += 1
if self.__path_to_file is not None:
return self.input_file_path(self.__path_to_file).accept() # <--- FYI Recursion
else:
raise Exception("Trying to accept dialog without any inputs, not gonna work.")
self.__recursions = 0
def decline(self):
if self.__recursions == SystemDialog.RECURSION_LIMIT:
raise Exception("Not able to decline the System dialog.")
self.__wait_for_dialog()
self.dialog.set_focus()
self.dialog[self.decline_button].click()
if self.dialog.exists():
self.__recursions += 1
return self.decline() # <--- Recursion
self.__recursions = 0
Here is the HTML as well
HTML
Here is me trying to send the files in my python code:
#Upload files
click(driver, 5, By.XPATH, '//*[#id="dm-react-shared-container"]/div/div[10]/div/div[1]/div[1]/div[2]/div[1]/div/div/div[5]/div/div[2]/div/div[2]', False)
click(driver, 5, By.XPATH, '//*[#id="downshift-0-label"]/div[1]/button', False)
process = psutil.Process(driver.service.process.pid) # chromedriver pid
pid = process.children()[0].pid # chrome tab pid
dialog = SystemDialog(application_pid=pid)
dialog.input_file_path(path)
dialog.accept()
I am met with this error:
Traceback (most recent call last):
File "blaineus_v2.py", line 331, in <module>
main()
File "blaineus_v2.py", line 64, in main
uploadPDFs(destination, driver, email, password, projectName)
File "blaineus_v2.py", line 324, in uploadPDFs
dialog.input_file_path(path)
File "blaineus_v2.py", line 91, in input_file_path
self.__wait_for_dialog()
File "blaineus_v2.py", line 88, in __wait_for_dialog
raise Exception("System Dialog did not show in 10 seconds")
Exception: System Dialog did not show in 10 seconds
Related
The Code:
# Libraries
import io
import os
import numpy as np
import pandas as pd
import streamlit as st
def login():
# interface codes for the login screen
# (css,buttons,background,input area etc )
path_input_0 = st.text_input(
"File Path:",
"Please enter the path to the folder containing the Abstract_Account_Web_App.py file",
key="PATH_INPUT_LAST"
)
st.write(path_input_0)
global proceed
if st.button("Proceed"):
st.session_state["page"] = "main"
st.balloons()
st.experimental_rerun()
def main():
if 'PATH_INPUT_LAST' in st.session_state:
file0 = st.session_state["PATH_INPUT_LAST"]+"/Bankomat Alışveriş Özeti.csv"
st.write(file0)
if(os.path.exists(file0) and os.path.isfile(file0)):
os.remove(file0)
print("file was deleted as preprocessing")
else:
print("file was not found to delete")
# interface codes for the main screen
# (css,input,buttons etc.)
def set_texts(pdf_files:list):
print("starting to text process")
#This function reads pdf and gets "CRC-32" components as texts
for pdf_file in pdf_files:
with fitz.open(pdf_file) as doc:
text = ""
for page in doc:
new_text = page.get_text()
text += new_text
return text
pathz = st.session_state["PATH_INPUT_LAST"] + "/Bankomat Alışveriş Özeti.pdf"
st.write("path1:", pathz)
file_names = r'%s' % pathz
st.write(file_names)
set_texts([file_names])
if st.button('Show Info Analysis'):
st.write(file_names) #ERROR HERE
if __name__ == "__main__":
if "page" not in st.session_state:
st.session_state["page"] = "login"
if st.session_state["page"] == "login":
login()
elif st.session_state["page"] == "main":
st.balloons()
main()
Hello friends, I’m entering the input area on the login screen: "folder path containing the Abstract_Account_Web_App.py file" and then I am pressing the Proceed button.
When it comes to the main screen, path1, and file_names are displayed correctly and properly. However, when I click the 'Show Info Analysis' button on the main screen, I get an error as below:
"KeyError: 'st.session_state has no key "PATH_INPUT_LAST". Did you forget to initialize it? More info: https://docs.streamlit.io/library/advanced -features/session-state#initialization'"
How can I solve this problem?
Traceback:
File "f:\anaconda\lib\site-packages\streamlit\runtime\scriptrunner\script_runner.py", line 556, in _run_script
exec(code, module.__dict__)
File "C:\Users\Desktop\abstract_account\Abstract_Account_Web_App.py", line 85, in <module>
main()
File "C:\Users\Desktop\abstract_account\Abstract_Account_Web_App.py", line 64, in main
pathz = st.session_state["PATH_INPUT_LAST"] + "/Bankomat Alışveriş Özeti.pdf"
File "f:\anaconda\lib\site-packages\streamlit\runtime\state\session_state_proxy.py", line 93, in __getitem__
return get_session_state()[key]
File "f:\anaconda\lib\site-packages\streamlit\runtime\state\safe_session_state.py", line 111, in __getitem__
return self._state[key]
File "f:\anaconda\lib\site-packages\streamlit\runtime\state\session_state.py", line 440, in __getitem__
raise KeyError(_missing_key_error_message(key))
def login():
# interface codes for the login screen
# (css,buttons,background,input area etc )
path_input_0 = st.text_input(
“File Path:”,
“Please enter the path to the folder containing the Abstract_Account_Web_App.py file”) #delete key
and
if st.button("Proceed"):
st.session_state["page"] = "main"
st.session_state["PATH_INPUT_LAST"] = path_input_0 #add this
st.balloons()
st.experimental_rerun()
I would like to be able to start a testmodule that is in my CANoe script; it works fine if I start everything without Python.
Now, my Python code can load CANoe, open the desired cfg, and start the simulation.
I tried some code from examples in the documentation and here, but it doesnt work...
# --------------------------------------------------------------------------
# Standard library imports
import os
import sys
import subprocess
# import win32com.client
import time
import threading
from win32com.client import *
from win32com.client.connect import *
my_xml_ts = r"C:\_my_path\boaz_test2.xml"
# Vector Canoe Class
class CANoe:
def __init__(self):
self.application = None
# check if there is any instance of CANoe process
# output = subprocess.check_output('tasklist', shell=True)
# if CANoe process is still available, kill the process
# if "CANoe32.exe" in str(output):
# os.system("taskkill /im CANoe32.exe /f 2>nul >nul")
# re-dispatch object for CANoe Application
self.application = win32com.client.DispatchEx("CANoe.Application")
self.ver = self.application.Version
print('Loaded CANoe version ',
self.ver.major, '.',
self.ver.minor, '.',
self.ver.Build, '...')#, sep,''
self.Measurement = self.application.Measurement.Running
print(self.Measurement)
def open_simulation(self, cfgname):
# open CANoe simulation
if (self.application != None):
# check for valid file and it is *.cfg file
if os.path.isfile(cfgname) and (os.path.splitext(cfgname)[1] == ".cfg"):
self.application.Open(cfgname)
else:
raise RuntimeError("Can't find CANoe cfg file")
else:
raise RuntimeError("CANoe Application is missing,unable to open simulation")
def set_testmodule(self):
print("set_testmodule start")
test_env = self.application.Configuration.TestSetup.TestEnvironments.Item("Test Environment")
print("set_testmodule 1")
test_env = win32com.client.CastTo(test_env, "ITestEnvironment2")
print("set_testmodule 2")
self.test_module = test_env.TestModules.Item("XML_Boaz_2")
print("set_testmodule end", self.test_module)
def test_module_run(self):
print("test_module_run start")
self.test_module.Start()
print("test_module_run end")
# {.Sequence} property returns a collection of <TestCases> or <TestGroup>
# or <TestSequenceItem> which is more generic
seq = self.test_module.Sequence
for i in range(1, seq.Count + 1):
# Cast from <ITestSequenceItem> to <ITestCase> to access {.Verdict}
# and the {.Enabled} property
tc = win32com.client.CastTo(seq.Item(i), "ITestCase")
if tc.Verdict != 1: # Verdict 1 is pass
tc.Enabled = True
print(f"Enabling Test Case {tc.Ident} with verdict {tc.Verdict}")
else:
tc.Enabled = False
print(f"Disabling Test Case {tc.Ident} since it has already passed")
def close_simulation(self):
# close CANoe simulation
if (self.application != None):
self.stop_Measurement()
self.application.Quit()
# make sure the CANoe is close properly, otherwise enforce taskkill
output = subprocess.check_output('tasklist', shell=True)
if "CANoe32.exe" in str(output):
os.system("taskkill /im CANoe32.exe /f 2>nul >nul")
self.application = None
def start_Measurement(self):
retry = 0
retry_counter = 5
# try to establish measurement within 20s timeout
while not self.application.Measurement.Running and (retry < retry_counter):
self.application.Measurement.Start()
time.sleep(1)
retry += 1
if (retry == retry_counter):
raise RuntimeWarning("CANoe start measuremet failed, Please Check Connection!")
and running that:
import Python_CANoe
import time
import random
def try2():
X = random.randrange(50)
Y = random.randrange(100)
print("start")
CANoe = Python_CANoe.CANoe()
CANoe.open_simulation(canoe_config_file)
CANoe.set_testmodule() # Doesn't work
print("CANoe script already Open")
CANoe.start_Measurement()
time.sleep(5)
CANoe.test_module_run() # Doesn't work
if __name__ == "__main__":
try2()
and this is the error code I am getting:
set_testmodule start
Traceback (most recent call last):
File "C:/Users/m.m/Documents/Python/CANoe_Python_Script/7_5_2021_3_for_stackoverflow/CANoe_Boaz_Test.py", line 133, in <module>
try2()
File "C:/Users/m.m/Documents/Python/CANoe_Python_Script/7_5_2021_3_for_stackoverflow/CANoe_Boaz_Test.py", line 77, in try2
CANoe.set_testmodule() # Doesn't work
File "C:\Users\m.m\Documents\Python\CANoe_Python_Script\7_5_2021_3_for_stackoverflow\Python_CANoe.py", line 52, in set_testmodule
test_env = self.application.Configuration.TestSetup.TestEnvironments.Item("Test Environment")
File "C:\Users\BOAZ~1.BIL\LOCALS~1\Temp\gen_py\3.7\7F31DEB0-5BCC-11D3-8562-00105A3E017Bx0x1x58.py", line 15873, in Item
ret = self._oleobj_.InvokeTypes(0, LCID, 2, (9, 0), ((12, 1),),index
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, 'TestEnvironments::Item', 'Invalid index: Item not found!', 'C:\\Program Files\\Vector CANoe 11.0\\Help01\\CANoeCANalyzer.chm', 4281, -2147467259), None)
Hi guys I'm new to automation and trying out to automate my ui and generate the HTML test report for it. I'm using Html-test runner for it.
Please refer the following code:
#invalid Password
def test1(self):
rva = signUp_invalidpassword(self.driver)
self.assertEqual("Error : Invalid password",rva)
time.sleep(6)
# self.driver.refresh()
# time.sleep(10)
#Password Mismatch
def test2(self):
rvb = signUp_passwordmismatch(self.driver)
self.assertEqual("Error : Confirm Password is not matching",rvb)
time.sleep(5)
#Signup Succesfully
def test3(self):
time.sleep(5)
rvc = signUp(self.driver)
self.assertEqual("Device Monitoring and Analysis Tool",rvc)
time.sleep(8)
#Default RF parameter
def test4(self):
rvd = SignIn(self.driver)
self.assertEqual("RSRP",rvd)
time.sleep(5)
#Default Zoom_level
def test5(self):
rve = zoomLevel(self.driver)
self.assertEqual("Zoom level: 4.0",rve)
time.sleep(5)
#Chance RF parameter
def test6(self):
rvf = changeRF(self.driver)
self.assertEqual("RSRQ",rvf)
time.sleep(4)
#Empty Search State
def test7(self):
rvg = noState(self.driver)
self.assertEqual("Please enter a search term.",rvg)
time.sleep(4)
#Polygon Functionality
def test8(self):
rvj = polygon(self.driver)
self.assertEqual("CLOSE",rvj)
if __name__=='__main__':
unittest.main(testRunner=HtmlTestRunner.HTMLTestRunner(output='Dmat_dir'))
But I'm getting the following output:
Generating HTML reports...
Traceback (most recent call last):
File "C:/Users/inswadhwa/PycharmProjects/automation/assertion.py", line 99, in <module>
unittest.main(testRunner=HtmlTestRunner.HTMLTestRunner(output='Dmat_dir'))
File "C:\Users\inswadhwa\AppData\Local\Programs\Python\Python36-32\lib\unittest\main.py", line 95, in __init__
self.runTests()
File "C:\Users\inswadhwa\AppData\Local\Programs\Python\Python36-32\lib\unittest\main.py", line 256, in runTests
self.result = testRunner.run(self.test)
File "C:\Users\inswadhwa\AppData\Local\Programs\Python\Python36-32\lib\site-packages\HtmlTestRunner\runner.py", line 95, in run
result.generate_reports(self)
File "C:\Users\inswadhwa\AppData\Local\Programs\Python\Python36-32\lib\site-packages\HtmlTestRunner\result.py", line 339, in generate_reports
testRunner)
File "C:\Users\inswadhwa\AppData\Local\Programs\Python\Python36-32\lib\site-packages\HtmlTestRunner\result.py", line 316, in _report_tests
tests = self.sort_test_list(tests)
File "C:\Users\inswadhwa\AppData\Local\Programs\Python\Python36-32\lib\site-packages\HtmlTestRunner\result.py", line 303, in sort_test_list
return sorted(test_list, key=self.get_test_number)
File "C:\Users\inswadhwa\AppData\Local\Programs\Python\Python36-32\lib\site-packages\HtmlTestRunner\result.py", line 295, in get_test_number
test_number = int(test_name.split('_')[1])
IndexError: list index out of range
Process finished with exit code 1
Can any one help me with this?
Try changing the name from test1 to test_1 for all test. From the error it seems the runner assumes there will be _ in the name
To control the order use test names like test_001, test_002 and so on.
Also it seems HtmlTestRunner is quite basic and not a great option. So look for alternatives
I am tring to make script controlling firewall rules on DVS ports.
Here is my script(I have tried to post only relevant part, but even it big enough):
#!/usr/bin/evn python
import sys
import pprint
from oslo.vmware import api as vmware_api
from oslo.vmware import vim_util
vcenter_host = 'vcenter-hostname.tld'
vcenter_login = 'login'
vcenter_password = 'password'
vcenter_retry_count = 4
vcenter_retry_interval = 2
def main():
vcenter = _make_connect()
dvs = _lookup_dvs(vcenter, 'dvSwitch')
port = _lookup_dvs_port(vcenter, dvs, '4853')
spec_factory = vcenter.vim.client.factory
port_spec = spec_factory.create('ns0:DVPortConfigSpec')
port_spec.operation = 'edit'
port_spec.key = port.key
port_spec.configVersion = port.config.configVersion
port_spec.setting = port_setting = spec_factory.create('ns0:DVPortSetting')
port_setting.filterPolicy = filter_policy = spec_factory.create(
'ns0:DvsFilterPolicy')
filter_policy.filterConfig.append(spec_factory.create(
'ns0:DvsTrafficFilterConfig'))
filter_policy.inherited = False
filter_config = filter_policy.filterConfig[0]
filter_config.agentName = "custom-dvs-firewall-agent"
filter_config.inherited = False
filter_config.trafficRuleset = traffic_ruleset = spec_factory.create(
'ns0:DvsTrafficRuleset')
traffic_ruleset.enabled = True
traffic_ruleset.rules.append(spec_factory.create('ns0:DvsTrafficRule'))
rule = traffic_ruleset.rules[0]
rule.description = "Port rule 0"
rule.sequence = 10
rule.direction = "incomingPackets"
rule.action = spec_factory.create('ns0:DvsDropNetworkRuleAction')
rule.qualifier.append(spec_factory.create('ns0:DvsIpNetworkRuleQualifier'))
match = rule.qualifier[0]
match.protocol = proto = spec_factory.create('ns0:IntExpression')
proto.value = 6
proto.negate = False
match.destinationIpPort = port = spec_factory.create('ns0:DvsSingleIpPort')
port.portNumber = 50001
port.negate = False
# import pdb; pdb.set_trace()
task = vcenter.invoke_api(
vcenter.vim,
'ReconfigureDVPort_Task',
dvs, port=[port_spec]
)
result = vcenter.wait_for_task(task)
pprint.pprint(result)
def _make_connect():
return vmware_api.VMwareAPISession(
vcenter_host,
vcenter_login,
vcenter_password,
vcenter_retry_count,
vcenter_retry_interval)
def _lookup_dvs(vcenter, name):
network_folder = _lookup_net_folder(vcenter)
networks = vcenter.invoke_api(
vim_util, 'get_object_property', vcenter.vim,
network_folder, 'childEntity').ManagedObjectReference
for dvs in _filter_objects_by_type(
networks, 'VmwareDistributedVirtualSwitch'):
dvs_name = vcenter.invoke_api(
vim_util, 'get_object_property',
vcenter.vim, dvs, 'name')
if dvs_name != name:
continue
break
else:
raise RuntimeError('DVS name=="{}" not found'.format(name))
return dvs
def _lookup_dvs_port(vcenter, dvs, port_key):
spec_factory = vcenter.vim.client.factory
criteria = spec_factory.create(
'ns0:DistributedVirtualSwitchPortCriteria')
criteria.portKey = port_key
try:
port = vcenter.invoke_api(
vcenter.vim, 'FetchDVPorts', dvs, criteria=criteria)[0]
except IndexError:
raise RuntimeError('DVS port key=="{}" not found'.format(port_key))
return port
def _lookup_net_folder(vcenter):
dc = _lookup_datacenter(vcenter)
return vcenter.invoke_api(
vim_util, 'get_object_property', vcenter.vim,
dc, 'networkFolder')
def _lookup_datacenter(vcenter):
return vcenter.invoke_api(
vim_util, 'get_objects', vcenter.vim,
'Datacenter', 100, ['name']).objects[0].obj
def _filter_objects_by_type(sequence, value):
return (obj for obj in sequence
if obj._type == value)
if __name__ == '__main__':
sys.exit(main())
results:
Traceback (most recent call last):
File "_dev_/dvs-port-filterPolicy.py", line 137, in <module>
sys.exit(main())
File "_dev_/dvs-port-filterPolicy.py", line 70, in main
result = vcenter.wait_for_task(task)
File "/home/dbogun/.venv/cisco0-neutron/lib/python2.7/site-packages/oslo_vmware/api.py", line 380, in wait_for_task
return evt.wait()
File "/home/dbogun/.venv/cisco0-neutron/lib/python2.7/site-packages/eventlet/event.py", line 121, in wait
return hubs.get_hub().switch()
File "/home/dbogun/.venv/cisco0-neutron/lib/python2.7/site-packages/eventlet/hubs/hub.py", line 294, in switch
return self.greenlet.switch()
File "/home/dbogun/.venv/cisco0-neutron/lib/python2.7/site-packages/oslo_vmware/common/loopingcall.py", line 76, in _inner
self.f(*self.args, **self.kw)
File "/home/dbogun/.venv/cisco0-neutron/lib/python2.7/site-packages/oslo_vmware/api.py", line 397, in _poll_task
'info')
File "/home/dbogun/.venv/cisco0-neutron/lib/python2.7/site-packages/oslo_vmware/api.py", line 341, in invoke_api
return _invoke_api(module, method, *args, **kwargs)
File "/home/dbogun/.venv/cisco0-neutron/lib/python2.7/site-packages/oslo_vmware/api.py", line 122, in func
return evt.wait()
File "/home/dbogun/.venv/cisco0-neutron/lib/python2.7/site-packages/eventlet/event.py", line 121, in wait
return hubs.get_hub().switch()
File "/home/dbogun/.venv/cisco0-neutron/lib/python2.7/site-packages/eventlet/hubs/hub.py", line 294, in switch
return self.greenlet.switch()
File "/home/dbogun/.venv/cisco0-neutron/lib/python2.7/site-packages/oslo_vmware/common/loopingcall.py", line 123, in _inner
idle = self.f(*self.args, **self.kw)
File "/home/dbogun/.venv/cisco0-neutron/lib/python2.7/site-packages/oslo_vmware/api.py", line 95, in _func
result = f(*args, **kwargs)
File "/home/dbogun/.venv/cisco0-neutron/lib/python2.7/site-packages/oslo_vmware/api.py", line 324, in _invoke_api
raise clazz(six.text_type(excep), excep.details)
oslo_vmware.exceptions.VMwareDriverException: The object has already been deleted or has not been completely created
Cause: Server raised fault: 'The object has already been deleted or has not been completely created'
Faults: [ManagedObjectNotFound]
Details: {'obj': 'task-5189'}
PortGroup config's trafficFilterOverrideAllowed option must be set to True. Or you get "oslo_vmware.exceptions.VMwareDriverException: A specified parameter was not correct.\nfilterPolicy". What is completely unusable and give absolutely no information about real problem.
Can point me on error in my understanding of this task? Or maybe someone have example of similar script?
PS: vCenter v5.5
You have to set:
filter_config.agentName = "dvfilter-generic-vmware"
I don't know why, but only with this agent name dvs apply ACL rules.
I'm trying to get my emails to work from commandline with mutt. I have been trying to follow these two guides: http://blog.developwithpassion.com/2013/05/02/getting-up-and-running-with-a-sane-mutt-setup/ and http://stevelosh.com/blog/2012/10/the-homely-mutt/#configuring-offlineimap
To do this there are 4 main steps:
1. setup offlineimap to download and keep synced your emails
2. setup mutt (the email user interface)
3. setup notmuch (to be able to search your emails)
4. setup msmtp (to be able to send emails)
Note that I am using Macbook Pro running the OS X 10.9.2. I am stuck at step 1 because I am getting an error with offlineimap! I am able to run offlineimap for a long time, i.e. it will sync all of the emails (36197 of them!) and then right at the end it spits out the following error:
ERROR: getfolder() asked for a nonexisting folder 'Drafts'.
Folder Deleted Items [acc: gloriphobia]:
Establishing connection to imap.gmail.com:993
Account sync gloriphobia:
*** Finished account 'gloriphobia' in 137:16
ERROR: Exceptions occurred during the run!
ERROR: command: UID => socket error: <class 'socket.error'> - [Errno 54] Connection reset by peer
Traceback:
File "/usr/local/Cellar/offline-imap/6.5.5/libexec/offlineimap/folder/IMAP.py", line 219, in getmessage
'(BODY.PEEK[])')
File "/usr/local/Cellar/offline-imap/6.5.5/libexec/offlineimap/imaplib2.py", line 1167, in uid
return self._simple_command('UID', command, *args, **kw)
File "/usr/local/Cellar/offline-imap/6.5.5/libexec/offlineimap/imaplib2.py", line 1615, in _simple_command
return self._command_complete(self._command(name, *args), kw)
File "/usr/local/Cellar/offline-imap/6.5.5/libexec/offlineimap/imaplib2.py", line 1378, in _command_complete
typ, dat = rqb.get_response('command: %s => %%s' % rqb.name)
File "/usr/local/Cellar/offline-imap/6.5.5/libexec/offlineimap/imaplib2.py", line 176, in get_response
raise typ(exc_fmt % str(val))
ERROR: getfolder() asked for a nonexisting folder 'Drafts'.
Traceback:
File "/usr/local/Cellar/offline-imap/6.5.5/libexec/offlineimap/accounts.py", line 241, in syncrunner
self.sync()
File "/usr/local/Cellar/offline-imap/6.5.5/libexec/offlineimap/accounts.py", line 320, in sync
localfolder = self.get_local_folder(remotefolder)
File "/usr/local/Cellar/offline-imap/6.5.5/libexec/offlineimap/accounts.py", line 269, in get_local_folder
replace(self.remoterepos.getsep(), self.localrepos.getsep()))
File "/usr/local/Cellar/offline-imap/6.5.5/libexec/offlineimap/repository/Maildir.py", line 134, in getfolder
OfflineImapError.ERROR.FOLDER)
My .offlineimaprc is:
[general]
accounts = gloriphobia
ui = TTYUI
pythonfile=~/Development/MuttMailPython/offline.py
fsync = False
[Account gloriphobia]
localrepository = gloriphobia_local
remoterepository = gloriphobia_remote
status_backend = sqlite
postsynchook = notmuch new
[Repository gloriphobia_local]
type = Maildir
localfolders = ~/.mail/Test
nametrans = get_remote_name
[Repository gloriphobia_remote]
maxconnections = 1
type = Gmail
cert_fingerprint = 89091347184d41768bfc0da9fad94bfe882dd358
remoteuser = myemailaddress
remotepasseval = get_keychain_pass(account="myemailaddress",server="imap.gmail.com")
realdelete = no
nametrans = get_local_name
folderfilter = is_included
My python file, the one that is called offline.py is:
#!/usr/bin/python
import subprocess
import re
class NameMapping:
def __init__(self, local_name, remote_name):
self.local_name = local_name
self.remote_name = remote_name
class LocalName:
def __init__(self, folder):
self.folder = folder
def matches(self, mapping):
return mapping.remote_name == self.folder
def mapped_folder_name(self, mapping):
return mapping.local_name
class RemoteName:
def __init__(self, folder):
self.folder = folder
def matches(self, mapping):
return mapping.local_name == self.folder
def mapped_folder_name(self, mapping):
return mapping.remote_name
def get_keychain_pass(account=None, server=None):
params = {
'security': '/usr/bin/security',
'command': 'find-internet-password',
'account': account,
'server': server,
'keychain': '/Users/mec07/Library/Keychains/login.keychain',
}
command = "sudo -u mec07 %(security)s -v %(command)s -g -a %(account)s -s %(server)s %(keychain)s" % params
output = subprocess.check_output(command, shell=True, stderr=subprocess.STDOUT)
outtext = [l for l in output.splitlines()
if l.startswith('password: ')][0]
return re.match(r'password: "(.*)"', outtext).group(1)
def is_included(folder):
result = True
for pattern in exclusion_patterns:
result = result and (re.search(pattern, folder) == None)
return result
exclusion_patterns = [
"efax",
"earth_class_mail",
"eventbrite",
"gotomeeting",
"moshi_monsters",
"peepcode",
"raini_fowl",
"stuart_know",
"training.*2008",
"training.*2009",
"training.*2010",
"training.*2011",
"training.*2012",
"training.*nbdn",
"training.*nothin_but_bdd",
"unblock_us",
"web_hosting",
"webinars",
"Gmail.*Important"
]
name_mappings = [
NameMapping('inbox', '[Gmail]/Inbox'),
NameMapping('starred', '[Gmail]/Starred'),
NameMapping('important', '[Gmail]/Important'),
NameMapping('sent', '[Gmail]/Sent Mail'),
NameMapping('drafts', '[Gmail]/Drafts'),
NameMapping('archive', '[Gmail]/All Mail'),
NameMapping('spam', '[Gmail]/Spam'),
NameMapping('flagged', '[Gmail]/Starred'),
NameMapping('trash', '[Gmail]/Trash'),
NameMapping('deleted', '[Gmail]/Deleted Items'),
NameMapping('Mum', '[Gmail]/Jana'),
NameMapping('Maggie', '[Gmail]/Maggie'),
NameMapping('papers', '[Gmail]/Scholar Alert'),
NameMapping('sent items', '[Gmail]/Sent Items'),
NameMapping('sent messages', '[Gmail]/Sent Messages')
]
def find_name_mapping(name):
default_mapping = NameMapping(name.folder, name.folder)
for mapping in name_mappings:
if (name.matches(mapping)):
return mapping
return default_mapping
def get_name_mapping(name):
mapping = find_name_mapping(name)
return name.mapped_folder_name(mapping)
def get_remote_name(local_folder_name):
name = RemoteName(local_folder_name)
return get_name_mapping(name)
def get_local_name(remote_folder_name):
name = LocalName(remote_folder_name)
return get_name_mapping(name)
Thanks in advance for your help!
Add:
folderfilter = lambda folder: folder not in ['Drafts,]