Skip to content

lang.python #

use virtual env

import freeflowuniverse.crystallib.lang.python
py:=python.new(name:'default')! //a python env with name default
py.update()!
py.pip('ipython')!

to activate an environment and use the installed python

source ~/hero/python/default/bin/activate

how to write python scripts to execute

//#!/usr/bin/env -S v -gc none -no-retry-compilation -cc tcc -d use_openssl -enable-globals run

import freeflowuniverse.crystallib.lang.python
import  json


pub struct Person {
    name     string
    age      int
    is_member bool
    skills   []string
}


mut py:=python.new(name:'test')! //a python env with name test
//py.update()!
py.pip('ipython')!


nrcount:=5
//this is used in the pythonexample
cmd:=$tmpl('pythonexample.py')

mut res:=''
for i in 0..5{
    println(i)
    res=py.exec(cmd:cmd)!

}
//res:=py.exec(cmd:cmd)!

person:=json.decode(Person,res)!
println(person)

example python script which is in the pythonscripts/ dir


import json

for counter in range(1, @nrcount):  ##    print(f'done_{counter}')


##example_struct = {
    'name': 'John Doe',
    'age': @nrcount,
    'is_member': True,
    'skills': ['Python', 'Data Analysis', 'Machine Learning']
}

##json_string = json.dumps(example_struct, indent=4)

##print('==RESULT==')
print(json_string)

see crystallib/examples/lang/python/pythonexample.vsh

remark

This is a slow way how to execute python, is about 2 per second on a fast machine, need to implement something where we keep the python in mem and reading from a queue e.g. redis this will go much faster, but ok for now.

see also examples dir, there is a working example

fn new #

fn new(args_ PythonEnvArgs) !PythonEnv

struct PythonEnv #

struct PythonEnv {
pub mut:
	name string
	path pathlib.Path
	db   dbfs.DB
}

fn (PythonEnv) exec #

fn (py PythonEnv) exec(args PythonExecArgs) !string

fn (PythonEnv) init_env #

fn (py PythonEnv) init_env() !

comma separated list of packages to install

fn (PythonEnv) pip #

fn (mut py PythonEnv) pip(packages string) !

comma separated list of packages to install

fn (PythonEnv) pips_done #

fn (mut py PythonEnv) pips_done() ![]string

fn (PythonEnv) pips_done_add #

fn (mut py PythonEnv) pips_done_add(name string) !

fn (PythonEnv) pips_done_check #

fn (mut py PythonEnv) pips_done_check(name string) !bool

fn (PythonEnv) pips_done_reset #

fn (mut py PythonEnv) pips_done_reset() !

fn (PythonEnv) shell #

fn (py PythonEnv) shell(name_ string) !

fn (PythonEnv) update #

fn (py PythonEnv) update() !

comma separated list of packages to install

struct PythonEnvArgs #

@[params]
struct PythonEnvArgs {
pub mut:
	name  string = 'default'
	reset bool
}

struct PythonExecArgs #

@[params]
struct PythonExecArgs {
pub mut:
	cmd                string @[required]
	result_delimiter   string = '==RESULT=='
	ok_delimiter       string = '==OK=='
	python_script_name string // if used will put it in root of the sandbox under that name
	stdout             bool = true
}