DeveloperBreeze

Python Programming Tutorials, Guides & Best Practices

Explore 50+ expertly crafted python tutorials, components, and code examples. Stay productive and build faster with proven implementation strategies and design patterns from DeveloperBreeze.

Promise-based Execution of Python Code with jsPython

Code January 26, 2024
javascript

Explanation:

  • The first callback (result => { ... }) handles the resolved value, printing out the result.
  • The second callback (error => { ... }) handles any rejected value (errors), printing out the error message.

Execute Python Code Using Skulpt

Code January 26, 2024
javascript python

// Configure Skulpt to handle output and file reading
Sk.configure({
    output: function (text) {
        // Capture output from Python code and log it to the console
        console.log(text);
    },
    read: function (filename) {
        // Simulate file reading; replace with actual logic if necessary
        if (filename === '<stdin>') {
            return 'print("Hello, Skulpt!")';
        } else {
            throw new Error('File not found: ' + filename);
        }
    },
});

// Define the Python code to execute
const pythonCode = `
print("Hello, Skulpt!")
print("This is Python code running in JavaScript.")
`;

// Execute the Python code using Skulpt
Sk.misceval
    .asyncToPromise(() => {
        return Sk.importMainWithBody('<stdin>', false, pythonCode, true);
    })
    .then(
        (module) => {
            console.log('Python code executed successfully.');
        },
        (error) => {
            console.error('Error running Python code:', error.toString());
        }
    );

Description: