从python内部调用python脚本 [英] Calling python scripts from inside python

查看:136
本文介绍了从python内部调用python脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我花了我一整天的时间才能找到此解决方案,所以我希望其他人也能看到它.

It took me forever to find this solution, so I want others to be able to see it.

我想编写一个python脚本来创建一个虚拟环境并在其中安装模块.不幸的是,pip不能很好地配合子流程,如下所示: https://github.com/pypa/pip/issues/610

I wanted to write a python script to create a virtual env and install modules inside it. Unfortunately, pip does not play nice with subprocess, as detailed here: https://github.com/pypa/pip/issues/610

我的答案已经在该线程上,但是我想在下面对其进行详细介绍

My answer is already on that thread, but I wanted to detail it below

推荐答案

基本上,问题是pip仍在使用原始python调用的python可执行文件.要解决此问题,您需要从传入的环境变量中将其删除.解决方法如下:

Basically, the issue is that pip is still using the python executable that the original python called. To fix this, you need to delete it from the passed in environment variables. Here is the solution:

#!/usr/bin/python3
import os
import subprocess

python_env_var = {"_", "__PYVENV_LAUNCHER__"}
CMD_ENVIRONMENT = {name: value for (name, value) in os.environ.items() 
                   if name not in python_env_var}  
subprocess.call('./pip install -r requirements.txt', shell=True, 
                env=CMD_ENVIRONMENT)

在Mac,ubuntu 14.04和Windows上使用python 3进行了测试

Tested on Mac, ubuntu 14.04 and Windows with python 3

在许多情况下很容易存在相同的问题-从现在开始,我将删除此变量,以防止在处理virtualenv时出现这种行为

This same problem could easily exist for lots of situations -- I will be deleting this variable from now on, to prevent this kind of behavior when dealing with virtualenv's

这篇关于从python内部调用python脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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