如何使用python脚本运行终端命令,这是通过wsgi进程保存的?

问题描述 投票:0回答:4

我有一个带有cPanel的Centos 7服务器,我正在研究Telegram机器人以满足我的业务需求。机器人应该能够使用os.system或subprocess.Popen运行终端命令,但是当通过webhook + wsgi进程配置时,这两个选项都不起作用。

我用bot.polling方法测试它们并且它们作为魅力工作,但是在我切换到由flask和wsgi服务的webhook方法之后,两个都停止了为我工作。我尝试过以下方法:

mycommand = "python3.6 GoReport.py --id 31-33 --format word"
os.chdir('dir_to_run_command_from')
os.system(mycommand)

以及以下一个:

mycommand = "python3.6 GoReport.py --id 31-33 --format word"
subprocess.Popen(mycommand, cwd="dir_to_run_command_from", shell=True)

这两个选项现在都什么都不做。我试图打印它们并收到0作为回应。我想知道问题是由权限还是其他原因造成的。

我希望这两个选项都可以通过webhook + wsgi工作,就像它们通过bot.polling方法一样工作。

apache flask centos cpanel wsgi
4个回答
0
投票

我想我弄错了。您的脚本将报告写入特定目录。您的申请路线中不需要结果。

我写了一个名为tryout的小测试应用程序。它在虚拟环境中运行。

$ mkdir tryout
$ cd tryout 
$ python3 -m venv tryout 
$ source tryout/bin/activate
$ export FLASK_APP=tryout/app 
$ export FLASK_ENV=development
$ flask run

目录结构:

/tryout
  /app/*
  /bin/*
  /include/*
  /lib/*
/subdir/*

应用:

# /tryout/app/__init__.py
import sys, os
from flask import Flask

def create_app(env=os.getenv('FLASK_ENV', 'development')):
    app = Flask(__name__)

    @app.route('/run-script')
    def run_script():
        import subprocess

        cmd = 'python script.py'
        cwd = 'subdir'
        ret = subprocess.check_output(cmd, cwd=cwd, shell=True)
        print(ret)

        return ret, 200

    return app

app = create_app()

脚本:

# /subdir/script.py
import os, sys

def main():
    with open('report.txt', 'w+') as fp:
        fp.write('Info\n')

    sys.stdout.write('It works!')

if __name__ == '__main__':
    main()

有用!名为“report.log”的新文件将写入“subdir”目录。在浏览器中显示“它工作!”。

希望我可以帮助你,或者我不知道你想做什么。


0
投票

如果要从flask中运行外部脚本,可以使用子进程从命令行运行脚本。这是正确的解决方案。

@app.route('/run-script')
def run_script():
   cmd = '<your command here!>'
   result = subprocess.check_output(cmd, cwd='<your wordir>', shell=True)
   return render_template('results.html', **locals())

玩得开心!


0
投票

@Bogdan Kozlowskyi

是否可以在命令行上管道?您需要将结果返回给用户吗?

cmd = 'first_cmd | tee report.log'
result = subprocess.check_output(cmd, cwd='<your wordir>', shell=True)

也许你应该寻找像'>>','>'和'tee'这样的shell命令。


0
投票

似乎是用户组权限问题(执行和写入)。

© www.soinside.com 2019 - 2024. All rights reserved.