如何从咖啡脚本执行Python代码并获取输出

发布于 2025-01-11 18:37:04 字数 840 浏览 3 评论 0原文

我正在开发一个 CoffeeScript,它需要执行一个 Python 程序并从 Python 代码中获取响应。 我的咖啡脚本是

module.exports = (robot) ->
    robot.respond /greetme/i, (msg) ->
        sender = msg.message.user.name.toLowerCase()
        @exec = require('child_process').exec
        command = "python3 ext-scripts/hello.py"
        @exec command, (out1) ->
            msg.send out1
        msg.send "Hello " + sender
        msg.finish()

,我的 python 代码是 hello.py

print("hey indhu")
return "reached the python file"

我需要将输出“到达 python 文件”获取到咖啡脚本中的第 6 行。发送消息时,

我在执行此 exec out 函数时遇到错误。

消息:错误:命令失败:python3 ext-scripts/hello.py 文件“ext-scripts/hello.py”,第 28 行 return“到达python文件” ^ 语法错误:“返回”外部函数

错误:响应不正常:no_text

如何使其工作?我是一名 Python 开发人员,也是 CoffeeScript 的新手。

I am developing a CoffeeScript which needs to execute a Python program and get the responses from the Python code.
My coffee script is

module.exports = (robot) ->
    robot.respond /greetme/i, (msg) ->
        sender = msg.message.user.name.toLowerCase()
        @exec = require('child_process').exec
        command = "python3 ext-scripts/hello.py"
        @exec command, (out1) ->
            msg.send out1
        msg.send "Hello " + sender
        msg.finish()

and my python code is hello.py

print("hey indhu")
return "reached the python file"

I need to get the output "reached the python file" to 6th line in coffee script. to send out the message

I am getting error while doing this exec out function.

message: Error: Command failed: python3 ext-scripts/hello.py File "ext-scripts/hello.py", line 28
return "reached the python file"
^ SyntaxError: 'return' outside function

error: Response not OK: no_text

How to make it work? I am a Python developer and new to CoffeeScript.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

煮茶煮酒煮时光 2025-01-18 18:37:04

最简单的方法是使用读取输出和过滤器的抑制器。第一个版本适用于 Windows 计算机,第二个版本适用于 Linux 系统。

import subprocess

process = subprocess.Popen(['echo', 'More output'],
                     stdout=subprocess.PIPE, 
                     stderr=subprocess.PIPE)
stdout, stderr = process.communicate()
stdout, stderr

或者

import os

cmd = 'your command here'
terminal_output = os.system(cmd)

print(terminal_output)

The easiest way is with a supprecess that reads the output and filters. The first version is good for Windows machines, the second for Linux systems.

import subprocess

process = subprocess.Popen(['echo', 'More output'],
                     stdout=subprocess.PIPE, 
                     stderr=subprocess.PIPE)
stdout, stderr = process.communicate()
stdout, stderr

OR

import os

cmd = 'your command here'
terminal_output = os.system(cmd)

print(terminal_output)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文