Python为几个进程创建shell

时间:2015-12-31 12:14:42

标签: python shell subprocess call

我在Windows上使用subprocess.call()在python中执行了几个命令,但是对于每一个我需要在调用正确命令之前使用environmet setup执行批处理文件,它看起来像这样

subprocess.call(precommand + command)

有没有办法在python中“创建”shell,批处理文件只执行一次,而且shell命令会多次执行?

2 个答案:

答案 0 :(得分:1)

  1. 将命令写入bat文件(tempfile.NamedTemporaryFile()
  2. 运行bat文件(subprocess.check_call(bat_file.name)
  3. (未经测试):

    #!/usr/bin/env python
    from __future__ import print_function
    import os
    import subprocess
    import tempfile
    
    with tempfile.NamedTemporaryFile('w', suffix='.bat', delete=False) as bat_file:
        print(precommand, file=bat_file)
        print(command, file=bat_file)
    rc = subprocess.call(bat_file.name)
    os.remove(bat_file.name)
    if rc != 0:
        raise subprocess.CalledProcessError(rc, bat_file.name)
    

答案 1 :(得分:0)

您是否需要单独从每个命令获取输出?如果不是 - 您可以使用&&,||传达这些命令或;

from django.shortcuts import render
from .forms import LotteryForm
from django.http import HttpResponseRedirect

# Create your views here.
def lottery_list(request):
    return render(request, 'lottery/lottery.html', {})

def lottery_new(request):
   if request.method == 'POST':
       form = LotteryForm(request.POST)
       if form.is_valid():
           form.save()
            return HttpResponseRedirect('lottery_submitted')
       else:
            return render(request, 'lottery/lottery.html' {'form': LotteryForm()})
   else:  
       form = LotteryForm()
       return render(request, 'lottery/lottery.html', {'form': LotteryForm()})