简体   繁体   English

如何在不同的编程语言之间进行通信?

[英]How to communicate between different programming languages?

I have wrote an api for my python code like this: 我已经为我的python代码编写了一个api,如下所示:

def greet_in_python(name, greets="Hello"):
    ## in real life this implementation may be more complex and has other **python** dependencies
    ....
    return greets + " " + name

But only python developers can use my api. 但只有python开发人员可以使用我的api。

What i want to do is the same thing but with a different language, like javascript, and without rewriting the whole code from python. 我想做的是同一件事,但是使用不同的语言(例如javascript),而无需从python重写整个代码。 I thought there must be a way for javascript to communicate with this python api, execute it, and get the result so that javascript developers too can use my api. 我认为javascript必须有一种与该python api通信,执行它并获取结果的方法,以便javascript开发人员也可以使用我的api。

greet_in_javascript(name, greets) {
    // talk to my python api
    // return the result easily
}

In a general sense how two languages can talk to each other? 在一般意义上,两种语言如何互相交流?

There are two very popular ways to do this, and probably a million others that I will neglect in my answer. 有两种非常流行的方法可以做到这一点,我可能会忽略一百万种其他答案。

Pipes: 管道:

import sys

This is where your use sys.stdin and sys.stdout to read the inputs for your program with the help of your OS, then output the result. 在这里,您可以使用sys.stdinsys.stdout在OS的帮助下读取程序的输入,然后输出结果。 Both of these are file-like objects in Python so you are likely already familiar with how to use them. 这两个都是Python中类似文件的对象,因此您可能已经熟悉如何使用它们。 In js and node you have child processes and exec and so on which can do calls to your program eg cat file.txt | python myscript.py 在js和node中,您具有子进程和exec等,可以对程序进行调用,例如cat file.txt | python myscript.py cat file.txt | python myscript.py

APIs: 蜜蜂:

import flask, django

With this approach you can use frameworks like flask & django to define endpoints (eg example.com/api/my/endpoint ) which map to your API in a way that makes sense for your business purpose. 通过这种方法,您可以使用flaskdjango类的框架来定义端点(例如example.com/api/my/endpoint ),这些端点以对您的业务目的有意义的方式映射到您的API。 API design is too broad for me to delve into in this answer (but there are much better folks than I out in the internet who have written brilliantly about that topic.) API设计太宽泛,我无法深入研究这个答案(但在互联网上比我出色的人对此主题写得很出色。)

Edit: 编辑:

Bonus: PubSub 奖金:PubSub

I probably should also mention PubSub, which creates a message system that you can publish to and subscribe to, provided you are using a language that has a client for that PubSub system. 我可能还应该提到PubSub,如果您使用的语言具有该PubSub系统的客户端,它会创建一个可以发布和订阅的消息系统。 For example here are all the clients for redis https://redis.io/clients and here is redis pubsub https://redis.io/topics/pubsub 例如,这里是redis https://redis.io/clients的所有客户端,这里是redis pubsub https://redis.io/topics/pubsub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM