如何从Django Web应用中在Linux Shell中启动Python子进程命令?

0 投票
1 回答
691 浏览
提问于 2025-04-16 04:21

我有一个网页应用,它可以读取并显示由Python测试文件生成的日志文件。目前,我可以通过命令行启动这些Python文件,运行得很好。

不过,我希望能在应用程序内部直接启动Python测试。

现在我有一个“启动测试”的按钮,它会调用views.py文件中的一个函数。

def launch_tests(request, test_txt_file):
    test_list_file = test_txt_file
    launcher2.main(test_list_file)

    return render_to_response('front_page.html')

这个文本文件里包含了要执行的.py文件的名称。

在launcher2.main里。

import os,time, string, pdb, sys
import getopt,subprocess
import pdb

bi_python_home = '//belfiler1/scratch-disk/conor.doherty/dev/python/bi_python'


def main(test_list_file):

    # if argument passed in for test list file  
    if test_list_file != None:
        test_list = bi_python_home + "/launcher/" + test_list_file
    else:
        # default
        test_list =  bi_python_home + "/launcher/test_list.txt"



    tests_dir =  bi_python_home + "/tests/"
    log_dir =bi_python_home + "/logs/"
    month = '%Y%m'
    day = '%d'
    try :
        for test_to_run in open(test_list):
            sub_dir=os.path.dirname(test_to_run) 
            test_filename = os.path.basename(test_to_run)

            # Create log directory for date if doesn't exist
            cur_log_dir = log_dir + time.strftime(month, time.localtime()) + '/' + time.strftime(month+day, time.localtime()) + '/' + sub_dir 
            if not os.path.exists(cur_log_dir):
                print "creating cur_log_dir "  + cur_log_dir
                os.makedirs(cur_log_dir)


            full_path = string.rstrip(tests_dir + test_to_run)
            #print ' full_path is "' + full_path + '"'
            cmd = 'python ' + full_path


            if os.path.isfile(full_path) == True :
                print'\n'*2
                print "Processing file " + test_to_run,

                log_timestamp = time.strftime("%Y%m%d_%H%M%S", time.localtime())
                log_filename = cur_log_dir + '/' + string.rstrip(test_filename) + "_" + log_timestamp + '.log' 
                print 'log file to use is' + log_filename
                # Redirect stdout and stderr to logfile
                cmd = string.rstrip(cmd) + ' > ' + log_filename
                popen_obj = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
                (stdout, stderr) = popen_obj.communicate()
                print 'executing: ' + cmd
                print 'stderr is: ', stderr





            # if need to debug , remove stream redirection &> above and print stdout, stderr

        #else :
            #print 'ignoring ' , full_path



except IOError, err:
    print str(err) 
    sys.exit(2)

代码运行得很好,除了一个问题。当我启动子进程时,它似乎默认在Windows上执行。因为这些测试使用了一个叫做pexpect的模块,我需要它在Linux上执行。

我一直在想应该有简单的解决办法,但到目前为止我还没有找到。

任何帮助都将非常感谢。

谢谢

1 个回答

1

这里的信息不够多,没法给出准确的答案,但一个常见的问题是,网页前端(比如说apache)是以一个和你不同的用户身份在运行。因此,网页处理程序没有权限去读取你家目录里的文件。它可能还缺少一些重要的环境变量,比如HOME。

先检查一下这个问题。网页服务器的日志里有什么信息呢?

撰写回答