当数据由节点js运行时,在python脚本中提交数据

2024-03-28 22:25:42 发布

您现在位置:Python中文网/ 问答频道 /正文

首先,我很抱歉我的英语很差
我使用python代码为telegram创建cli帐户,如下所示:

from pyrogram import Client
from pyrogram.raw import functions

api_id = someNumber
api_hash = "someHash"

with Client("my_account", api_id, api_hash) as app:
    print('Bot is online...')

我使用node.js代码运行python脚本,如下所示:
if(command == 'run cli'){
     var spawn = require("child_process").spawn;
     var process = spawn('python', ["python/hello.py"]);
     process.stdout.on('data', function(data) {
           console.log(data.toString());
     });
}

输出为: Enter phone number or bot token:

我如何从node.js给它我的电话号码?
实际上,当我通过“python hello.py”运行带有cmd的python脚本时,它希望我输入电话号码,然后我按enter键并完成。很容易。
但在这种情况下,我不知道该怎么办


1条回答
网友
1楼 · 发布于 2024-03-28 22:25:42

我认为最简单的方法(如果可能的话)是通过sys.argv修改python脚本以接受命令行参数

因此,您可以将python程序修改为:

from pyrogram import Client
from pyrogram.raw import functions
import sys # we need the sys module to access these arguments I'm talking about

phone_number = sys.argv[1] # the phone number will be the first (and only, I'm assuming) argument. You can pass multiple arguments, and access them with `sys.argv[2]`, `sys.argv[3]`...etc.
api_id = someNumber
api_hash = "someHash"

with Client("my_account", api_id, api_hash, phone_number=phone_number) as app: # pass the phone number to Client
    print('Bot is online...')

现在,您已经将电话号码存储在变量phone_number中,并将其传递给Client,因此您在Python方面应该做得很好

不过,在节点脚本中,实际上必须将电话号码作为参数传递给,您可以通过添加参数作为数组的元素来实现,其中"python/hello.py"是数组的一部分,如下所示:

if(command == 'run cli'){
     var spawn = require("child_process").spawn;
     var process = spawn('python', ["python/hello.py", "PHONE NUMBER GOES HERE"]);
     process.stdout.on('data', function(data) {
           console.log(data.toString());
     });
}

…你应该表现得很好

注意,我还没有测试这段代码

相关问题 更多 >