gpt4 book ai didi

python - 如何从Deno运行Python脚本?

转载 作者:行者123 更新时间:2023-12-03 16:09:06 25 4
gpt4 key购买 nike

我有一个带有以下代码的python脚本:

print("Hello Deno")

我想使用Deno从test.ts运行此python脚本(test.py)。到目前为止,这是test.ts中的代码:
const cmd = Deno.run({cmd: ["python3", "test.py"]});

如何获得Deno中python脚本的输出?

最佳答案

Deno.run返回 Deno.Process 的实例。为了获得输出,请使用.output()。如果您想阅读内容,请不要忘记传递stdout/stderr选项。

// --allow-run
const cmd = Deno.run({
cmd: ["python3", "test.py"],
stdout: "piped",
stderr: "piped"
});

const output = await cmd.output() // "piped" must be set
const outStr = new TextDecoder().decode(output);

const error = await p.stderrOutput();
const errorStr = new TextDecoder().decode(error);

cmd.close(); // Don't forget to close it

console.log(outStr, errorStr);

如果不传递 stdout属性,则将输出直接发送到 stdout
 const p = Deno.run({
cmd: ["python3", "test.py"]
});

await p.status();
// output to stdout "Hello Deno"
// calling p.output() will result in an Error
p.close()

您也可以将输出发送到文件
// --allow-run --allow-read --allow-write
const filepath = "/tmp/output";
const file = await Deno.open(filepath, {
create: true,
write: true
});

const p = Deno.run({
cmd: ["python3", "test.py"],
stdout: file.rid,
stderr: file.rid // you can use different file for stderr
});

await p.status();
p.close();
file.close();

const fileContents = await Deno.readFile(filepath);
const text = new TextDecoder().decode(fileContents);

console.log(text)

为了检查进程的状态码,您需要使用 .status()
const status = await cmd.status()
// { success: true, code: 0, signal: undefined }
// { success: false, code: number, signal: number }

如果您需要将数据写入 stdin,可以这样做:
const p = Deno.run({
cmd: ["python", "-c", "import sys; assert 'foo' == sys.stdin.read();"],
stdin: "piped",
});


// send other value for different status code
const msg = new TextEncoder().encode("foo");
const n = await p.stdin.write(msg);

p.stdin.close()

const status = await p.status();

p.close()
console.log(status)

您需要使用以下命令运行Deno: --allow-run标志才能使用 Deno.run

关于python - 如何从Deno运行Python脚本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61710787/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com