How to explode block with pyautocad - python

I am importing a .dwg file to another AutoCAD file using pyautocad.
It shows the object as a block and now I have to explode it and I don't know how.
If anyone can help me with how I explode the block will be greatly appreciated.
from pyautocad import Autocad,APoint
acad = Autocad(create_if_not_exists = True)
p1 = APoint(0,0)
blockp = acad.model.InsertBlock(p1,"C:\S20 A.dwg",1,1,1,0)
print (blockp.name)

I found a solution to work around the 'KeyError:9'. I made an exception when using the command 'entity.Explode()' and after, loop through the blocks in ModelSpace to get the inserted block again. If somebody help me in how to correct the syntax to avoid this 'KeyError:9' will be appreciated.
import array
from comtypes import COMError
from comtypes.client import CreateObject,GetModule, GetActiveObject
try:
acad = GetActiveObject("AutoCAD.Application")
except(OSError, COMError):
acad = CreateObject("AutoCAD.Application",dynamic=True)
filename = r"C:\Test\CP20 IMPERIAL.dwt"
doc = acad.Documents.Open(filename)
files = r"C:\Test\Series 20\S20 A.dwg"
insertionPnt = array.array('d', [0,0,0])
blockI = doc.ModelSpace.InsertBlock(insertionPnt, files, 1, 1, 1, 0)
acad.visible = True
if blockI:
try:
eent = blockI.Explode()
print('Exploded')
except KeyError:
print("Explode with Error")
try:
ssBlocks = doc.SelectionSets.Add("AllBlockRefs")
except:
ssBlocks = doc.SelectionSets.Item("AllBlockRefs")
SELECT_ALL = 5
FilterType = array.array('h',[0])
FilterData = ['Insert']
ssBlocks.Select(SELECT_ALL,(0,0,0),(0,0,0),FilterType,FilterData)
icount = ssBlocks.Count
print(icount)
for entity in ssBlocks:
name = entity.Name
print(name)
if name == 'S20 A':
try:
entity.Explode()
print('Exploded')
except KeyError:
print("Explode with Error")
entity.Delete()
ssBlocks.Clear
ssBlocks.Delete
for entity in doc.ModelSpace:
name = entity.EntityName
if name == "AcDbBlockReference":
if entity.IsDynamicBlock:
print(entity.Name)
print("Is Dinamic Block")

Related

Conversion cloud module not found

Hello Stack Overflow friends!
I'm trying to use this conversion cloud module (https://github.com/groupdocs-conversion-cloud/groupdocs-conversion-cloud-python), but it's returning the module error: ModuleNotFoundError: No module named 'groupdocs_conversion_cloud'
I've installed the packaged through the terminal with no problem, even though the error keeps returning.
Here's my code:
import groupdocs_conversion_cloud
# Get your app_sid and app_key at https://dashboard.groupdocs.cloud (free registration is required).
app_sid = "3e9***ca"
app_key = "f0***ad407e1"
# Create instance of the API
convert_api = groupdocs_conversion_cloud.ConvertApi.from_keys(app_sid, app_key)
file_api = groupdocs_conversion_cloud.FileApi.from_keys(app_sid, app_key)
try:
#upload soruce file to storage
filename = 'FT_Manteiga virgem de cacau.pdf'
remote_name = 'FT_Manteiga virgem de cacau.pdf'
output_name= 'FT_Manteiga virgem de cacau.docx'
strformat='docx'
request_upload = groupdocs_conversion_cloud.UploadFileRequest(remote_name,filename)
response_upload = file_api.upload_file(request_upload)
#Convert PDF to Word document
settings = groupdocs_conversion_cloud.ConvertSettings()
settings.file_path =remote_name
settings.format = strformat
settings.output_path = output_name
loadOptions = groupdocs_conversion_cloud.PdfLoadOptions()
loadOptions.hide_pdf_annotations = True
loadOptions.remove_embedded_files = False
loadOptions.flatten_all_fields = True
settings.load_options = loadOptions
convertOptions = groupdocs_conversion_cloud.DocxConvertOptions()
convertOptions.from_page = 1
convertOptions.pages_count = 1
settings.convert_options = convertOptions
request = groupdocs_conversion_cloud.ConvertDocumentRequest(settings)
response = convert_api.convert_document(request)
print("Document converted successfully: " + str(response))
except groupdocs_conversion_cloud.ApiException as e:
print("Exception when calling get_supported_conversion_types: {0}".format(e.message))
I've installed this lib using pip install groupdocs_conversion_cloud

while creating ndvi.tif file using gdal module getting TIFFReadDirectory error

when I'm using same code in jupyter notebook. it doesn't throw error but when I'm using flask for creating an api for the task then it throw "TIFFReadDirectory: Warning, Unknown field with tag 42112 (0xa480) encountered.
Segmentation fault: 11 " this error.
for the reference I am adding the code snipped here:-
import osgeo.gdal as gdal
#app.route('/ndvi', methods =['POST'])
def cal_ndvi():
orthophoto_path = "path/of/my/odm_orthophoto.tif/file"
outfile = "NDVI_files"
if not os.path.exists(outfile):
logger.info("creating download_path............")
os.makedirs(outfile)
outfile = outfile + "/ndvi.tif"
print("start reading")
g = gdal.Open (orthophoto_path)
print("file read")
if g is None:
raise IOError("Couldn't open baikal_subset.tif")
b3 = g.GetRasterBand(3).ReadAsArray().astype(np.float32)
b4 = g.GetRasterBand(4).ReadAsArray().astype(np.float32)
ndvi = (b4 - b3)/(b4 + b3)
geoTransform = g.GetGeoTransform()
print("geoTransform: ",geoTransform)
geoProjection = g.GetProjection()
print("geoProjection: ",geoProjection)
drv = gdal.GetDriverByName ( "GTiff" )
dst_ds = drv.Create (outfile, g.RasterXSize, g.RasterYSize, 1,
gdal.GDT_Float32, options=["COMPRESS=LZW"])
dst_ds.GetRasterBand(1).WriteArray(ndvi)
dst_ds.SetGeoTransform(geoTransform)
dst_ds.SetProjection(geoProjection)
dst_ds = None
return "True"
please review the code and suggest the proper solution.

How to properly get table-row indexes and named values from trapped var-binds in pysnmp

I'm trying to keep my code as clean as possible but I'm not completely satisfied with what I achieved so far.
I built a SNMP manager which receive traps from another device using a custom MIB, which I will refer to as MY-MIB.
I am not sure this is the cleanest way, but essentially I have:
from pysnmp.entity import engine, config
from pysnmp.carrier.asynsock.dgram import udp
from pysnmp.entity.rfc3413 import ntfrcv, context
from pysnmp.smi import builder, rfc1902
from pysnmp.smi.view import MibViewController
from pysnmp.entity.rfc3413 import mibvar
_snmp_engine = engine.SnmpEngine()
_snmpContext = context.SnmpContext(_snmpEngine)
_mibBuilder = _snmpContext.getMibInstrum().getMibBuilder()
#Add local path where MY-MIB is located
_mibSources = _mibBuilder.getMibSources() + (builder.DirMibSource('.'),)
_mibBuilder.setMibSources(*mibSources)
_mibBuilder.loadModules('MY-MIB')
_view_controller = MibViewController(_mibBuilder)
def my_callback_trap_processor(snmp_engine, state_reference,
context_id, context_name, var_binds, ctx):
#...CALLBACK CODE...
config.addV1System(snmp_engine, 'my-area', 'MYCOMMUNITY')
config.addTargetParams(snmp_engine, 'my-creds', 'my-area',
'noAuthNoPriv', 1)
config.addSocketTransport(snmp_engine,
udp.domainName + (1,),
udp.UdpTransport().openServerMode((IP_ADDRESS,
PORT)))
ntfrcv.NotificationReceiver(snmp_engine, my_callback_trap_processor)
snmp_engine.transportDispatcher.jobStarted(1)
try:
snmp_engine.transportDispatcher.runDispatcher()
except:
snmp_engine.transportDispatcher.closeDispatcher()
raise
In the callback function above I can get a pretty intelligible print by just using the following code:
varBinds = [rfc1902.ObjectType(rfc1902.ObjectIdentity(x[0]), x[1]).resolveWithMib(_view_controller) for x in var_binds]
for varBind in varBinds:
print(varBind.prettyPrint())
which, from a given trap that I receive, gives me:
SNMPv2-MIB::sysUpTime.0 = 0
SNMPv2-MIB::snmpTrapOID.0 = MY-MIB::myNotificationType
MY-MIB::myReplyKey.47746."ABC" = 0x00000000000000000000000000000000000
MY-MIB::myTime.0 = 20171115131544Z
MY-MIB::myOperationMode.0 = 'standalone'
Nice. But I want to manipulate/dissect each bit of information from the given var-binds, especially in a higher level way.
Looking at the innards of the library I was able to gather this code up:
for varBind in var_binds:
objct = rfc1902.ObjectIdentity(varBind[0]).resolveWithMib(self._view_controller)
(symName, modName), indices = mibvar.oidToMibName(
self._view_controller, objct.getOid()
)
print(symName, modName, indices, varBind[1])
that gives me:
sysUpTime SNMPv2-MIB (Integer(0),) 0
snmpTrapOID SNMPv2-MIB (Integer(0),) 1.3.6.1.X.Y.Z.A.B.C.D
myReplyKey MY-MIB (myTimeStamp(47746), myName(b'X00080')) 0x00000000000000000000000000000000000
myTime MY-MIB (Integer(0),) 20171115131544Z
myOperationMode MY-MIB (Integer(0),) 1
and in the case of myReplyKey indexes I can just do a:
for idx in indices:
try:
print(idx.getValue())
except AttributeError:
print(int(idx))
But in the case of the myOperationMode var-bind, how do I get the named-value 'standalone' instead of 1? And how to get the names of the indexes (myTimeStamp and myName)?
Update:
After Ilya's suggestions I researched the library a little bit more for getting the namedValues and, also, I used some Python hacking to get what I was looking for on the indices.
varBinds = [rfc1902.ObjectType(rfc1902.ObjectIdentity(x[0]), x[1]).resolveWithMib(_view_controller) for x in var_binds]
processed_var_binds = []
for var_bind in resolved_var_binds:
object_identity, object_value = var_bind
mod_name, var_name, indices = object_identity.getMibSymbol()
var_bind_dict = {'mib': mod_name, 'name': var_name, 'indices': {}}
for idx in indices:
try:
value = idx.getValue()
except AttributeError:
var_bind_dict['indices'] = int(idx.prettyPrint())
else:
var_bind_dict['indices'][type(value).__name__] = str(value)
try:
var_bind_dict['value'] = object_value.namedValues[object_value]
except (AttributeError, KeyError):
try:
var_bind_dict['value'] = int(object_value.prettyPrint())
except ValueError:
var_bind_dict['value'] = object_value.prettyPrint()
processed_var_binds.append(var_bind_dict)
To resolve SNMP PDU var-bindings against a MIB you can use this snippet what I think you have done already:
from pysnmp.smi.rfc1902 import *
var_binds = [ObjectType(ObjectIdentity(x[0]), x[1]).resolveWithMib(mibViewController)
for x in var_binds]
By this point you have a list of rfc1902.ObjectType objects. The ObjectType instance mimics a two-element tuple: ObjectIdentity and SNMP value object.
var_bind = var_binds[0]
object_identity, object_value = var_bind
Now, getMibSymbol() will give you MIB name, MIB object name and the tuple of indices made up from the trailing part of the OID. Index elements are SNMP value objects just as object_value:
>>> object_identity.getMibSymbol()
('SNMPv2-MIB', 'sysDescr', (0,))
The enumeration, should it present, is reported by .prettyPrint():
>>> from pysnmp.proto.rfc1902 import *
>>> Error = Integer.withNamedValues(**{'disk-full': 1, 'no-disk': -1})
>>> error = Error(1)
>>> error.prettyPrint()
'disk-full'
>>> int(error)
1

add chartobject to excel via Python

so I have been trying to add a chart object to an Excel file using IronPython and I keep getting an error whenever I call ws.ChartObjects. For some reason it tells me that its a DispCallable and that it has no Add property.
clr.AddReferenceByName('Microsoft.Office.Interop.Excel, Version=11.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c')
from Microsoft.Office.Interop import Excel
System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo("en-US")
from System.Runtime.InteropServices import Marshal
def SetUp(xlApp):
# supress updates and warning pop ups
xlApp.Visible = False
xlApp.DisplayAlerts = False
xlApp.ScreenUpdating = False
return xlApp
def ExitExcel(filePath, xlApp, wb, ws):
# clean up before exiting excel, if any COM object remains
# unreleased then excel crashes on open following time
def CleanUp(_list):
if isinstance(_list, list):
for i in _list:
Marshal.ReleaseComObject(i)
else:
Marshal.ReleaseComObject(_list)
return None
wb.SaveAs(str(filePath))
xlApp.ActiveWorkbook.Close(False)
xlApp.ScreenUpdating = True
CleanUp([ws,wb,xlApp])
return None
def GetWidthHeight(origin, extent, ws):
left = ws.Cells(bb.xlRange(cellRange)[1], bb.xlRange(cellRange)[0]).Left
top = ws.Cells(bb.xlRange(cellRange)[1], bb.xlRange(cellRange)[0]).Top
width = ws.Range[origin, extent].Width
height = ws.Range[origin, extent].Height
return [left, top, width, height]
if runMe:
message = None
try:
xlApp = SetUp(Excel.ApplicationClass())
errorReport = None
xlApp.Workbooks.open(str(filePath))
wb = xlApp.ActiveWorkbook
ws = xlApp.Sheets(sheetName)
# i have no clue why ws.ChartObjects.Count throws an error all the time
origin = ws.Cells(bb.xlRange(cellRange)[1], bb.xlRange(cellRange)[0])
extent = ws.Cells(bb.xlRange(cellRange)[3], bb.xlRange(cellRange)[2])
left = GetWidthHeight(origin, extent, ws)[0]
top = GetWidthHeight(origin, extent, ws)[1]
width = GetWidthHeight(origin, extent, ws)[2]
height = GetWidthHeight(origin, extent, ws)[3]
xlChartObject = ws.ChartObjects.Add(int(left), int(top), int(width), int(height))
Marshal.ReleaseComObject(extent)
Marshal.ReleaseComObject(origin)
ExitExcel(filePath, xlApp, wb, ws)
except:
# if error accurs anywhere in the process catch it
import traceback
errorReport = traceback.format_exc()
My problem is with calling ws.ChartObjects.Add() which throws an exception 'DispCallable' object has no attribute 'Add'. How do i go around this? What is wrong?
Based on a similar issue indicating that ChartObjects is a function you should use
ChartObjects().Add(...)
As per official documentation, the arguments should be double. If this is not the issue, you can split
xlChartObject = ws.ChartObjects.Add(...
into
xlChartObjects = ws.ChartObjects
xlChartObject = xlChartObjects.Add(...
to start debugging. It is a good idea to:
Check available methods (for the class of xlChartObjects, e.g.) with How do I get list of methods in a Python class?, or Finding what methods an object has.
Check type with What's the canonical way to check for type in python?.
You will likely learn how to fix these lines.
PS: In the code you posted sheetName and bb are not defined, although you probably define them earlier.

Want to filter out failure Message from my robot framework output files

I want to filter failure messages from output files generated after executing my testcases in Robot Framework. I have tried modules like from robot.api import ExecutionResult but it gives me only only count of Passed and Failed Testcases.
I have also tried other Robot framework Libtraries like import robot.errors to filter out all error messages but didn't get any luck. Below is my code block:
`
#!/usr/bin/python
from robot.api import ExecutionResult
import robot.errors
from robot.result.visitor import ResultVisitor
xmlpath = "<output.xml PATH>"
result = ExecutionResult(xmlpath)
result.configure(stat_config={'suite_stat_level': 2,
'tag_stat_combine': 'tagANDanother'})
stats = result.statistics
print stats.total.critical.failed
print stats.total.critical.passed
print stats.total.critical.passed + stats.total.critical.failed
class FailureCollector(ResultVisitor):
def __init__(self):
self.failures = []
def visit_test(self, test):
if not test.passed:
self.failures += [test]
failure_collector = FailureCollector()
result.visit(failure_collector)
print failure_collector.failures
#the above print gives me all failed testcases as a list Eg: ['test1:My example Testcase1','test2:My example Testcase2' ]`
Any example to get this work done will be very helpful.
I have tried a lot to get my expected output by using Robot Framework APIs but didn't get proper solution. Finally I got my solution by using import xml.etree.ElementTree as ET module. By using xml.etree.ElementTree module I am parsing my robot result.xml file and getting my work done.
`
import xml.etree.ElementTree as ET
import re
tree = ET.parse('<output.xml file Path>')
root = tree.getroot()
testplans = <Testplans as a list>
i = 0
err_dict = {}
for testplan in testplans:
full_err_list = []
err_list = []
for suite_level_1 in root:
try:
if suite_level_1.tag == "suite":
for suite_level_2 in suite_level_1:
if suite_level_2.tag == "suite" and suite_level_2.attrib['name'] == testplan:
for suite_level_3 in suite_level_2:
if suite_level_3.tag == "suite":
for test in suite_level_3:
if test.tag == "test":
for kw_level_5 in test:
if kw_level_5.tag == "kw" and kw_level_5.attrib['name'] == '<specific keyword under which you expect your result(error or Success message >':
for msg in kw_level_5:
if msg.tag == 'msg':
err_str = msg.text
#print err_str
mat = re.match(r'\$\{FinalResult\}\s=\s(.*)',err_str)
if mat and mat.group(1) != 'Succeeded.':
i=i+1
#print mat.group(1), i
err = mat.group(1)
full_err_list.append(err)
if err not in err_list:
err_list.append(err)
except:
print "Errors found"
break
err_dict[testplan] = err_list
print "\n########## "+testplan+" ##########\n"
print "Total no of failures", len(full_err_list)
for err_name in err_list:
print err_name, "===>>", full_err_list.count(err_name)
##The above will print the error name and its count in specific testPlan`

Categories