简体   繁体   English

从命令行或子进程 popen 运行 python function

[英]Run python function from command line or subprocess popen

I wanted to run a test function called test.counttest() that counts up to 10.我想运行一个名为test.counttest()的测试 function,最多计数 10。

def counttest():
    x = 0
    for x in range(0,3):
        x = x+1
        print("Number: "+ str(x))
        time.sleep(1)

I want to call just the function from the command line OR from subprocess popen.我想从命令行或从子进程 popen只调用 function Not write the function, just call it.不写function,直接调用。 Everything I have google keeps bringing me back to how I can write a function from the command line which is NOT what I need.我在谷歌上的所有东西都让我回到了如何从命令行编写 function 这不是我需要的。

I need to specifically run a function from subprocess popen so I can get the stdout in a forloop that can then be sent to a flask socket.我需要专门从子进程 popen 运行 function 以便我可以在 forloop 中获取标准输出,然后可以将其发送到 flask 套接字。 (This is required) (这是必需的)

Main point - How can Call (not write) a function from the command line or from subprocess?要点 - 如何从命令行或子进程调用(不写) function?

Not this:不是这个:

python -c 'import whatever then add code'

But something like this:但是这样的事情:

python "test.counttest()"

or like this:或像这样:

subprocess.Popen(['python', ".\test.counttest()"],stdout=subprocess.PIPE, bufsize=1,universal_newlines=True)

EDIT: This is for @Andrew Holmgren.编辑:这是给@Andrew Holmgren 的。 Consider the following script:考虑以下脚本:

def echo(ws):
    data = ws.receive()
    with subprocess.Popen(['powershell', ".\pingtest.ps1"],stdout=subprocess.PIPE, bufsize=1,universal_newlines=True) as process:
            for line in process.stdout:
                line = line.rstrip()
                print(line)
                try:
                    ws.send(line+ "\n")
                except:
                    pass

this works perfectly for what I need as it: takes the script's stdout and send's it to the ws.send() function which is a websocket.这非常适合我需要的东西:获取脚本的标准输出并将其发送到ws.send() function,这是一个 websocket。

However I need this same concept for a function instead.但是,对于 function,我需要同样的概念。 The only way I know how to get the stdout easily is from using subprocess.popen but if there is another way let me know.我知道如何轻松获取标准输出的唯一方法是使用subprocess.popen但如果有另一种方法让我知道。 This is why I am trying to make a hackjob way of running a function through the subprocess module.这就是为什么我试图通过子进程模块运行 function 的 hackjob 方式。

The question of Run python function from command line or subprocess popen relates in the fact that if I can get a function to run from subprocess, then I know how to get the stdout for a websocket. The question of Run python function from command line or subprocess popen relates in the fact that if I can get a function to run from subprocess, then I know how to get the stdout for a websocket.

Actually you have really a lot of questions inside this one.实际上你在这个里面有很多问题。

  1. How can I send output of function line-by-line to another one (and/or websocket)?如何将 function 的 output 逐行发送到另一个(和/或 websocket)? Just avoid writing to stdout and communicate directly.只需避免写入标准输出并直接通信即可。 yield (or other generator creation methods) are intended exatly for that. yield (或其他生成器创建方法)正是为此而设计的。
import time

def counttest():
    for i in range(10):
        yield f'Item {i}'
        time.sleep(1)

def echo(ws):
    # data = ws.receive()
    for row in counttest():
        ws.send(row)
  1. How to call a function func_name defined in file (suppose it's test.py ) from command line?如何从命令行调用文件中定义的 function func_name (假设它是test.py )? Being in directory with test.py , dotest.py目录中,做
$ python -c 'from test import func_name; func_name()'
  1. How to read from sys.stdout ?如何从sys.stdout读取? The easiest will be to replace it with io.StringIO and restore thing back later.最简单的方法是将其替换为io.StringIO并稍后恢复。
from contextlib import redirect_stdout
import io

def echo(ws):
    f = io.StringIO()
    with redirect_stdout(f):
        counttest()
    output = f.getvalue()
    ws.send(output)

It will return only after call_function() , so you cannot monitor real-time printed items.它只会在call_function()之后返回,因此您无法监控实时打印的项目。

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

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