Trying to use nix-shell in systemd.services

Hi all

I am trying to configure a service which first executes a nix-shell to prepare environment and after that it starts a streamlit (python) application.

Executing these 2 commands seperately works but configured in a service throws following error.

Jun 07 21:57:32 nixos systemd[1]: llamaindex-streamlit.service: Main process exited, code=exited, status=203/EXEC
Jun 07 21:57:32 nixos systemd[1]: llamaindex-streamlit.service: Failed with result ‘exit-code’.

Here my systemd setup.

‘’’
{ pkgs, … }:
{

systemd.services.llamaindex-streamlit = {
enable = true;

serviceConfig = {
   User = "cyrill";
   WorkingDirectory = "/home/cyrill/tie/llama-index-playground";
   Type = "oneshot";
   ExecStart = ["nix-shell /etc/nixos/shell/python.nix" "pipenv run streamlit run app.py --server.port 8080"];
 };

};
}
‘’’

This is my python.nix

{ pkgs ? import {
config.allowUnfree = true;
} }:

let
manyLinuxFile =
pkgs.writeTextDir “_manylinux.py”
‘’
print(“in _manylinux.py”)
manylinux1_compatible = True
‘’;
in
(pkgs.buildFHSUserEnv {
name = “python-shell”;
targetPkgs = pkgs: (with pkgs; [
python3
pipenv
which
gcc
binutils
ncurses
xorg.libX11
xorg.libXext
xorg.libXrender
xorg.libICE
xorg.libSM
glib
cudatoolkit
]);
profile = ‘’
export PYTHONPATH=${manyLinuxFile.out}:/usr/lib/python3.11/site-packages
‘’;
runScript = “bash”;
}).env

Any sugestion what I’m doing wrong?

thanks
cyrill

nix-shell is meant for temporary nix environments, if you want to setup a Python environment to run your service, define it with Nix straight in your config.

Besides that, your whole setup seems very fragile, imperative and non deterministic.

Ideally, this llama-index-playground project should be available online, and you should be able to build it with Nixpkgs’ python3.pkgs.buildPythonApplication - meaning you’d have to find a different way to run it - not with pipenv run.

Question: Why do you use buildFHSUserEnv?

P.S Use Markdown’s syntax highlighting for code blocks:

```nix
1 Like

Thanks for your answer. I’m new to NIXOS and appreciate any info that helps me set up my Python environment correctly. A first resource I have read through is Python - NixOS Wiki . And it says that you set up python with nix-shell. I just thought I could use my python nix-shell script in the service. But then I’ll try to rebuild it without nix-shell.

Had some trouble to get python libraries running with cudatoolkit and I found an example which worked containing buildFHSUserEnv.

Thanks.

Using buildFHSUserEnv for such a development workflow is a mess - you should use Nixpkgs’ Python packages instead of the Python wheels provided by pypi.org … As for using cudatoolkit, that also should be possible to set this up properly.