DeveloperBreeze

Code Integration Development Tutorials, Guides & Insights

Unlock 1+ expert-curated code integration tutorials, real-world code snippets, and modern dev strategies. From fundamentals to advanced topics, boost your code integration skills on DeveloperBreeze.

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: