Program name
You are encouraged to solve this task according to the task description, using any language you may know.
The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".)
Sometimes a multiline shebang is necessary in order to provide the script name to a language's internal ARGV.
See also Command-line arguments
Examples from GitHub.
[edit] Ada
Being a compiled language, Ada has difficulties accessing source code filenames. But it is easy to access the executable's filename, using the function Command_Name defined in Ada.Command_Line:
with Ada.Command_Line, Ada.Text_IO;
procedure Command_Name is
begin
Ada.Text_IO.Put_Line(Ada.Command_Line.Command_Name);
end Command_Name;
[edit] Aime
The program command line arguments are accessible via the argc()/argv() functions. The program name is the first in the list of arguments.
o_text(argv(0));
o_byte('\n');
[edit] AutoHotkey
MsgBox, % A_ScriptName
[edit] BASIC
Many BASICs -- notably older DOS BASICs, and especially DOS MS BASICs -- do not provide any way to retrieve the program's name.
[edit] FreeBASIC
Unlike most MS BASICs, FreeBASIC provides a parsed version of COMMAND$ (called as COMMAND$(n)). COMMAND$(0) is the program's name:
appname = COMMAND$(0)
Additionally, FreeBASIC also provides an analog of C's argc/argv[], called __FB_ARGC__ and __FB_ARGV__. __FB_ARGV__ can be used to get the program's name like this:
appname = *__FB_ARGV__(0)
See also: PowerBASIC, PureBasic, Visual Basic.
[edit] BBC BASIC
SYS "GetCommandLine" TO cl%
PRINT $$cl%
[edit] C
It might not be very useful for a C program to access source filenames, because C code must be compiled into an executable, and anything could have happened to the source file after the compilation. However, C can access the executable's name in argv[0].
-
argv[0]might be the name of an executable in the PATH, or it might be an absolute or relative path to the executable. At least with Unix, the parent process can setargv[0]to any string, soargv[0]might not be the real name. It is best to pretend thatargv[0]has the correct value, but mind thatargv[0]might not be an actual file.
#include <stdio.h>
int main(int argc, char **argv) {
printf("Executable: %s\n", argv[0]);
return 0;
}
To get the source information about some part of code, use compiler defined macros. Most compilers support them or some variation of.
#include <stdio.h>
int main()
{
printf("This code was in file %s in function %s, at line %d\n",\
__FILE__, __FUNCTION__, __LINE__);
return 0;
}
[edit] BSD
BSD provides two more ways to get the program's name.
-
__prognameis the filename fromargv[0](so ifargv[0]is a path, then__prognameis only the filename). No header file declares__progname, so programs must declareextern char __progname;to use it. -
ucommalways gives the real filename of the executable, even ifargv[0]has a different name.ucommis a field in the process information;ps -O ucommprints it. Other than ps(1) and top(1), few programs accessucomm. There is a C interface to the process information, but it often changes between BSD versions.
Starting with OpenBSD 5.0, ucomm is field p_comm of struct kinfo_proc, and kvm_getprocs() in libkvm can fill this struct. (Rosetta Code will welcome contributions for other BSD variants.)
make myname LDLIBS=-lkvm
/* myname.c */
#include <sys/param.h>
#include <sys/sysctl.h> /* struct kinfo_proc */
#include <err.h>
#include <fcntl.h> /* O_RDONLY */
#include <kvm.h>
#include <limits.h> /* _POSIX2_LINE_MAX */
#include <stdio.h>
int
main(int argc, char **argv) {
extern char *__progname; /* from crt0.o */
struct kinfo_proc *procs;
kvm_t *kd;
int cnt;
char errbuf[_POSIX2_LINE_MAX];
printf("argv[0]: %s\n", argv[0]);
printf("__progname: %s\n", __progname);
kd = kvm_openfiles(NULL, NULL, NULL, KVM_NO_FILES, errbuf);
if (kd == NULL)
errx(1, "%s", errbuf);
procs = kvm_getprocs(kd, KERN_PROC_PID, getpid(),
sizeof procs[0], &cnt);
if (procs == NULL)
errx(1, "%s", kvm_geterr(kd));
if (cnt != 1)
errx(1, "impossible");
printf("p_comm: %s\n", procs[0].p_comm);
kvm_close(kd);
return 0;
}
The program can have three different names!
$ perl -e 'exec {"./myname"} "/nobin/fakename"'
argv[0]: /nobin/fakename
__progname: fakename
ucomm: myname
[edit] Windows
GetModuleFileName, from the Win32 API, provides the correct path to the current executable file.
#include <windows.h>
#include <stdlib.h>
#include <wchar.h>
/*
* Returns the path to the current executable file, in a newly
* allocated buffer. Use free() to free it.
*/
wchar_t *
exepath(void)
{
wchar_t *buf, *newbuf;
long blen, flen;
/*
* Most paths fit in MAX_PATH == 260 characters, but very
* long UNC paths might require a larger buffer.
*/
buf = NULL;
for (blen = MAX_PATH; 1; blen += MAX_PATH) {
/* Enlarge buffer. */
newbuf = realloc(buf, blen * sizeof buf[0]);
if (newbuf == NULL) {
free(buf);
return NULL;
}
buf = newbuf;
flen = GetModuleFileNameW(NULL, buf, blen);
if (flen == 0) {
free(buf);
return NULL;
}
if (flen < blen)
return buf;
}
}
/*
* Print the path to this executable.
*/
int
main()
{
wchar_t *path;
path = exepath();
if (path == NULL) {
wprintf(L"Sorry, an error occured.\n");
return 1;
}
wprintf(L"Path to executable: %ls\n", path);
free(path);
return 0;
}
Path to executable: C:\Users\kernigh\Documents\field\scratch.exe
[edit] C++
C++ has difficulty accessing source code filenames, because C code must be compiled into an executable. However, C++ can access the executable's filename.
#include <iostream>
using namespace std;
int main(int argc, char **argv) {
char *program = argv[0];
cout << "Program: " << program << endl;
return 0;
}
[edit] C#
This effectively outputs the executable name, file path, and any arguments for the current program.
using System;
namespace ProgramName
{
class Program
{
static void Main(string[] args)
{
Console.Write(Environment.CommandLine);
}
}
}
In a C# application with a reference to System.Windows.Forms, the following can be used to retrieve the executable name and arguments without the full path.
using System;
namespace ProgramName
{
class Program
{
static void Main(string[] args)
{
// Extracts the filename from the full path
System.IO.FileInfo exeInfo = new System.IO.FileInfo(System.Windows.Forms.Application.ExecutablePath);
Console.Write(exeInfo.Name);
// Writes all arguments to the console
foreach (string argument in args)
{
Console.Write(" " + argument);
}
}
}
}
[edit] Clojure
":";exec lein exec $0 ${1+"$@"}
":";exit
(ns scriptname
(:gen-class))
(defn -main [& args]
(let [program (first *command-line-args*)]
(println "Program:" program)))
(when (.contains (first *command-line-args*) *source-path*)
(apply -main (rest *command-line-args*)))
[edit] Coffeescript
scriptname.coffee:
#!/usr/bin/env coffee
main = () ->
program = __filename
console.log "Program: " + program
if not module.parent then main()
[edit] Common Lisp
Shebangs require a special tweak to ~/.clisprc.lisp.
;;; Play nice with shebangs
(set-dispatch-macro-character #\# #\!
(lambda (stream character n)
(declare (ignore character n))
(read-line stream nil nil t)
nil))
#!/bin/sh
#|
exec clisp -q -q $0 $0 ${1+"$@"}
exit
|#
;;; Usage: ./scriptname.lisp
(defun main (args)
(let ((program (car args)))
(format t "Program: ~a~%" program)
(quit)))
;;; With help from Francois-Rene Rideau
;;; http://tinyurl.com/cli-args
(let ((args
#+clisp (ext:argv)
#+sbcl sb-ext:*posix-argv*
#+clozure (ccl::command-line-arguments)
#+gcl si:*command-args*
#+ecl (loop for i from 0 below (si:argc) collect (si:argv i))
#+cmu extensions:*command-line-strings*
#+allegro (sys:command-line-arguments)
#+lispworks sys:*line-arguments-list*
))
(if (member (pathname-name *load-truename*)
args
:test #'(lambda (x y) (search x y :test #'equalp)))
(main args)))
[edit] D
#!/usr/bin/env rdmd
import std.stdio;
void main(in string[] args) {
writeln("Program: ", args[0]);
}
- Output:
C:\rosetta>program_name.exe Program: program_name.exe
$ dmd scriptname.d
$ ./scriptname
Program: ./scriptname
If the system is configured, the D programming language offers an 'interpreted-looking' mode, which exhibits slightly different behavior than the normal compilation:
$ ./scriptname.d
Program: /tmp/.rdmd/Users/andrew/Desktop/src/scriptname/scriptname.d.D3B32385A31B968A3CF8CAF1E1426E5F
[edit] Dart
#!/usr/bin/env dart
main() {
var program = new Options().script;
print("Program: ${program}");
}
[edit] Delphi
program ProgramName;
{$APPTYPE CONSOLE}
begin
Writeln('Program name: ' + ParamStr(0));
Writeln('Command line: ' + CmdLine);
end.
[edit] Emacs Lisp
:;exec emacs -batch -l $0 -f main $*
;;; Shebang from John Swaby
;;; http://www.emacswiki.org/emacs/EmacsScripts
(defun main ()
(let ((program (nth 2 command-line-args)))
(message "Program: %s" program)))
[edit] Erlang
Erlang's macros hold information about the running module.
%% Compile
%%
%% erlc scriptname.erl
%%
%% Run
%%
%% erl -noshell -s scriptname
-module(scriptname).
-export([start/0]).
start() ->
Program = ?FILE,
io:format("Program: ~s~n", [Program]),
init:stop().
[edit] Euphoria
constant cmd = command_line()
puts(1,cmd[2])
[edit] F#
This code correctly prints the program name in three modes:
- Run as a compiled program (either scriptname.exe in Windows, or mono scriptname.exe in Unix)
- Run as an interpreted program (fsharpi scriptname.fsx)
- Run as a dotslashed program in Unix (./scriptname.fsx)
#light (*
exec fsharpi --exec $0 --quiet
*)
let scriptname =
let args = System.Environment.GetCommandLineArgs()
let arg0 = args.[0]
if arg0.Contains("fsi") then
let arg1 = args.[1]
if arg1 = "--exec" then
args.[2]
else
arg1
else
arg0
let main =
printfn "%s" scriptname
[edit] Factor
#! /usr/bin/env factor
USING: namespaces io command-line ;
IN: scriptname
: main ( -- ) script get print ;
MAIN: main
[edit] Forth
0 arg type cr \ gforth or gforth-fast, for example
1 arg type cr \ name of script
[edit] Fortran
Please find example runs in the comments at the beginning of the FORTRAN2003 source. Program name verification can deter system attackers. Therefore, the code is provided as a separate easily reused module.
! program run with invalid name path/f
!
!-*- mode: compilation; default-directory: "/tmp/" -*-
!Compilation started at Sun Jun 2 00:18:31
!
!a=./f && make $a && OMP_NUM_THREADS=2 $a < unixdict.txt
!gfortran -std=f2008 -Wall -fopenmp -ffree-form -fall-intrinsics -fimplicit-none f.f08 -o f
!
!Compilation finished at Sun Jun 2 00:18:31
! program run with valid name path/rcname
!
!-*- mode: compilation; default-directory: "/tmp/" -*-
!Compilation started at Sun Jun 2 00:19:01
!
!gfortran -std=f2008 -Wall -fopenmp -ffree-form -fall-intrinsics -fimplicit-none f.f08 -o rcname && ./rcname
! ./rcname approved.
! program continues...
!
!Compilation finished at Sun Jun 2 00:19:02
module sundry
contains
subroutine verify_name(required)
! name verification reduces the ways an attacker can rename rm as cp.
character(len=*), intent(in) :: required
character(len=1024) :: name
integer :: length, status
! I believe get_command_argument is part of the 2003 FORTRAN standard intrinsics.
call get_command_argument(0, name, length, status)
if (0 /= status) stop
if ((len_trim(name)+1) .ne. (index(name, required, back=.true.) + len(required))) stop
write(6,*) trim(name)//' approved.'
end subroutine verify_name
end module sundry
program name
use sundry
call verify_name('rcname')
write(6,*)'program continues...'
end program name
[edit] Go
scriptname.go:
package main
import (
"fmt"
"os"
)
func main() {
fmt.Println("Program:", os.Args[0])
}
- Command line session:
> go build scriptname.go > ./scriptname Program: ./scriptname > mv scriptname newname > ./newname Program: ./newname
[edit] Groovy
All the Java solutions work equally well under Groovy when the program is invoked through the "main" method of a class. However, if a Groovy program is invoked as a script, the script runs as an instance method of itself as the instantiating class. If the script is running as a compiled string, the Groovy environment under which it is running assigns it a name.
If you want the script filename, use:
#!/usr/bin/env groovy
def program = getClass().protectionDomain.codeSource.location.path
println "Program: " + program
But if you just want the class name, there are easier ways.
So, just typing in and running the following in the GroovyConsole environment:
println this.class.getName()
yields the following on the first run:
ConsoleScript0
and the following on the third run:
ConsoleScript2
But if we save this one line script under the filename "Autonomous.groovy" and then load the file into the console, we get this on every run:
Autonomous
Using the package statement and an appropriate directory hierarchy to provide namespace semantics works exactly as it does in Java.
[edit] Haskell
Haskell has an impure function for this.
import System (getProgName)
main :: IO ()
main = getProgName >>= putStrLn . ("Program: " ++)
[edit] Icon and Unicon
procedure main()
write(&progname) # obtain and write out the program name from the keyword &progname
end
[edit] Io
#!/usr/bin/env io
main := method(
program := System args at(0)
("Program: " .. program) println
)
if (System args size > 0 and System args at(0) containsSeq("scriptname"), main)
[edit] J
#!/usr/bin/env jconsole
program =: monad : 0
if. (#ARGV) > 1 do.
> 1 { ARGV
else.
'Interpreted'
end.
)
echo 'Program: ', program 0
exit ''
[edit] Java
On one hand, this task is trivial for Java. Java code is (usually) compiled into bytecode as class files. There is exactly one class file per class, named <class name>.class (regardless of what the original source files were called or how classes were organized in the source). One executes Java code by executing some class which contains a main method, by running the command java <class name> <possible arguments>. Hence, it is guaranteed that the "name" of the executable is the class name (possibly prepended by package names, using the usual Java dot notation); and this is known in the main method at the time the code is written because it is the very class that the main method is in. Hence, the complicated solutions listed in this section do not gain anything that is not already known by the programmer at the time the code is written.
However, it is tedious to hard-code the class names if you need to do this in a lot of Java programs. Thus, a more interesting task is to write a snippet of Java code which, without modification, can be copy-and-pasted into the main method of any class and retrieve the class name. This is not trivial because in Java there is no way to use this in a static method to get the class it's in. Listed below are several notable, commonly-cited solutions for this.
You can get the listing of the arguments to the java command through a system property. The first one is the name of the main class that was run. This depends on a system property named "sun.java.command", which might not exist on all Java virtual machines.
public class ScriptName {
public static void main(String[] args) {
String program = System.getProperty("sun.java.command").split(" ")[0];
System.out.println("Program: " + program);
}
}
An alternate solution is to create a dummy inner class, and then retrieve its enclosing class (which is the class the main method is in) through reflection (though this will not work if the code is placed in a method in another source file--it will give the name of the class it is in inside that source file):
public class ScriptName {
public static void main(String[] args) {
Class c = new Object(){}.getClass().getEnclosingClass();
System.out.println("Program: " + c.getName());
}
}
A solution using the security manager:
public class ScriptName {
public static void main(String[] args) {
Class c = System.getSecurityManager().getClassContext()[0];
System.out.println("Program: " + c.getName());
}
}
A solution using the stack trace (requires Java 1.5+):
public class ScriptName {
public static void main(String[] args) {
String program = Thread.currentThread().getStackTrace()[1].getClassName();
System.out.println("Program: " + program);
}
}
[edit] JavaScript
There is no capability within the ECMA-262 standard (the standard for ECMAScript, the language underlying JavaScript) for a function to determine its name. Since objects in JavaScript are first class objects, variables and properties are only references to objects. The name of an object might be said to be the name used to reference it, however a single object may have many variables and properties that reference it, or none.
In some implementations, the following (non–standard) code will work:
function foo() {
return arguments.callee.name;
}
But it will fail in in others. JavaScript also has anonymous functions that don't have a name, e.g.:
(function(){alert(arguments.callee.name);}())
returns an empty string or undefined even where the first example works.
Node.js has a global variable for this.
#!/usr/bin/env node
/*jslint nodejs:true */
function main() {
var program = __filename;
console.log("Program: " + program);
}
if (!module.parent) { main(); }
[edit] LLVM
Like C, LLVM can use argv to access the executable's filename.
$ make
llvm-as scriptname.ll
llc -disable-cfi scriptname.bc
gcc -o scriptname scriptname.s
./scriptname
Program: ./scriptname
Makefile
all: scriptname.ll
llvm-as scriptname.ll
llc scriptname.bc
gcc -o scriptname scriptname.s
./scriptname
clean:
-rm scriptname
-rm scriptname.s
-rm scriptname.bc
@msg_main = internal constant [13 x i8] c"Program: %s\0A\00"
declare i32 @printf(i8* noalias nocapture, ...)
define i32 @main(i32 %argc, i8** %argv) {
%program = load i8** %argv
call i32 (i8*, ...)* @printf(i8* getelementptr inbounds ([13 x i8]* @msg_main, i32 0, i32 0), i8* %program)
ret i32 0
}
[edit] Lua
Lua's arg is like C's argv.
#!/usr/bin/env lua
function main(arg)
local program = arg[0]
print("Program: " .. program)
end
if type(package.loaded[(...)]) ~= "userdata" then
main(arg)
else
module(..., package.seeall)
end
[edit] Mathematica
#!/usr/bin/env MathKernel -script
ScriptName[] = Piecewise[
{
{"Interpreted", Position[$CommandLine, "-script", 1] == {}}
},
$CommandLine[[Position[$CommandLine, "-script", 1][[1,1]] + 1]]
]
Program = ScriptName[];
Print["Program: " <> Program]
[edit] Mozart/Oz
Makefile:
all: test
test: scriptname
./scriptname
scriptname: scriptname.oz
ozc -x scriptname.oz
clean:
-rm scriptname
-rm *.exe
scriptname.oz:
functor
import
System
Application
Property
define
local ScriptName = {Property.get 'application.url'} in
{System.printInfo "Script name: "#ScriptName#"\n"}
{Application.exit 0}
end
end
[edit] NASM assembly
[edit] Linux
Makefile:
FORMAT=-f elf
RUN=./
BIN=scriptname
OBJ=scriptname.o
all: test
test: $(BIN)
$(RUN)$(BIN)
$(BIN): $(OBJ)
ld -o $(BIN) $(OBJ)
$(OBJ): scriptname.asm
nasm $(FORMAT) -o $(OBJ) scriptname.asm
clean:
-rm $(BIN)
-rm $(OBJ)
scriptname.asm:
bits 32
section .data
stdout equ 1
sys_write equ 4
sys_exit equ 1
kernel equ 0x80
program db "Program: ", 0
programlen equ $-program
nl db "", 10, 0
nllen equ $-nl
section .bss
scriptname resd 1
scriptnamelen resd 1
section .text
global _start
strlen: ; eax: a string ending in 0
push eax ; cache eax
.strloop:
mov bl, byte [eax]
cmp bl, 0
je .strret ; return len if bl == 0
inc eax ; else eax++
jmp .strloop
.strret:
pop ebx ; ebx = cached eax
sub eax, ebx ; eax -= ebx
ret ; eax = len
_start:
mov eax, esp
add eax, 4
mov eax, [eax]
mov dword [scriptname], eax
mov eax, sys_write
mov ebx, stdout
mov ecx, program
mov edx, programlen
int kernel
mov dword eax, [scriptname]
call strlen
mov dword [scriptnamelen], eax
mov eax, sys_write
mov ebx, stdout
mov dword ecx, [scriptname]
mov dword edx, [scriptnamelen]
int kernel
mov eax, sys_write
mov ebx, stdout
mov ecx, nl
mov edx, nllen
int kernel
mov eax, sys_exit
mov ebx, 0
int kernel
[edit] FreeBSD/Mac OS X
Makefile:
# FreeBSD defaults
FORMAT=-f elf
RUN=./
BIN=scriptname
OBJ=scriptname.o
# Mac OS X
ifeq ($(shell uname -s),Darwin)
FORMAT=-f macho
MINV=-macosx_version_min 10.6
endif
all: test
test: $(BIN)
$(RUN)$(BIN)
$(BIN): $(OBJ)
ld -o $(BIN) $(MINV) $(OBJ)
$(OBJ): scriptname.asm
nasm $(FORMAT) -o $(OBJ) scriptname.asm
clean:
-rm $(BIN)
-rm $(OBJ)
scriptname.asm:
bits 32
section .data
stdout equ 1
sys_write equ 4
sys_exit equ 1
kernel equ 0x80
program db "Program: ", 0
programlen equ $-program
nl db "", 10, 0
nllen equ $-nl
section .bss
scriptname resd 1
scriptnamelen resd 1
section .text
global start
strlen: ; eax: a string ending in 0
push eax ; cache eax
.strloop:
mov bl, byte [eax]
cmp bl, 0
je .strret ; return len if bl == 0
inc eax ; else eax++
jmp .strloop
.strret:
pop ebx ; ebx = cached eax
sub eax, ebx ; eax -= ebx
ret ; eax = len
start:
mov eax, esp
add eax, 4
mov eax, [eax]
mov dword [scriptname], eax
push programlen
push program
push stdout
mov eax, sys_write
sub esp, 4
int kernel
add esp, 4 + 4 * 3
mov dword eax, [scriptname]
call strlen
mov dword [scriptnamelen], eax
push dword [scriptnamelen]
push dword [scriptname]
push stdout
mov eax, sys_write
sub esp, 4
int kernel
add esp, 4 + 4 * 3
push nllen
push nl
push stdout
mov eax, sys_write
sub esp, 4
int kernel
add esp, 4 + 4 * 3
push 0
mov eax, sys_exit
sub esp, 4
int kernel
[edit] Windows
Makefile:
FORMAT=-f win32
BIN=scriptname.exe
OBJ=scriptname.obj
RUN=
all: test
test: $(BIN)
$(RUN)$(BIN)
$(BIN): $(OBJ)
golink /fo $(BIN) $(OBJ) /console kernel32.dll Msvcrt.dll
$(OBJ): scriptname.asm
nasm $(FORMAT) -o $(OBJ) scriptname.asm
clean:
-rm $(BIN)
-rm $(OBJ)
scriptname.asm:
bits 32
section .data
program db "Program: ", 0
programlen equ $-program
nl db "", 13, 10, 0
nllen equ $-nl
stdouthandle equ -11
section .bss
stdout resd 1
charswritten resd 1
env resd 1
argc resd 1
argv resd 255
scriptname resd 1
scriptnamelen resd 1
section .text
global Start
extern GetStdHandle
extern __getmainargs
extern WriteConsoleA
extern ExitProcess
strlen: ; eax: a string ending in 0
push eax ; cache eax
.strloop:
mov bl, byte [eax]
cmp bl, 0
je .strret ; return len if bl == 0
inc eax ; else eax++
jmp .strloop
.strret:
pop ebx ; ebx = cached eax
sub eax, ebx ; eax -= ebx
ret ; eax = len
Start:
push 0
push env
push argv
push argc
call __getmainargs
mov eax, [argv]
mov eax, [eax]
mov [scriptname], eax
add esp, 4 * 4
push stdouthandle
call GetStdHandle
mov [stdout], eax
add esp, 4 * 1
push 0
push charswritten
push programlen
push program
push dword [stdout]
call WriteConsoleA
add esp, 4 * 5
mov eax, [scriptname]
call strlen
mov [scriptnamelen], eax
push 0
push charswritten
push dword [scriptnamelen]
push dword [scriptname]
push dword [stdout]
call WriteConsoleA
add esp, 4 * 5
push 0
push charswritten
push nllen
push nl
push dword [stdout]
call WriteConsoleA
add esp, 4 * 5
push 0
call ExitProcess
[edit] NetRexx
/* NetRexx */
options replace format comments java crossref symbols nobinary
package org.rosettacode.samples
say 'Source: ' source
say 'Program:' System.getProperty('sun.java.command')
return
Output
Called directly:
$ java org.rosettacode.samples.RProgramName Source: Java method RProgramName.nrx Program: org.rosettacode.samples.RProgramName
When bundled inside a JAR file and referenced as the application entry point via the manifest's Main-Class header:
$ java -jar pn.jar Source: Java method RProgramName.nrx Program: pn.jar
[edit] newLISP
newLISP has a function, (main-args int) for this.
#!/usr/bin/env newlisp
(let ((program (main-args 1)))
(println (format "Program: %s" program))
(exit))
[edit] Objective-C
scriptname.m:
#import <Foundation/Foundation.h>
int main(int argc, char **argv) {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
char *program = argv[0];
printf("Program: %s\n", program);
// Alternatively:
NSString *program2 = [[NSProcessInfo processInfo] processName];
NSLog(@"Program: %@\n", program2);
[pool drain];
return 0;
}
$ gcc -o scriptname -framework foundation scriptname.m
$ ./scriptname
Program: ./scriptname
[edit] OCaml
let () =
print_endline Sys.executable_name;
print_endline Sys.argv.(0)
$ ocamlc -o prog_name.bye prog_name.ml $ ocamlopt -o prog_name.opt prog_name.ml $ ocaml prog_name.ml /usr/bin/ocaml prog_name.ml $ ./prog_name.bye ./prog_name.bye ./prog_name.bye $ ./prog_name.opt /tmp/prog_name.opt ./prog_name.opt
[edit] Octave
function main()
program = program_name();
printf("Program: %s", program);
endfunction
main();
[edit] Order
This is relatively trivial in Order, as the program being executed is a macro expression in the current C program file being read by the compiler:
__FILE__
When including another file containing another ORDER_PP expression, within that file the __FILE__ macro will expand to the name of that file; but arguably that expression constitutes a separate Order program within the greater C project.
[edit] PARI/GP
GP does not have access to the name of the program running (especially since it is usually run from the REPL gp). PARI has the same access to argv[0] as C.
[edit] Pascal
program ScriptName;
var
prog : String;
begin
prog := ParamStr(0);
write('Program: ');
writeln(prog)
end.
[edit] Perl
#!/usr/bin/env perl
use strict;
use warnings;
sub main {
my $program = $0;
print "Program: $program\n";
}
unless(caller) { main; }
[edit] Perl 6
In Perl 6, the name of the program being executed is in the special global variable $*PROGRAM_NAME.
say $*PROGRAM_NAME;
[edit] PHP
PHP has a global dictionary for this.
<?php
$program = $_SERVER["SCRIPT_NAME"];
echo "Program: $program\n";
?>
[edit] PicoLisp
The function 'cmd' returns the command name.
: (cmd)
-> "/usr/bin/picolisp"
[edit] PowerBASIC
Previous versions of PowerBASIC (PB/Win 8 or older; PB/CC 4 or older) have to make an API call:
#INCLUDE "Win32API.inc"
'[...]
DIM fullpath AS ASCIIZ * 260, appname AS STRING
GetModuleFileNameA 0, fullpath, 260
IF INSTR(fullpath, "\") THEN
appname = MID$(fullpath, INSTR(-1, fullpath, "\") + 1)
ELSE
appname = fullpath
END IF
Recent versions of PowerBASIC provide the EXE object; EXE.NAME$ returns the program's name, while EXE.NAMEX$ returns the program's name and extension. (EXE.EXTN$ returns the extension only.) So, to get the program's name, we do this:
appname = EXE.NAMEX$
[edit] PureBasic
PureBasic provides a way to retrieve the filename of the program being executed. It includes the file's path.
If OpenConsole()
PrintN(ProgramFilename())
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf
Sample output when executing the above program compiled to an executible file called 'program name.exe':
H:\Data\Rosetta Code\program name.exe
[edit] Python
Python has at least two ways to get the script name: the traditional ARGV and the inspect module.
#!/usr/bin/env python
import sys
def main():
program = sys.argv[0]
print "Program: %s" % program
if __name__=="__main__":
main()
#!/usr/bin/env python
import inspect
def main():
program = inspect.getfile(inspect.currentframe())
print "Program: %s" % program
if __name__=="__main__":
main()
[edit] R
R's syntax is complicated, but doable.
#!/usr/bin/env Rscript
getProgram <- function(args) {
sub("--file=", "", args[grep("--file=", args)])
}
args <- commandArgs(trailingOnly = FALSE)
program <- getProgram(args)
cat("Program: ", program, "\n")
q("no")
[edit] Racket
#!/usr/bin/env racket
#lang racket
(define (program) (find-system-path 'run-file))
(module+ main (printf "Program: ~a\n" (program)))
[edit] Raven
ARGS list " " join "%s\n" print
- Output:
raven arg_file.rv
[edit] REXX
The Rexx PARSE SOURCE instruction parses data describing the source of the program running.
The language processor returns a string that does not change while the program is running.
The source string contains operating system name, followed by either COMMAND, FUNCTION,
SUBROUTINE, or METHOD, depending on whether the program was called as a host command or from a
function call in an expression or using the CALL instruction or as a method of an object.
These two tokens are followed by the complete path specification of the program file.
It should be noted that the format of the complete path varies depending upon the operating system.
/* Rexx */
Parse source . . pgmPath
Say pgmPath
- Output
$ rexx RProgramName.rex /tmp/RProgramName.rex
REXX does not support the use of arg(0) to access the program name. A workaround is to use a shell wrapper script to obtain and provide the invocation name of the wrapper:
#!/bin/sh
rexxbit.rexx $0 $*
Here is a rexx script that makes use of this:
say "The program is called " arg(1)
On TSO, this program
/*REXX program RANG1 in PDS N561985.PRIV.CLIST W. Pachl */
Parse Source a b c
Say 'a='a
Say 'b='!!b
Say 'c='c
yields
a=TSO b=COMMAND c=RANG1 SYS00056 N561985.PRIV.CLIST ? TSO ISPF ?
[edit] version with various types of invokes
Used under Windows/XP and Windows 7 with the following REXXes:
- R4 REXX
- REGINA REXX
- Personal REXX
- ROO REXX
- ooRexx
/*REXX pgm displays the name (& possible path) of the REXX program name.*/
parse version _version
parse source _system _howInvoked _path
say right(_version '◄──►' space(arg(1) arg(2)), 79, '─') /*show title.*/
say " REXX's name of system being used:" _system
say ' how the REXX program was invoked:' _howInvoked
say ' name of the REXX program and path:' _path
if arg()>1 then return 0 /*don't let this program recurse.*/
/*Mama said that cursing is a sin*/
/*invoke ourself with a 2nd arg.*/
call prog_nam , 'subroutine' /*call ourself as a subroutine. */
zz = prog_nam( , 'function') /* " " " " function. */
/*stick a fork in it, we're done.*/
output when using R4 REXX with the input of: command
───────────────────────────────────────────REXX-r4 4.00 3 Jul 2012 ◄──► command
REXX's name of system being used: Win32
how the REXX program was invoked: COMMAND
name of the REXX program and path: D:\PROG_NAM.REX * * PROG_NAM
────────────────────────────────────────REXX-r4 4.00 3 Jul 2012 ◄──► subroutine
REXX's name of system being used: Win32
how the REXX program was invoked: SUBROUTINE
name of the REXX program and path: D:\PROG_NAM.REX * * PROG_NAM
──────────────────────────────────────────REXX-r4 4.00 3 Jul 2012 ◄──► function
REXX's name of system being used: Win32
how the REXX program was invoked: FUNCTION
name of the REXX program and path: D:\PROG_NAM.REX * * PROG_NAM
output when using REGINA REXX with the input of: command
──────────────────────────────REXX-Regina_3.7(MT) 5.00 14 Oct 2012 ◄──► command
REXX's name of system being used: WIN32
how the REXX program was invoked: COMMAND
name of the REXX program and path: D:\prog_nam.rex
───────────────────────────REXX-Regina_3.7(MT) 5.00 14 Oct 2012 ◄──► subroutine
REXX's name of system being used: WIN32
how the REXX program was invoked: SUBROUTINE
name of the REXX program and path: D:\PROG_NAM.rex
─────────────────────────────REXX-Regina_3.7(MT) 5.00 14 Oct 2012 ◄──► function
REXX's name of system being used: WIN32
how the REXX program was invoked: FUNCTION
name of the REXX program and path: D:\PROG_NAM.rex
output when using Personal REXX with the input of: command
────────────────────────────────────REXX/Personal 4.00 21 Mar 1992 ◄──► command
REXX's name of system being used: PCDOS
how the REXX program was invoked: COMMAND
name of the REXX program and path: D:\PROG_NAM.REX
─────────────────────────────────REXX/Personal 4.00 21 Mar 1992 ◄──► subroutine
REXX's name of system being used: PCDOS
how the REXX program was invoked: SUBROUTINE
name of the REXX program and path: D:\PROG_NAM.REX
───────────────────────────────────REXX/Personal 4.00 21 Mar 1992 ◄──► function
REXX's name of system being used: PCDOS
how the REXX program was invoked: FUNCTION
name of the REXX program and path: D:\PROG_NAM.REX
output when using ROO REXX with the input of: command
─────────────────────────────────────────REXX-roo 4.00 28 Jan 2007 ◄──► command
REXX's name of system being used: Win32
how the REXX program was invoked: COMMAND
name of the REXX program and path: D:\PROG_NAM.REX * * PROG_NAM
──────────────────────────────────────REXX-roo 4.00 28 Jan 2007 ◄──► subroutine
REXX's name of system being used: Win32
how the REXX program was invoked: SUBROUTINE
name of the REXX program and path: D:\PROG_NAM.REX * * PROG_NAM
────────────────────────────────────────REXX-roo 4.00 28 Jan 2007 ◄──► function
REXX's name of system being used: Win32
how the REXX program was invoked: FUNCTION
name of the REXX program and path: D:\PROG_NAM.REX * * PROG_NAM
output when using ooRexx with the input of: command
-----------------------------------REXX-ooRexx_4.1.2(MT) 6.03 28 Aug 2012 ?--?
REXX's name of system being used: WindowsNT
how the REXX program was invoked: COMMAND
name of the REXX program and path: E:\PROG_NAM.REX
-------------------------REXX-ooRexx_4.1.2(MT) 6.03 28 Aug 2012 ?--? subroutine
REXX's name of system being used: WindowsNT
how the REXX program was invoked: SUBROUTINE
name of the REXX program and path: E:\PROG_NAM.REX
---------------------------REXX-ooRexx_4.1.2(MT) 6.03 28 Aug 2012 ?--? function
REXX's name of system being used: WindowsNT
how the REXX program was invoked: FUNCTION
name of the REXX program and path: E:\PROG_NAM.REX
[edit] Ruby
#!/usr/bin/env ruby
puts "Path: #{$0}"
puts "Name: #{File.basename $0}"
For example,
$ ruby script.rb Path: script.rb Name: script.rb $ ruby ../rc/script.rb Path: ../rc/script.rb Name: script.rb $ ruby -e 'load "script.rb"' Path: -e Name: -e
[edit] Rust
scriptname.rs:
fn main() {
io::println(fmt!("Program: %s", os::args()[0]));
}
Example:
$ rustc scriptname.rs
$ ./scriptname
Program: ./scriptname
[edit] SAC
scriptname.sac:
use StdIO: all;
use Array: all;
use String: { string };
use CommandLine: all;
int main() {
program = argv(0);
printf("Program: %s\n", program);
return(0);
}
Makefile:
all: scriptname
scriptname: scriptname.sac
sac2c -o scriptname scriptname.sac
clean:
-rm scriptname
-rm scriptname.c
Example:
$ make
sac2c -o scriptname scriptname.sac
$ ./scriptname
Program: ./scriptname
[edit] Scala
Works in interpreted, compiled, and manually interpreted modes.
Example:
$ scala ScriptName.scala
Program: ScriptName.scala
$ scalac ScriptName.scala
$ scala -classpath . ScriptName
Program: ScriptName.scala
$ scala
Welcome to Scala version 2.9.1.final (Java HotSpot(TM) 64-Bit Server VM, Java 1.6.0_26).
Type in expressions to have them evaluated.
Type :help for more information.
scala> :load ScriptName.scala
Loading ScriptName.scala...
import scala.util.matching.Regex.MatchIterator
defined module ScriptName
scala> ScriptName.main(Array[String]())
Program: <console>
ScriptName.scala:
import scala.util.matching.Regex.MatchIterator
object ScriptName {
val program = {
val filenames = new RuntimeException("").getStackTrace.map { t => t.getFileName }
val scala = filenames.indexOf("NativeMethodAccessorImpl.java")
if (scala == -1)
"<console>"
else
filenames(scala - 1)
}
def main(args: Array[String]) {
val prog = program
println("Program: " + prog)
}
}
[edit] Scheme
Getting the program name is tricky. When interpreted, the script name will be printed. When compiled, the executable name will be printed.
#!/bin/sh
#|
exec csi -ss $0 ${1+"$@"}
exit
|#
(use posix)
(require-extension srfi-1) ; lists
(require-extension srfi-13) ; strings
(define (main args)
(let ((prog (cdr (program))))
(display (format "Program: ~a\n" prog))
(exit)))
(define (program)
(if (string=? (car (argv)) "csi")
(let ((s-index (list-index (lambda (x) (string-contains x "-s")) (argv))))
(if (number? s-index)
(cons 'interpreted (list-ref (argv) (+ 1 s-index)))
(cons 'unknown "")))
(cons 'compiled (car (argv)))))
(if (equal? (car (program)) 'compiled)
(main (cdr (argv))))
[edit] Seed7
The function path(PROGRAM) returns the path of the file executed. When the program is interpreted this is the path of the source file. When the program is compiled this is the path of the executable. The functions dir(PROGRAM) and file(PROGRAM) deliver the directory respectivly file name of the program path.
$ include "seed7_05.s7i";
const proc: main is func
local
var integer: i is 0;
begin
writeln("Program path: " <& path(PROGRAM));
writeln("Program directory: " <& dir(PROGRAM));
writeln("Program file: " <& file(PROGRAM));
end func;
Output when the program is interpreted:
Program path: /home/anyuser/seed7_5/prg/programname.sd7 Program directory: /home/anyuser/seed7_5/prg Program file: programname.sd7
Output when the program is compiled:
Program path: /home/anyuser/seed7_5/prg/programname Program directory: /home/anyuser/seed7_5/prg Program file: programname
[edit] Smalltalk
Note that this only works when run as "./scriptname.st", because the shebang must force the script name onto ARGV.
"exec" "gst" "-f" "$0" "$0" "$@"
"exit"
| program |
program := Smalltalk getArgv: 1.
Transcript show: 'Program: ', program; cr.
Works when run in script mode or in a workspace.
| program |
program := Smalltalk commandLine first.
Transcript show: 'Program: ', program; cr.
[edit] Standard ML
#!/usr/bin/env sml
let
val program = CommandLine.name ()
in
print ("Program: " ^ program ^ "\n")
end;
[edit] Tcl
#!/usr/bin/env tclsh
proc main {args} {
set program $::argv0
puts "Program: $program"
}
if {$::argv0 eq [info script]} {
main {*}$::argv
}
[edit] UNIX Shell
#!/bin/sh
echo "Program: $0"
[edit] Vala
Get name of program and print to console:
public static void main(string[] args){
string command_name = args[0];
stdout.printf("%s\n", command_name);
}
Output for program named "filename":
./filename
[edit] VBA
VBA can retrieve the name of the program hosting the VBA code using the Application object:
Debug.Print Application.Name
This is mostly useful for code that is shared between, say, Microsoft Excel and Microsoft Word, but has different requirements or actions depending on where it's running.
[edit] Visual Basic
Visual Basic provides the App object, which has a property called EXEName that contains the program's filename without the extension. (For most uses, this doesn't matter, but for code shared between, for example, a program and a screensaver, it can be important.) So, if a program is called "MyVBapp.exe", retreiving the value of App.EXEName would look like this:
appname = App.EXEName 'appname = "MyVBapp"
Alternately, Visual Basic can make an API call:
Declare Function GetModuleFileName Lib "kernel32" Alias "GetModuleFileNameA" (ByVal hModule As Long, ByVal lpFileName As String, ByVal nSize As Long) As Long
Dim fullpath As String * 260, appname As String, namelen As Long
namelen = GetModuleFileName (0, fullpath, 260)
fullpath = Left$(fullpath, namelen)
If InStr(fullpath, "\") Then
appname = Mid$(fullpath, InStrRev(fullpath, "\") + 1)
Else
appname = fullpath
End If
- Programming Tasks
- Basic language learning
- Initialization
- Ada
- Aime
- AutoHotkey
- BASIC
- BBC BASIC
- C
- BSD libc
- Win32
- C++
- C sharp
- Clojure
- Coffeescript
- Common Lisp
- D
- Dart
- Delphi
- Emacs Lisp
- Erlang
- Euphoria
- F Sharp
- Factor
- Forth
- Fortran
- Go
- Groovy
- Haskell
- Icon
- Unicon
- Io
- J
- Java
- JavaScript
- LLVM
- Lua
- Mathematica
- Mozart/Oz
- NASM assembly
- Linux
- FreeBSD/Mac OS X
- Windows
- NetRexx
- NewLISP
- Objective-C
- OCaml
- Octave
- Order
- PARI/GP
- Pascal
- Perl
- Perl 6
- PHP
- PicoLisp
- PowerBASIC
- PureBasic
- Python
- R
- Racket
- Raven
- REXX
- Ruby
- Rust
- SAC
- Scala
- Scheme
- Seed7
- Smalltalk
- Standard ML
- Tcl
- UNIX Shell
- Vala
- VBA
- Visual Basic
- AWK/Omit
- GUISS/Omit
- Retro/Omit
- ZX Spectrum Basic/Omit
- Maxima/Omit