使用 python 在不同的 virtualenv 中运行子进程 [英] Running subprocess within different virtualenv with python

查看:27
本文介绍了使用 python 在不同的 virtualenv 中运行子进程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在 2 个不同的虚拟环境中安装了 2 个不同版本的应用程序.myapp v1.0 和 myapp v2.0.

Let's say I have 2 different versions of my app installed in 2 different virtualenvironments. myapp v1.0 and myapp v2.0.

现在我想比较这些.比较是用python本身编写的.什么是最好的方法呢?让我们假设我可以单独运行它们并同时编写一个输出文件,我可以稍后进行比较.

Now I would like to compare those. The comparison is written in python itself. What would be the best way to do that? Let's assume I can run them separately and both write an output file, which I can compare later.

一种方法是编写一个 bash 脚本(这是我目前所拥有的).我激活一个 virtualenv,运行 myapp v1.0,激活另一个 virtualenv,运行 myapp v2.0.稍后在这些文件上运行比较模块.但我想在那里添加更多动态(采用一些可选参数等),这在 python 中会更容易.

One way to do that would be to write a bash script (that's what I have currently). I activate one virtualenv, run myapp v1.0, activate another virtualenv, run myapp v2.0. Later run a comparison module on those files. But I would like to add some more dynamics there (take some optional arguments etc) which would be easier with python.

目前我有类似的东西(一个 bash 脚本):

Currently I have something like that (a bash script):

source virtualenv1/bin/activate
python my_script.py
deactivate

source virtualenv2/bin/activate
python my_other_script.py
deactivate

python my_comparison_script.py

相反,我只想做:

python my_comparison_script.py

我的脚本将在其中运行.

and my scripts would be run inside this.

推荐答案

究竟是什么问题?如何使用子进程执行shell命令?如果是这种情况,一些简单的伪代码可能如下所示:

what exactly is the question? how to use subprocess to execute shell commands? if that's the case, some simplistic pseudo code might look like:

import subprocess

myProcess = subprocess.Popen(   ['these', 'are', 'for', 'the', 'shell'],
                                stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE )

[outStream, errStream] = myProcess.communicate()

然后你可以用标准输出(outStream)做任何你想做的事情,如果errStream存在(标准错误),你可以做不同的事情.这包括将标准输出或标准错误写入文件.那么我想你会区分这些文件吗?

then you can do whatever you'd like with standard out (outStream) and do different things if errStream exists (standard error). this includes writing the standard out or standard error to a file. then i presume you would diff those files?

一个实际的代码示例(假设您在 linux 系统上有 python 2.6+)可能如下所示:

an actual code example (assuming you have python 2.6+ on a linux system) might look like:

import subprocess

with open('dateHelp.log', 'w') as dateLog:
    with open('dateHelp.err', 'w') as errLog:
        dateHelp = subprocess.Popen([ 'date', '-h'], stdout=dateLog, 
                                                     stderr=errLog)
        dateHelp.communicate()

这篇关于使用 python 在不同的 virtualenv 中运行子进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆