要查看环境中已安装的库,我在 Jupyter Python 笔记本单元中运行此代码:
%%bash
pip freeze
这可行,但是如何有条件地执行此代码?
这是我的尝试:
from __future__ import print_function
from ipywidgets import interact, interactive, fixed, interact_manual
import ipywidgets as widgets
def f(x1):
if(x1 == True):
f2()
return x1
interact(f , x1 = False)
def f2():
%%bash
pip freeze
但是评估单元格会引发错误:
File "<ipython-input-186-e8a8ec97ab2d>", line 15
pip freeze
^
SyntaxError: invalid syntax
要生成我正在使用 ipywidgets 的复选框:https ://github.com/ipython/ipywidgets
更新:pip freeze
在check_call
返回 0 结果中运行:
跑步
%%bash
pip freeze
返回已安装的库,因此 0 不正确。
是否subprocess.check_call("pip freeze", shell=True)
正确?
更新 2:
这有效:
from __future__ import print_function
from ipywidgets import interact, interactive, fixed, interact_manual
import ipywidgets as widgets
import subprocess
def f(View):
if(View == True):
f2()
interact(f , View = False)
def f2():
print(subprocess.check_output(['pip', 'freeze']))