乐闻世界logo
搜索文章和话题

How to run a Python Script from Deno?

1个答案

1

Step 1: Ensure Python is installed on your system

First, ensure that Python is installed on your system and accessible via the command line. You can verify its installation and version by running python --version or python3 --version.

Step 2: Write the Python script

Assume you have a simple Python script named script.py in the same directory, with the following content:

python
# script.py print("Hello from Python!")

Step 3: Write Deno code to run the Python script

Within a Deno script, you can use Deno.run to invoke the external Python interpreter and execute the script. Here is an example code snippet for Deno:

typescript
// deno_script.ts const runPythonScript = async () => { const process = Deno.run({ cmd: ["python", "script.py"], // or use "python3" depending on your system configuration stdout: "piped", stderr: "piped", }); const { code } = await process.status(); // Wait for the Python script to complete if (code === 0) { const rawOutput = await process.output(); const output = new TextDecoder().decode(rawOutput); console.log("Python Script Output:", output); } else { const rawError = await process.stderrOutput(); const errorString = new TextDecoder().decode(rawError); console.error("Python Script Error:", errorString); } Deno.exit(code); // Exit the Deno program, returning the same exit code as the Python script }; runPythonScript();

Step 4: Run the Deno script

Before running the Deno script, ensure that Deno has permission to run subprocesses. This can be achieved by using the --allow-run flag in the command line:

bash
deno run --allow-run deno_script.ts

This will launch the Deno script, which invokes the Python interpreter to execute script.py, and prints the output or errors to the console.

By using this method, you can conveniently run Python scripts within the Deno environment, which is useful for integrating tools and scripts written in different programming languages.

2024年7月20日 18:57 回复

你的答案