繁体   English   中英

尝试使用子进程执行Python脚本(Django)

[英]Trying to Execute Python Script Using Subprocess (Django)

我正在尝试使用我知道可以在手动执行脚本的子进程来执行脚本; 以下来自我的调用脚本:

# the command string we want to issue to ffmpeg.py to generate our ffmpeg command strings
        commandString = [
            'python',
            os.path.join(SCRIPT_DIR, 'ffmpeg.py'),
            '-i', os.path.join('/srv/nfsshare/transcode50', userFolder, directory, title),
            '-d', os.path.join('/srv/nfsshare/transcode50', userFolder, directory),
            '-r', request.POST['framerate'],
            '-p 2', '-f', ",".join(formats), '-t', ",".join(rasters)
        ]

        # call transcode50 script to generate condor_execute.py
        subprocess.call(' '.join(commandString) + ' > /srv/nfsshare/transcode50/output.txt', shell=True)

实际的脚本本身实质上将生成命令字符串列表,并将其输出到控制台。 我将输出通过管道传递到该命令字符串末尾的名为output.txt的文件以进行测试,因为我正在运行Django的Python代码,无法实时查看shell输出,但是当我分别检查文件时时间,里面什么也没有,被调用脚本也没有产生副作用(生成Python文件)。 因此,我相信使用子流程模块可能会考虑也可能不会考虑,也许它是Django特有的?

使用''.join(...)将列表转换为shell字符串是有风险的,因为列表中可能存在某些需要转义shell的内容(例如文件名中的空格)。 您最好只坚持使用命令列表而不是shell。 您还应该捕获stderr,这将是好的东西。 最后,使用check_call并将整个程序包装在记录执行失败的异常处理程序中。

try:
    commandString = [
        'python',
        os.path.join(SCRIPT_DIR, 'ffmpeg.py'),
        '-i', os.path.join('/srv/nfsshare/transcode50', userFolder, directory, title),
        '-d', os.path.join('/srv/nfsshare/transcode50', userFolder, directory),
        '-r', request.POST['framerate'],
        '-p 2', '-f', ",".join(formats), '-t', ",".join(rasters)
    ]

    # call transcode50 script to generate condor_execute.py
    subprocess.check_call(commandString, 
        stdout=open('/srv/nfsshare/transcode50/output.txt', 'w'),
        stderr=subprocess.STDOUT)

except Exception, e:
    # you can do fancier logging, but this is quick
    open('/tmp/test_exception.txt', 'w').write(str(e))
    raise

暂无
暂无

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

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