[plt-scheme] environment variables (i.e. getenv)

From: Daniel Yoo (dyoo at cs.wpi.edu)
Date: Fri Mar 23 13:51:36 EDT 2007


On Fri, 23 Mar 2007, Andrew Gwozdziewycz wrote:

> In scheme48 there is a function that returns an association list of all 
> the environment variables, environment->alist.
>
> Is there something similar in MzLib? I've only come up with references 
> to getenv in my searching, but that only returns one variable or #f. Any 
> help appreciated.


Hi Andrew,

This might not be completely right yet, but here's something that should 
help, using the Foreign Function Interface (FFI):

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(module environ-vars mzscheme
   (require (lib "foreign.ss"))
   (unsafe!)
   (provide get-environ)

   (define lib (ffi-lib #f))

   ;; get-environ: -> (listof byte-string)
   ;; Returns a list of byte strings.  Each byte string will be
   ;; in the form "key=value".
   (define (get-environ)
     (let ([byte-ptr (get-ffi-obj "environ" lib _pointer)])
       (let loop ([results '()]
                  [i 0])
         (let ([next-elt (ptr-ref byte-ptr _bytes/eof i)])
           (cond
             [(eof-object? next-elt) (reverse! results)]
             [else
              (loop (cons next-elt results) (add1 i))]))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;


This module should provide access to the environ byte strings, so that you 
can later figure out all the environment names:

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
> (map (lambda (b) (car (regexp-match #rx"^[^=]+" b))) (get-environ))
(#"SSH_AGENT_PID"
  #"SHELL"
  #"GTK_RC_FILES"
  #"OLDPWD"
  #"USER"
  #"GNOME_KEYRING_SOCKET"
  #"SSH_AUTH_SOCK"
  #"SESSION_MANAGER"
  #"USERNAME"
  #"DESKTOP_SESSION"
  #"PATH"
  #"GDM_XSERVER_LOCATION"
  #"PWD"
  #"JAVA_HOME"
  #"LANG"
  #"GDMSESSION"
  #"HOME"
  #"SHLVL"
  #"LANGUAGE"
  #"GNOME_DESKTOP_SESSION_ID"
  #"LOGNAME"
  #"DBUS_SESSION_BUS_ADDRESS"
  #"DISPLAY"
  #"XAUTHORITY")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;


Best of wishes!


Posted on the users mailing list.