web
You’re offline. This is a read only version of the page.
close
Skip to main content

Announcements

News and Announcements icon
Community site session details

Community site session details

Session Id :
Power Platform Community / Forums / Power Automate / How to give python mod...
Power Automate
Unanswered

How to give python module path in Run Python Script Action in PAD?

(0) ShareShare
ReportReport
Posted on by 357

Hi Team ,

I want to run the Python script in PAD, 

I am passing the module path in script sys.path.appent("C:\Users\sanket.shinde\Documents\@JsonExtraction\@JsonData\Python_Modules\JsonModule")

Still I am getting error that No module Json


Sanket1_0-1719500450769.pngSanket1_1-1719500465505.png

 

I have the same question (0)
  • NathanAlvares24 Profile Picture
    1,714 Moderator on at

    Hi @Sanket1 !

     

    Alternate solution:

    You can run the python code using PowerShell. All you have to do is save the py file and js file (since you are using json) and run the powershell script to execute that py script.

     

    Here is an example. You can try it out:

    NathanAlvares24_0-1719502205922.png

     

    My py file:

    NathanAlvares24_1-1719502302253.png

    PY Code (testing.py):

     

    import json
    
    def main():
     # Path to the JSON file
     json_file_path = 'C:/Users/Nathan/Desktop/data.json'
     
     # Read the JSON file
     with open(json_file_path, 'r') as file:
     data = json.load(file)
     
     # Print the original JSON data
     print("Original JSON data:")
     print(json.dumps(data, indent=4))
     
     # Modify the JSON data (e.g., add a new key-value pair)
     data['name'] = 'Nathan'
     
     # Print the modified JSON data
     print("\nModified JSON data:")
     print(json.dumps(data, indent=4))
     
     # Write the modified JSON data back to the file
     with open(json_file_path, 'w') as file:
     json.dump(data, file, indent=4)
     
     print("\nJSON file has been updated.")
    
    if __name__ == "__main__":
     main()

     

     

    My JSon file:

    NathanAlvares24_2-1719502378955.png

     

    JSON code (data.json):

     

    {
     "name": "John",
     "age": 30,
     "city": "New York"
    }

     

     

    The aim of the py code is to get a key value (name) from json and replace it with a string. Here I am replacing John with Nathan.

     

    Before:

    NathanAlvares24_2-1719502378955.png

     

    After:

    NathanAlvares24_3-1719502484180.png

     

    NathanAlvares24_4-1719502508710.png

     

    Then run the py script given below:

     

    NOTE: To get the python.exe, follow these steps:

    - Press Win + R, type cmd, and press Enter.

     

    - Type where python and press Enter.

     

    - Then copy the full path (if many, choose the topmost one as that is the latest version of your python on your system).

     

    Code:

     

    @@copilotGeneratedAction: 'False'
    Scripting.RunPowershellScript.RunPowershellScript Script: $'''# run_python_script.ps1
    
    # Path to the Python executable
    $pythonPath = \"C:\\Python312\\python.exe\" # Change this to the path of your Python executable
    
    # Path to the Python script
    $scriptPath = \"C:\\Users\\UserName\\Desktop\\testing.py\" # Change this to the path of your Python script
    
    # Execute the Python script
    & $pythonPath $scriptPath''' ScriptOutput=> PowershellOutput ScriptError=> ScriptError

     

     

    I hope this helps.

  • Sanket1 Profile Picture
    357 on at

    I have number of json files and I want to extract each json file data so  I have use for each then passing json file path in python script

    then how I can run the such scenario using power shell to run python script

  • Deenuji_Loganathan_ Profile Picture
    6,250 Moderator on at

    @Sanket1 

     

    Could you please explain full job of your python with some example and screenshot?

     


    Thanks,
    Deenuji Loganathan 👩‍💻
    Automation Evangelist 🤖
    Follow me on LinkedIn 👥

    -------------------------------------------------------------------------------------------------------------
    If I've helped solve your query, kindly mark my response as the solution ✔ and give it a thumbs up!👍 Your feedback supports future seekers 🚀

  • Sanket1 Profile Picture
    357 on at

    I have number of Json files and I have stored it in local.

    now I want to extract the data from json file. 


    I have used power automate to extract the data from json its took 4 hrs to get complete one json file which ha 30k line of data .

     

    By using python script its extract the data from json file within 11 sec. for 30k line of json.


    Thats why I am going with pyton script...

    Now I have python script but it contains some modules such as json, Docx module 

    so I am not able to run this script in Power automate desktop using Run Python Script Action deu to module

    I have downloaded those modules and keep it in one of folder and now I am passing module path but it still gives error that no module 'Json'


  • NathanAlvares24 Profile Picture
    1,714 Moderator on at

    Hi @Sanket1 !

     

    What is the function of your python script? Is it like extract from json file and then input it into your doc file?

     

    If not, please share your python script and your expected output you want. If you can provide a part of your json, it will be helpful.

     

    Also explain in detail the process.

  • Sanket1 Profile Picture
    357 on at

    this is py python script

    import json
    import os
    from docx import Document
    from docx.shared import Pt
    from docx.enum.text import WD_ALIGN_PARAGRAPH
    from docx.enum.table import WD_TABLE_ALIGNMENT

    def set_margins(section😞
        # Set page margins to Narrow (0.5 inches)
        section.left_margin = Pt(36)  # 0.5 inch
        section.right_margin = Pt(36)  # 0.5 inch
        section.top_margin = Pt(36)  # 0.5 inch
        section.bottom_margin = Pt(36)  # 0.5 inch

    def add_tables_to_word(data, output_file😞
        document = Document()

        # Set page margins
        section = document.sections[0]  # Get the first section
        set_margins(section)

        try:
            # Add LNB headings
            for key, value in data.items():
                if 'LNB_heading' in value:
                    lnb_headings = value['LNB_heading']
                    for heading in lnb_headings:
                        p = document.add_paragraph(heading)
                        p.alignment = WD_ALIGN_PARAGRAPH.CENTER
                        p.style.font.size = Pt(14)
                        p.style.font.bold = True  # Assuming headings are bold as per usual document formatting
                    break  # Only add headings from the first section

            # Add tables
            for section_name, section_data in data.items():
                if 'LNB_heading' in section_data:
                    continue  # Skip LNB heading section for tables

                document.add_paragraph(section_name, style='Heading 1')
                document.add_paragraph()

                for table_name, table_info in section_data.items():
                    if table_name == 'Exp_info':
                        # Handle Exp_info table separately for stretching
                        headers = table_info['headers']
                        rows = table_info['rows']

                        # Add table name
                        document.add_paragraph(table_name, style='Heading 2')
                        document.add_paragraph()

                        # Create table with correct number of columns
                        num_cols = len(headers)
                        table = document.add_table(rows=1, cols=num_cols)
                        table.style = 'Table Grid'
                        table.alignment = WD_TABLE_ALIGNMENT.CENTER

                        # Add headers and calculate column widths based on header length
                        hdr_cells = table.rows[0].cells
                        for idx, header in enumerate(headers):
                            hdr_cells[idx].text = header
                            hdr_cells[idx].paragraphs[0].runs[0].font.size = Pt(10)  # Set font size to 10pt
                            hdr_cells[idx].paragraphs[0].runs[0].font.bold = False  # Ensure headers are not bold

                            # Calculate width based on header length
                            max_header_width = max(len(header), len(hdr_cells[idx].text))
                            table.columns[idx].width = Pt(max_header_width * 12)  # Adjust multiplier as needed

                        # Add rows
                        for row_data in rows:
                            if isinstance(row_data, dict😞
                                # If row_data is a dictionary, extract values in order of headers
                                if any(row_data.values()):  # Check if any value in row_data is non-empty
                                    row_cells = table.add_row().cells
                                    for idx, header in enumerate(headers):
                                        cell_value = str(row_data.get(header, ''))
                                        row_cells[idx].text = cell_value
                                        row_cells[idx].paragraphs[0].runs[0].font.bold = False  # Ensure cell text is not bold
                                        row_cells[idx].paragraphs[0].runs[0].font.size = Pt(10)  # Set font size to 10pt
                            elif isinstance(row_data, list😞
                                # If row_data is a list, assume it directly represents row values
                                if any(row_data):  # Check if any value in row_data is non-empty
                                    row_cells = table.add_row().cells
                                    for idx, value in enumerate(row_data):
                                        cell_value = str(value)
                                        row_cells[idx].text = cell_value
                                        row_cells[idx].paragraphs[0].runs[0].font.bold = False  # Ensure cell text is not bold
                                        row_cells[idx].paragraphs[0].runs[0].font.size = Pt(10)  # Set font size to 10pt
                            else:
                                # Handle unexpected data types gracefully
                                print(f"Unexpected data type encountered in '{table_name}'")

                        # Add paragraph to separate tables
                        document.add_paragraph()
                    else:
                        # For other tables, add them as usual
                        headers = table_info['headers']
                        rows = table_info['rows']

                        # Add table name
                        document.add_paragraph(table_name, style='Heading 2')
                        document.add_paragraph()

                        # Create table with correct number of columns
                        num_cols = len(headers)
                        table = document.add_table(rows=1, cols=num_cols)
                        table.style = 'Table Grid'
                        table.alignment = WD_TABLE_ALIGNMENT.CENTER

                        # Add headers
                        hdr_cells = table.rows[0].cells
                        for idx, header in enumerate(headers):
                            hdr_cells[idx].text = header
                            hdr_cells[idx].paragraphs[0].runs[0].font.size = Pt(10)  # Set font size to 10pt
                            hdr_cells[idx].paragraphs[0].runs[0].font.bold = False  # Ensure headers are not bold

                        # Add rows
                        for row_data in rows:
                            if isinstance(row_data, dict😞
                                # If row_data is a dictionary, extract values in order of headers
                                if any(row_data.values()):  # Check if any value in row_data is non-empty
                                    row_cells = table.add_row().cells
                                    for idx, header in enumerate(headers):
                                        cell_value = str(row_data.get(header, ''))
                                        row_cells[idx].text = cell_value
                                        row_cells[idx].paragraphs[0].runs[0].font.bold = False  # Ensure cell text is not bold
                                        row_cells[idx].paragraphs[0].runs[0].font.size = Pt(10)  # Set font size to 10pt
                            elif isinstance(row_data, list😞
                                # If row_data is a list, assume it directly represents row values
                                if any(row_data):  # Check if any value in row_data is non-empty
                                    row_cells = table.add_row().cells
                                    for idx, value in enumerate(row_data):
                                        cell_value = str(value)
                                        row_cells[idx].text = cell_value
                                        row_cells[idx].paragraphs[0].runs[0].font.bold = False  # Ensure cell text is not bold
                                        row_cells[idx].paragraphs[0].runs[0].font.size = Pt(10)  # Set font size to 10pt
                            else:
                                # Handle unexpected data types gracefully
                                print(f"Unexpected data type encountered in '{table_name}'")

                        # Add paragraph to separate tables
                        document.add_paragraph()

            # Save the single document in the specified output directory
            document.save(output_file)
            print(f"All tables and LNB headings added to the Word document '{output_file}' successfully.")

        except Exception as e:
            print(f"Error occurred while processing data: {e}")

    def process_json_files(input_directory, output_directory😞
        # Ensure the output directory exists
        if not os.path.exists(output_directory):
            os.makedirs(output_directory)

        # Iterate over each file in the input directory
        for filename in os.listdir(input_directory):
            if filename.endswith(".json"😞
                json_file_path = os.path.join(input_directory, filename)
                json_filename = filename.split('.')[0]
                output_file = os.path.join(output_directory, f"{json_filename}_output.docx")

                # Load JSON data from each file
                with open(json_file_path, 'r') as json_file:
                    data = json.load(json_file)

                # Add tables and LNB headings to a single Word document for each JSON file
                add_tables_to_word(data, output_file)

    # Example usage
    input_directory = r"C:\Users\sanket.shinde\Documents\JsonExtraction\JsonFiles"
    output_directory = r"C:\Users\sanket.shinde\Documents\JsonExtraction\JsonData\Word_Files"

    # Process all JSON files in the input directory
    process_json_files(input_directory, output_directory)

    I want to run this script in power automate desktop using Run Python script action.

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

Introducing the 2026 Season 1 community Super Users

Congratulations to our 2026 Super Users!

Kudos to our 2025 Community Spotlight Honorees

Congratulations to our 2025 community superstars!

Leaderboard > Power Automate

#1
Haque Profile Picture

Haque 589

#2
Valantis Profile Picture

Valantis 328

#3
David_MA Profile Picture

David_MA 284 Super User 2026 Season 1

Last 30 days Overall leaderboard