The os module
command and environ are built in and short, but each loses something. An
empty argument looks like the end of the list, and a variable that is not set
reads the same as one set to nothing. std/os keeps both apart.
#import "std/os"
#import "std/containers"
#import "std/outcome"
'' Every argument, including an empty one.
dim args as containers.Array( of ustring ) = os.Args( )
print "arguments:"; args.Count( ) - 1
for i as int32 = 1 to args.Count( ) - 1
print " ["; args[ i ]; "]"
next
'' Not set, and set to nothing, are different answers.
os.SetEnv( "BYEXAMPLE_EMPTY", "" )
print "BYEXAMPLE_EMPTY set? "; os.GetEnv( "BYEXAMPLE_EMPTY" ).HasValue( )
print "BYEXAMPLE_NONE set? "; os.GetEnv( "BYEXAMPLE_NONE" ).HasValue( )
'' A default for a variable that is not set.
dim level as ustring = os.GetEnv( "BYEXAMPLE_LEVEL" ).ValueOr( "info" )
print "level: "; level
'' Variables inside a string.
os.SetEnv( "BYEXAMPLE_NAME", "report" )
print os.ExpandEnv( "${BYEXAMPLE_NAME}-final.txt" )
os.UnsetEnv( "BYEXAMPLE_NAME" )
print "after unset: ["; os.ExpandEnv( "$BYEXAMPLE_NAME" ); "]"
'' The system it runs on.
dim as boolean known = cbool( os.OS_NAME = "windows" orelse _
os.OS_NAME = "linux" orelse os.OS_NAME = "macos" )
print "os known? "; known; ", arch: "; os.ARCH_NAME
Run as os first "" "third one":
Output
arguments: 3
[first]
[]
[third one]
BYEXAMPLE_EMPTY set? true
BYEXAMPLE_NONE set? false
level: info
report-final.txt
after unset: []
os known? true, arch: x86_64
| Call | Gives |
|---|---|
os.Args( ) | every argument in an Array( of ustring ), the program first |
os.GetEnv( name ) | an Optional( of ustring ), empty when not set |
os.SetEnv( name, value ) | sets it; a Result that fails on a name with = |
os.UnsetEnv( name ) | removes it |
os.Environment( ) | every variable, sorted, in an OrderedMap |
os.ExpandEnv( text ) | $NAME and ${NAME} replaced; %NAME% too on Windows |
GetEnv( ... ).ValueOr( "info" ) is the usual way to give a setting a default.
A variable that is not set expands to nothing, as in a shell.
The module also knows about the machine: os.OS_NAME and os.ARCH_NAME,
OsVersion( ), Hostname( ), UserName( ), ProcessId( ), PageSize( ),
TotalMemory( ), IsTerminal( fd ), and CpuCount( ) — the processors this
program may use, which is fewer than the machine has inside a container. The
example prints only facts that are the same everywhere.
Set the environment before starting threads. On Linux and macOS, changing a variable while another thread reads the environment is not safe.
Activities
- Set
BYEXAMPLE_LEVELin your shell and run the program again. - Print
os.CpuCount( )and compare it with what your system monitor says.