March 31 - April 2, 2025, in Las Vegas, Nevada. Use code MSCUST for a $150 discount! Early bird discount ends December 31.
Register NowBe one of the first to start using Fabric Databases. View on-demand sessions with database experts and the Microsoft product team to learn just how easy it is to get started. Watch now
I found this scipts python from github and try to used with powerbi.
I pretty sure my problem is this line
print(tabulate(tabular_data=results, headers=keep, tablefmt=cmd_line.table_format))
don't know I to convert into a table
the script work in visual code.
Thx for your help
Solved! Go to Solution.
Hi, @SylvainN
You'll need to convert your script output to a tabular format that Power BI can use, and you can modify the script to save the results to a CSV file instead of printing it out. Power BI makes it easy to import CSV files for further analysis and visualization.
You can refer to the modified code:
import os
import logging
import pandas as pd
from argparse import ArgumentParser, RawTextHelpFormatter, Namespace
from falconpy import APIHarnessV2, APIError
from tabulate import tabulate
import csv
def consume_arguments() -> Namespace:
"""Consume any provided command line arguments."""
parser = ArgumentParser(description=__doc__, formatter_class=RawTextHelpFormatter)
parser.add_argument("-d", "--debug",
help="Enable API debugging",
action="store_true",
default=False
)
parser.add_argument("-m", "--mssp",
help="List groups in all child CIDs (MSSP parents only)",
action="store_true",
default=False
)
parser.add_argument("-c", "--child",
help="List groups in a specific child CID (MSSP parents only)",
default=None
)
parser.add_argument("-t", "--table_format",
help="Table format to use for tabular display",
default="simple"
)
req = parser.add_argument_group("Required arguments")
parsed = parser.parse_args()
return parsed
cmd_line = consume_arguments()
# Activate debugging if requested
if cmd_line.debug:
logging.basicConfig(level=logging.DEBUG)
# Create our base authentication dictionary (parent / child)
auth = {
"client_id": "my key",
"client_secret": "my secret key",
"debug": cmd_line.debug,
"pythonic": True
}
# If we are in MSSP mode, retrieve our child CID details
if cmd_line.mssp:
parent = APIHarnessV2(**auth)
cids = parent.command("getChildren", ids=parent.command("queryChildren").data)
elif cmd_line.child:
parent = APIHarnessV2(**auth)
try:
cid_name = parent.command("getChildren", ids=cmd_line.child)
except APIError as api_error:
# Throw an error if they provided us an invalid CID
raise SystemExit(api_error.message)
cids = [{"name": cid_name["name"]}]
else:
# If not, we'll just run this in our current tenant
cids = [{"name": "CrowdStrike"}]
# Do the needful for each CID in the list
for cid in cids:
print(f"\n{cid['name']} host groups")
if cmd_line.mssp:
# If we're a parent, add this child's CID to our authentication request
auth["member_cid"] = cid["child_cid"]
elif cmd_line.child:
auth["member_cid"] = cmd_line.child
# Demonstrating using the SDK interface as a context manager
# This will automatically discard the bearer token when exiting the context.
with APIHarnessV2(**auth) as sdk:
# Fields we want to display
keep = {"id": "ID", "name": "Name", "description": "Description"}
# Sometimes list comprehension is ridiculously cool...
results = [{k: v for k, v in d.items() if k in keep} for d in sdk.command("queryCombinedHostGroups")]
# Define the CSV file name
csv_file = f"{cid['name']}_host_groups.csv"
# Write results to CSV file
with open(csv_file, mode='w', newline='') as file:
writer = csv.DictWriter(file, fieldnames=keep.values())
writer.writeheader()
writer.writerows(results)
print(f"Results saved to {csv_file}")
Next, import the CSV file into Power BI. Open Power BI Desktop. Click "Get Data" and select "Text/CSV". Select your CSV file and click Open.
Preview the data, confirm that it is correct, and click "Load". Model and visualize data in Power BI. This way, the data generated by your Python script can be easily used in Power BI.
Alternatively, you can use the Python script connector to enter the code directly. On the home page of Power BI Desktop, click the Get Data button in the upper-left corner.
Select "More...": In the pop-up window, scroll down and select the "More..." option.
Make sure your Python scripts can run in Power BI. Because Power BI's Python script connector has some limitations (for example, it doesn't support interactive input), you'll want to make sure that your scripts are self-contained and don't require user interaction. Also make sure you have the correct Python environment configured in Power BI. You can set the installation path for Python in Power BI's options. You can check the following link:
Run Python scripts in Power BI Desktop - Power BI | Microsoft Learn
How to Get Your Question Answered Quickly
Best Regards
Yongkang Hua
If this post helps, then please consider Accept it as the solution to help the other members find it more quickly.
Hi, @SylvainN
You'll need to convert your script output to a tabular format that Power BI can use, and you can modify the script to save the results to a CSV file instead of printing it out. Power BI makes it easy to import CSV files for further analysis and visualization.
You can refer to the modified code:
import os
import logging
import pandas as pd
from argparse import ArgumentParser, RawTextHelpFormatter, Namespace
from falconpy import APIHarnessV2, APIError
from tabulate import tabulate
import csv
def consume_arguments() -> Namespace:
"""Consume any provided command line arguments."""
parser = ArgumentParser(description=__doc__, formatter_class=RawTextHelpFormatter)
parser.add_argument("-d", "--debug",
help="Enable API debugging",
action="store_true",
default=False
)
parser.add_argument("-m", "--mssp",
help="List groups in all child CIDs (MSSP parents only)",
action="store_true",
default=False
)
parser.add_argument("-c", "--child",
help="List groups in a specific child CID (MSSP parents only)",
default=None
)
parser.add_argument("-t", "--table_format",
help="Table format to use for tabular display",
default="simple"
)
req = parser.add_argument_group("Required arguments")
parsed = parser.parse_args()
return parsed
cmd_line = consume_arguments()
# Activate debugging if requested
if cmd_line.debug:
logging.basicConfig(level=logging.DEBUG)
# Create our base authentication dictionary (parent / child)
auth = {
"client_id": "my key",
"client_secret": "my secret key",
"debug": cmd_line.debug,
"pythonic": True
}
# If we are in MSSP mode, retrieve our child CID details
if cmd_line.mssp:
parent = APIHarnessV2(**auth)
cids = parent.command("getChildren", ids=parent.command("queryChildren").data)
elif cmd_line.child:
parent = APIHarnessV2(**auth)
try:
cid_name = parent.command("getChildren", ids=cmd_line.child)
except APIError as api_error:
# Throw an error if they provided us an invalid CID
raise SystemExit(api_error.message)
cids = [{"name": cid_name["name"]}]
else:
# If not, we'll just run this in our current tenant
cids = [{"name": "CrowdStrike"}]
# Do the needful for each CID in the list
for cid in cids:
print(f"\n{cid['name']} host groups")
if cmd_line.mssp:
# If we're a parent, add this child's CID to our authentication request
auth["member_cid"] = cid["child_cid"]
elif cmd_line.child:
auth["member_cid"] = cmd_line.child
# Demonstrating using the SDK interface as a context manager
# This will automatically discard the bearer token when exiting the context.
with APIHarnessV2(**auth) as sdk:
# Fields we want to display
keep = {"id": "ID", "name": "Name", "description": "Description"}
# Sometimes list comprehension is ridiculously cool...
results = [{k: v for k, v in d.items() if k in keep} for d in sdk.command("queryCombinedHostGroups")]
# Define the CSV file name
csv_file = f"{cid['name']}_host_groups.csv"
# Write results to CSV file
with open(csv_file, mode='w', newline='') as file:
writer = csv.DictWriter(file, fieldnames=keep.values())
writer.writeheader()
writer.writerows(results)
print(f"Results saved to {csv_file}")
Next, import the CSV file into Power BI. Open Power BI Desktop. Click "Get Data" and select "Text/CSV". Select your CSV file and click Open.
Preview the data, confirm that it is correct, and click "Load". Model and visualize data in Power BI. This way, the data generated by your Python script can be easily used in Power BI.
Alternatively, you can use the Python script connector to enter the code directly. On the home page of Power BI Desktop, click the Get Data button in the upper-left corner.
Select "More...": In the pop-up window, scroll down and select the "More..." option.
Make sure your Python scripts can run in Power BI. Because Power BI's Python script connector has some limitations (for example, it doesn't support interactive input), you'll want to make sure that your scripts are self-contained and don't require user interaction. Also make sure you have the correct Python environment configured in Power BI. You can set the installation path for Python in Power BI's options. You can check the following link:
Run Python scripts in Power BI Desktop - Power BI | Microsoft Learn
How to Get Your Question Answered Quickly
Best Regards
Yongkang Hua
If this post helps, then please consider Accept it as the solution to help the other members find it more quickly.
March 31 - April 2, 2025, in Las Vegas, Nevada. Use code MSCUST for a $150 discount!
Your insights matter. That’s why we created a quick survey to learn about your experience finding answers to technical questions.
Arun Ulag shares exciting details about the Microsoft Fabric Conference 2025, which will be held in Las Vegas, NV.
User | Count |
---|---|
123 | |
85 | |
85 | |
70 | |
51 |
User | Count |
---|---|
205 | |
157 | |
97 | |
79 | |
69 |