Pywin32 update word document via scheduler - python

I have some simple code which opens a word document, updates the fields in it, then closes it. This code works correctly when I manually run it, however when I run it via the SQL Server Agent, I get an error. The user that SQL Server Agent runs with is the same user I am logged in with when running manually. I know the agent can 'see' the document because earlier code used in the task actually creates this document.
Code:
import win32com.client
word = win32com.client.DispatchEx("Word.Application")
filePath = "\\\\network\\data\\file.docx"
doc = word.Documents.Open(filePath)
doc.TablesOfContents(1).Update()
doc.Close(SaveChanges=True)
word.Quit()
Error:
Executed as user: DOMAIN\User. Traceback (most recent call last):
File "\\network\data\file.docx", line 8, in
doc.TablesOfContents(1).Update() AttributeError: 'NoneType' object
has no attribute 'TablesOfContents'
Why might this behavior happen?

For anyone in the future that might get this issue, I fixed it like this:
Open dcomcnfg Navigate to Component Services>Computers>My
Computer>DCOM Config>Microsoft Word 97-2003 Document
Right-click, click Properties
Select the Identity Tab
Select 'The Interactive User'

Related

Pyhton USGS EarthExplorer API not Working

I am trying to write a pyhton script that I would have my login credientals to log into USGS earth explorer and use their API to search for images in a dataset and give me the results, I am not sure what I want to do with the results but I am having trouble even searching for anything using the api.
Here is the code I have:
from usgs import api
#USGS EarthExplorer username and password
username = ''
password = ''
# Connect to the USGS EarthExplorer API using username and password
# This will prompt you to enter your credentials if you haven't set them up already
api.login(username, password)
# Search for Landsat 8 images within a specific date range and location
# In this example, we are searching for images over Washington, D.C. from January 1, 2022 to February 1, 2022
result = api.search(dataset='LANDSAT_8_C1',
node='EE',
latitude=38.9072,
longitude=-77.0369,
start_date='2022-01-01',
end_date='2022-02-01')
# Print the result to see the available images
print(result)
As a note I have removed my login so that is not the issue. When I go to run this code I get the following error:
Traceback (most recent call last):
File "c:\Users\edwar\OneDrive\Research\MyCode\connect.py", line 13, in <module>
result = api.search(dataset='LANDSAT_8_C1',
^^^^^^^^^^
AttributeError: module 'usgs.api' has no attribute 'search'
I have looked up this error and read through the documentation however maybe I am missing something that someone can point out for me? I also have an API key is there something I need to do with that or is the login credientials enough?
I have gotten my idea to use api.search from here . This documentation does the same thing I have it is just formatted differently but the methods are the same.

Spotipy - Bad Request following doc example

Following the docs here for Auth Code Flow, I can't seem to get the example to work.
import apis
import spotipy
import spotipy.util as util
username = input("Enter username: ")
scope = "user-library-read"
token = util.prompt_for_user_token(username, scope,
client_id=apis.SPOTIFY_CLIENT,
client_secret=apis.SPOTIFY_SECRET,
redirect_uri="http://localhost")
if token:
sp = spotipy.Spotify(auth=token)
results = sp.current_user_saved_tracks()
for item in results['items']:
track = item['track']
print(track['name'] + ' - ' + track['artists'][0]['name'])
else:
print("Can't get token for", username)
I get a 400 Bad Request error:
Traceback (most recent call last):
File "/home/termozour/.local/share/JetBrains/Toolbox/apps/PyCharm-P/ch-0/193.6494.30/plugins/python/helpers/pydev/pydevd.py", line 1434, in _exec
pydev_imports.execfile(file, globals, locals) # execute the script
File "/home/termozour/.local/share/JetBrains/Toolbox/apps/PyCharm-P/ch-0/193.6494.30/plugins/python/helpers/pydev/_pydev_imps/_pydev_execfile.py", line 18, in execfile
exec(compile(contents+"\n", file, 'exec'), glob, loc)
File "/media/termozour/linux_main/PycharmProjects/SpotiDowner/main.py", line 27, in <module>
sp = spotipy.Spotify(auth=token)
File "/media/termozour/linux_main/PycharmProjects/SpotiDowner/venv/lib/python3.7/site-packages/spotipy/util.py", line 92, in prompt_for_user_token
token = sp_oauth.get_access_token(code, as_dict=False)
File "/media/termozour/linux_main/PycharmProjects/SpotiDowner/venv/lib/python3.7/site-packages/spotipy/oauth2.py", line 382, in get_access_token
raise SpotifyOauthError(response.reason)
spotipy.oauth2.SpotifyOauthError: Bad Request
Yes, I've seen the other ideas people had to fix this issue but none worked for me:
I tried to reset the client secret, change my URI to a website or localhost, check my client ID and secret ID, and they are all fine.
What I also tried was to go all the way to spotipy/oauth2.py where I get the traceback, added a neat little print(response.text) and got a marvelous {"error":"invalid_grant","error_description":"Invalid authorization code"}
Any ideas or insight?
I have to specify that I ran this code from PyCharm Professional(2019.3.3) and the issue came up from a trailing space.
When the code is run, spotipy asks for that confirmation URL you get with the code based on the redirect URI you set in the app and the code.
The issue was how PyCharm handles URLs in it's terminal window when you run the project. When you put a URL in, and you press enter, PyCharm opens the URL in the browser (for some reason) so the workaround for that is to add a space after the URL and then press enter. That works for PyCharm, but sometimes screws up the code. In this case, it did.
I tried to run the code from PyCharm terminal (python3 ), pasted the URL and directly pressed enter. Not only it didn't open the browser window, it also accepted the URL and let me get my info from Spotify.
In any case, the code is fine, it was the IDE that was breaking it all - maybe a good suggestion would be to remove trailing spaces after the url, if any when parsed from the library itself.
This 'bug' has been reported here and has been marked as fixed (spoiler alert: not fixed) and will be fixed in PyCharm 2020.1
I tried running the code normally from PyCharm 2020.1 and it all works fine, so I can confirm: in my case it was an IDE issue.

PyGoogleVoice API Raises TypeError when trying to login

I am trying to mess with the pygooglevoice api and am trying to run the example call program on the documentation website:
from googlevoice import Voice
from googlevoice.util import input
voice = Voice()
voice.login()
outgoingNumber = input('Number to call: ')
forwardingNumber = input('Number to call from [optional]: ') or None
voice.call(outgoingNumber, forwardingNumber)
if input('Calling now... cancel?[y/N] ').lower() == 'y':
voice.cancel(outgoingNumber, forwardingNumber)
I then get the following error when voice.login() tries to execute:
File "C:\Users\<USER>\AppData\Local\Programs\Python\Python35\lib\configparser.py", line 406, in _interpolate_some
rawval = parser.get(section, option, raw=True, fallback=rest)
TypeError: get() got an unexpected keyword argument 'raw'
I am currently using Python 3.5 on a Windows 10 machine. I am also 90% sure I configured my .gvoice file properly in my user home directory. I have the email, password, and forwardingnumber all written out in that file.
Has anyone else had this issue? Am I using a deprecated API?
I found a more recent version of the library here: https://github.com/pettazz/pygooglevoice
This did fix my configparser error but I am now encountering another problem of a different nature. However my primary problem is fixed.

Application ID error with GAE remote API

I am trying to use the Remote API in a local Client, following instructions given in Google documentation (https://developers.google.com/appengine/docs/python/tools/remoteapi).
I first tried from the Remote API shell, and everything is working fine. I can connect to my remote datastore and fetch data.
But when I run the following script, which is very similar to Google's example :
#!/opt/local/bin/python2.7
import sys
SDK_PATH = "/usr/local/google_appengine/"
sys.path.append(SDK_PATH)
import dev_appserver
dev_appserver.fix_sys_path()
from google.appengine.ext.remote_api import remote_api_stub
import model.account
def auth_func():
return ('myaccount', 'mypasswd')
remote_api_stub.ConfigureRemoteApi('myappid', '/_ah/remote_api', auth_func)
# Fetch some data
entries = model.account.list()
for a in entries:
print a.name
then I get an error :
Traceback (most recent call last):
File "./remote_script_test.py", line 26, in <module>
entries = model.account.list()
[...]
File "/Developer/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/datastore/datastore_rpc.py", line 1333, in check_rpc_success
raise _ToDatastoreError(err)
google.appengine.api.datastore_errors.BadRequestError: Application Id (app) format is invalid: '_'
It says my application ID is a plain underscore '_', which is not the case since my app.yaml is correctly configured and when I do a
print app_identity.get_application_id()
from that script I get the correct application ID. I am under the impression that the GAE environment is not properly setup, but I could not figure out how to make it work. Does anyone have a full piece of code that works in this context ?
I am using Mac Os X Mountain Lion.
You may wish to start with remote_api_shell.py and remove stuff until it breaks, rather than add in things until it works.
For instance there's a line after the one you copied: remote_api_stub.MaybeInvokeAuthentication() is that necessary? There may be a number of necessary lines in remote_api_shell.py, maybe better to customize that rather than start from scratch.

Type error writing to file in Python

I am writing a Python script to notify me when changes are made to a webpage and store the current state of the page to a file in order to resume seamlessly after rebooting.
The code is as follows:
import urllib
url="http://example.com"
filepath="/path/to/file.txt"
try:
html=open(filepath,"r").read() # Restores imported code from previous session
except:
html="" # Blanks variable on first run of the script
while True:
imported=urllib.urlopen(url)
if imported!=html:
# Alert me
html=imported
open(filepath,"w").write(html)
# Time delay before next iteration
Running the script returns:
Traceback (most recent call last):
File "April_Fools.py", line 20, in <module>
open(filepath,"w").write(html)
TypeError: expected a character buffer object
------------------
(program exited with code: 1)
Press return to continue
I've no idea what this means. I'm relatively new to Python. Any help would be much appreciated.
urllib.urlopen does not return a string, it returns a response as a file-like object. You need to read that response:
html = imported.read()
Only then is html a string you can write to a file.
As an aside, using open(filename).read() is not considered good style, because you never close the file. The same goes for writing. Try using a context manager instead:
try:
with open(filepath,"r") as htmlfile:
html = htmlfile.read()
except:
html=""
The with block will automatically close the file when you leave the block.

Categories