Module: A2KM::ENV_UTILS

Defined in:
lib/a2km/env.rb

Constant Summary collapse

ACTIVATE_TPL_S =
"{{activate}} {{name}}"
ACTIVATE_TPL =
Liquid::Template.parse ACTIVATE_TPL_S
ENV_CMD_TPL =
Liquid::Template.parse(<<-END
#!/usr/bin/env bash
set -e
#{ACTIVATE_TPL_S}
exec python -m ipykernel $@
END
)
CONDA_ACTIVATE =
'source activate'
VIRTUALENV_ACTIVATE =
'workon'

Class Method Summary collapse

Class Method Details

.activate_cmd(kind) ⇒ Object



28
29
30
31
32
33
34
35
36
37
# File 'lib/a2km/env.rb', line 28

def activate_cmd(kind)
  case kind
  when 'conda'
    return CONDA_ACTIVATE
  when 'venv'
    return VIRTUALENV_ACTIVATE
  else
    throw ArgumentError, "kind must be 'conda' or 'venv', not '#{kind}'"
  end
end

.get_prefix(name, kind) ⇒ Object



75
76
77
# File 'lib/a2km/env.rb', line 75

def get_prefix(name, kind)
  in_env(name, 'python -c "import sys; print(sys.prefix)"', kind: kind)
end

.in_env(env, cmd, kind: 'conda') ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/a2km/env.rb', line 39

def in_env(env, cmd, kind: 'conda')
  Open3::popen2('bash') do |stdin, stdout, wait_thr|
    stdin.puts 'set -e'
    stdin.puts ACTIVATE_TPL.render('name' => env, 'activate' => activate_cmd(kind))
    stdin.puts cmd
    stdin.close
    status = wait_thr.value
    if status != 0
      raise ENVError.new("Failed to run #{cmd} in #{kind} env: #{env}")
    end
    return stdout.read
  end
end

.ipykernel_version(env, kind: 'conda') ⇒ Object



58
59
60
# File 'lib/a2km/env.rb', line 58

def ipykernel_version(env, kind: 'conda')
  in_env(env, "python -c 'import ipykernel; print(ipykernel.__version__)'", kind: kind)
end

.kernel_script(name, kind: 'conda') ⇒ Object



53
54
55
56
# File 'lib/a2km/env.rb', line 53

def kernel_script(name, kind: 'conda')
  # return kernel script as a string
  ENV_CMD_TPL.render('name' => name, 'activate' => activate_cmd(kind))
end

.make_kernel_exe(kernel_name, env_name, kind: 'conda') ⇒ Object



62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/a2km/env.rb', line 62

def make_kernel_exe(kernel_name, env_name, kind: 'conda')
  path = A2KM.get_kernel(kernel_name)['resource_dir']
  cmd = kernel_script(env_name, kind: kind)
  kernel_exe = File.join(path, "jupyter-kernel-#{kernel_name}")
  puts "Making executable '#{kernel_exe}'"
  
  File.open(kernel_exe, 'w') do |f|
    f.write(cmd)
  end
  File.chmod(0o755, kernel_exe)
  return kernel_exe
end