【问题标题】:Trying to Execute Python Script Using Subprocess (Django)尝试使用子进程(Django)执行 Python 脚本
【发布时间】:2013-11-02 08:58:59
【问题描述】:

我正在尝试使用子进程执行一个脚本,当我手动执行它时我知道它可以工作;以下来自我的调用脚本:

# 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 文件)不会发生。因此,我相信我可能会或可能不会考虑使用 subprocess 模块,也许它是 Django 特定的?

【问题讨论】:

  • 你为什么要把它作为一个子进程调用而不是简单地导入脚本并调用它?
  • 我可以导入这个脚本,这可能会起作用,但它会生成一个新的 Python 脚本,无论如何都需要运行,所以仍然需要解决问题才能执行新脚本,除非您有任何关于在“会话”开始后运行生成的 Python 脚本的建议(即,保存一个新的 script.py 文件,但仍然能够从生成它的同一脚本中打开并执行它)。跨度>
  • 你失去了标准错误,这可以解释发生了什么。

标签: python django subprocess


【解决方案1】:

使用 ' '.join(...) 将列表转换为 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

【讨论】:

    猜你喜欢
    • 2016-11-29
    • 1970-01-01
    • 1970-01-01
    • 2021-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多