Getting error in running ExportReport Python code in ArcMap - python

i am unable to generate pdf report using ExportReport function of Arcgis 10.2. getting error of IOError: Could not open report template
tried different template files but still getting this error.
Template directory is correct. checked all the directory positions.
Code
import arcpy
mxd = arcpy.mapping.MapDocument(r"C:\Users\Abrar ahmad\Documents\ArcGIS\New_Rwp_Cencus(12-17-2014).mxd")
df = arcpy.mapping.ListDataFrames(mxd)[0]
for lyr in arcpy.mapping.ListLayers(mxd, "",df):
if lyr.name == "New_Districts_5_without_limit":
arcpy.mapping.ExportReport(lyr,r"C:\Users\Abrar ahmad\Documents\ArcGIS\test.rlf",r"C:\Users\Abrar ahmad\Documents\ArcGIS\ProjectReport2.pdf","USE_RLF")
del mxd
Complete Error Data:
Runtime error
Traceback (most recent call last):
File "", line 7, in
File "c:\program files (x86)\arcgis\desktop10.2\arcpy\arcpy\utils.py", line 181, in fn_
return fn(*args, **kw)
File "c:\program files (x86)\arcgis\desktop10.2\arcpy\arcpy\mapping.py", line 515, in ExportReport
return report_source._arc_object.ExportReport(*gp_fixargs((report_layout_file, output_file, dataset_option, report_title, starting_page_number, page_range, report_definition_query, extent, field_map), True))
IOError: Could not open report template

Execute your code inside try/except/finally and see if this gives some hint:
import arcpy
import sys
import traceback
mxd = arcpy.mapping.MapDocument(r"C:\Users\Abrar ahmad\Documents\ArcGIS\New_Rwp_Cencus(12-17-2014).mxd")
try:
df = arcpy.mapping.ListDataFrames(mxd)[0]
for lyr in arcpy.mapping.ListLayers(mxd, "",df):
if lyr.name == "New_Districts_5_without_limit":
arcpy.mapping.ExportReport(lyr,r"C:\Users\Abrar ahmad\Documents\ArcGIS\test.rlf",r"C:\Users\Abrar ahmad\Documents\ArcGIS\ProjectReport2.pdf","USE_RLF")
except arcpy.ExecuteError:
# Get the tool error messages
msgs = arcpy.GetMessages(2)
# Return tool error messages for use with a script tool
arcpy.AddError(msgs)
# Print tool error messages for use in Python/PythonWin
print msgs
except:
# Get the traceback object
tb = sys.exc_info()[2]
tbinfo = traceback.format_tb(tb)[0]
# Concatenate information together concerning the error into a message string
pymsg = "PYTHON ERRORS:\nTraceback info:\n" + tbinfo + "\nError Info:\n" + str(sys.exc_info()[1])
msgs = "ArcPy ERRORS:\n" + arcpy.GetMessages(2) + "\n"
# Return python error messages for use in script tool or Python Window
arcpy.AddError(pymsg)
arcpy.AddError(msgs)
# Print Python error messages for use in Python / Python Window
print pymsg + "\n"
print msgs
finally:
del mxd

Related

TypeError: 'type' object is not subscriptable, error when creating an trading bot with python

I am creating a trading bot. I have 2 files a settings.json file and a main.py file.
my settings.json file :
`{
"username": "51410030",
"password": "s5p3GI1zY",
"server": "Alpari-MT5-Demo",
"mt5Pathway": "C://Program Files/Alpari MT5/terminal64.exe",
"symbols": ["USDJPY.a"],
"timeframe": "M30"
}
and my main.py file :
import json
import os
import mt5_interface
import strategy
# Function to import settings from settings.json
def get_project_settings(importFilepath):
# Test the filepath to sure it exists
if os.path.exists(importFilepath):
# Open the file
f = open(importFilepath, "r")
# Get the information from file
project_settings = json.load(f)
# Close the file
f.close()
project_settings = list(project_settings)
# Return project settings to program
return project_settings
else:
return ImportError
# Main function
if __name__ == '__main__':
# Set up the import filepath
import_filepath = "C:/Users/james/PycharmProjects/how_to_build_a_metatrader5_trading_bot_expert_advisor/settings.json"
# Import project settings
project_settings = get_project_settings(import_filepath)
# Start MT5
mt5_interface.start_mt5(project_settings["username"], project_settings["password"], project_settings["server"],
project_settings["mt5Pathway"])
# Initialize symbols
mt5_interface.initialize_symbols(project_settings["symbols"])
# Select symbol to run strategy on
symbol_for_strategy = project_settings['symbols'][0]
# Start strategy one on selected symbol
strategy.strategy_one(symbol=symbol_for_strategy, timeframe=project_settings['timeframe'],
pip_size=project_settings['pip_size'])
my prblem is when i run my main.py file it gives me this error:
Traceback (most recent call last):
File "i:\Traiding Bot\code\main.py", line 32, in <module>
mt5_interface.start_mt5(project_settings["username"], project_settings["password"], project_settings["server"],
TypeError: 'type' object is not subscriptable
please help me.
I couldn't find a solution please help me.
There are a few issues with your code:
You're trying to access fields in a list. That's not possible, you should keep your list a dictionary if you want access its fields.
You're returning an ImportError, if you want to raise an error, use raise ImportError("Your error message"). Or if you want to catch the error, use a try: <your code> except: return None and then check if you're returning None or not.

Error converting MSG to pdf using pdftron - Python

I am trying to convert msg file to pdf using Convert.ToPdf(doc, filename).
The .docx to pdf conversion is done properly using this function, however, I am only getting an error while converting msg to pdf.
The 'print' option is also there in the context menu when I right click on the file.
This is the error I am getting:
PDFNet is running in demo mode.
Traceback (most recent call last): File "test.py", line 58, in
main() File "test.py", line 44, in main Convert.ToPdf(doc,
filename)
Exception: An error occurred while converting the file.
Detailed error: Exception: Message: Unable to find printer Conditional
expression: success Version : 8.1.0.30521 Platform : Windows
Architecture : AMD64 Filename : Convert.cpp Function :
trn::PDF::ToPdfPrinterManager::InitPrinter Linenumber : 776
printing to printer \trial_msg.msg AssocQueryString printto:
AssocQueryString print : "C:\Program Files\Microsoft
Office\Root\Office16\OUTLOOK.EXE" /p "" Created new PDFNet Mutex
WaitForSingleObject start WaitForSingleObject End printo:
/Local/Temp/pdftron/Trn-17236-1616513476-af5adf11-bd4d-4d40-beec-8f6aad996f18.xps
Using HKCU Return value for delete registry: 0 Return value for delete
registry: 0 Return value for release mutex: 0 Return value for close
mutex: 0 Error destructing ToPdfPrinterManager
The next release of PDFNet, 9.0, will use Outlook interop to do the MSG conversion, instead of the less reliable printto command line option.

Unable to pass location of input and output to an extenal command using User-Interface in python

I am completely new to python.
I am trying to pass the location of Input and output using User interface as shown in this particular discussion [1]:How to give the location of "Input" and "Output" for a python code using User Interface and run the code from UI itself?
But here, I am calling an external command and trying to run it from my python code by passing location of input and output as in the above mentioned case.
from tkinter import *
from tkinter import filedialog
import numpy as np
import gdal
gdal.UseExceptions()
import os
def your_code(input_file, intermediate_file, output_file):
cmd = "gpt F:\saikiran\myGraph.xml -Psource=input_file - Ptarget=intermediate_file"
os.system(cmd)
ds = gdal.Open(intermediate_file)
band = ds.GetRasterBand(1)
……………………………………………...
#gen_map_button.place(x=230, y=300)
gen_map_button.pack()
root.mainloop()
But I encountered with this error :
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\User\Anaconda3\lib\tkinter\__init__.py", line 1705, in __call__
return self.func(*args)
File "C:\Users\User\GUI-pywt.py", line 145, in gen_map
your_code(input_filename, intermediate_filename, output_filename)
File "C:\Users\User\GUI-pywt.py", line 15, in your_code
ds = gdal.Open(intermediate_file)
File "C:\Users\User\Anaconda3\lib\site-packages\osgeo\gdal.py", line 3251, in Open
return _gdal.Open(*args)
RuntimeError: F:/saikiran/ddd: No such file or directory
What mistake did i do ?
Your cmd is not correct.
Concatenate string with values
cmd = "gpt F:\saikiran\myGraph.xml -Psource=" + input_file + " - Ptarget=" + intermediate_file
or use string formatting
cmd = "gpt F:\saikiran\myGraph.xml -Psource={} - Ptarget={}".format(input_file, intermediate_file)
With Python 3.6 or 3.7 you can use f-string
cmd = f"gpt F:\saikiran\myGraph.xml -Psource={input_file} - Ptarget={intermediate_file}"
Current cmd
"gpt F:\saikiran\myGraph.xml -Psource=input_file - Ptarget=intermediate_file"
will create file with name literally
intermediate_file
not
F:/saikiran/ddd
and it can make problem in gdal.Open()

Python - variable not defined but I think it is

I am pulling images from the Internet Archive as a test of some python code and I am incorporating the requests module. My code is as follows: (note, not the entire code, just the relevant section)
image_results = []
image_hashes = []
session = requests.Session()
for image in image_list:
if txtUrl not in image:
continue
try:
self.rslBox.AppendText("[v] Downloading %s" % image + "\n")
self.rslBox.Refresh()
response = session.get(image)
except:
self.rslBox.AppendText("[!] Failed to download: %s" % image + "\n")
self.rslBox.Refresh()
# continue
if "image" in response.headers['content-type']:
sha1 = hashlib.sha1(response.content).hexadigest()
if sha1 not in image_hashes:
image_hashes.append(sha1)
image_path = "WayBackImages/%s-%s" % (sha1.image.split("/")[-1])
with open(image_path, "wb") as fd:
fd.write(response.content)
self.rslBox.AppendText("[*] Saved %s" % images + "\n")
self.rslBox.Refresh()
info = pyexifinfo.get_json(image_path)
info[0]['ImageHash'] = sha1
image_results.append(info[0])
image_results_json = json.dumps(image_results)
data_frame = pandas.read_json(image_results_json)
csv = data_frame.to_csv('results.csv')
self.rslBox.AppendText("[*] Finished writing CSV to results.csv" + '\n')
self.rslBox.Refresh()
return
When I run my code, I get the following message:
Traceback (most recent call last):
File "C:\eclipse-workspace\test\tabbedPage.py", line 136, in OnSearch
if "image" in response.headers['content-type']:
NameError: name 'response' is not defined
But response is defined in the try statement - or so I would think. It only complains on the if "image" section - why??
I am new to python and I am using python3.6 and pydev with Eclipse.
Thanks!
Something inside your try failed. Your except caught it handle the error but since there is no raise in it, it continues execution, but response is not set.
It's because you are declaring response in the try block. If the exception gets thrown then response is not declared.
A work around for this would be putting the code that relies on response being declared into that try block.

Python: error with file op operations

I am loop through json and writing to file and passing that to another funtion to upload using a curl command.
Here is the error message i am getting:
Traceback (most recent call last):
File "D:\python_ws\test.py", line 33, in <module>
main((sys.argv[1:]))
File "D:\python_ws\test.py", line 30, in main
upload_file_bams(out_file)
File "D:\python_ws\test.py", line 7, in upload_file
file = open(rel_file).read()
TypeError: coercing to Unicode: need string or buffer, file found
I tried different ways but seems like i am missing some basics here. any help is appreciated.
Here is the my code:
#!/usr/bin/env python
import urllib2,json,sys,requests,subprocess,os
def upload_file(rel_file):
url = "https://localhost:8080/artifactory/list/default.generic.local/ct/releases/"
user = "john.smith"
file = open(rel_file).read()
cmd = 'curl --verbose --user %s --upload-file %s %s' %(user,file,url)
print 'trying to execute %s' % cmd
x = subprocess.Popen('cmd', shell=True)
#subprocess.call('cmd', shell=True)
retval = x.wait()
def main(argv):
#environment
env = sys.argv[1]
rel_name=sys.argv[2]
consul_url=("http://localhost:9090") % (env)
list_services = "/v1/catalog/services"
services_url = consul_url+list_services
list_of_services = urllib2.urlopen(services_url).read()
each_service = json.loads(list_of_services)
#to remove keys with blank values
newdict = dict([(vkey,vdata) for vkey, vdata in each_service.iteritems() if(vdata) ])
try:
out_file = open(rel_name,"wb")
json.dump(newdict,out_file, indent=4)
finally:
out_file.close()
#uploading release json file to BAMS
upload_file(out_file)
if __name__ == "__main__":
main((sys.argv[1:]))
When you call upload_file(), you pass it out_file which is of type file instead of string (file name). The function open() takes for the first argument the file name that you want to open.

Categories

Resources