【问题标题】:How to run a Python Script from Deno?如何从 Deno 运行 Python 脚本?
【发布时间】:2020-05-10 23:30:14
【问题描述】:

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

print("Hello Deno")

我想使用 Deno 从 test.ts 运行这个 python 脚本 (test.py)。到目前为止,这是 test.ts 中的代码:

const cmd = Deno.run({cmd: ["python3", "test.py"]});

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

【问题讨论】:

    标签: python typescript deno


    【解决方案1】:

    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)
    

    您需要使用 --allow-run 标志运行 Deno 才能使用 Deno.run

    【讨论】:

    • 你不需要,除非你正在阅读像我的第二个例子这样的文件。
    • 这就像一个魅力!感谢您的惊人解释!我捡了很多。
    猜你喜欢
    • 2021-07-19
    • 1970-01-01
    • 2020-11-12
    • 1970-01-01
    • 2019-07-10
    • 2017-05-18
    • 1970-01-01
    相关资源
    最近更新 更多