tasks a-s

This commit is contained in:
Ingy döt Net 2013-04-10 23:57:08 -07:00
parent 47bf37c096
commit b83f433714
12433 changed files with 156208 additions and 123 deletions

View file

@ -0,0 +1,7 @@
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 [https://github.com/mcandre/scriptname GitHub].

View file

@ -0,0 +1,4 @@
---
category:
- Initialization
note: Basic language learning

View file

@ -0,0 +1,6 @@
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;

View file

@ -0,0 +1 @@
MsgBox, % A_ScriptName

View file

@ -0,0 +1 @@
appname = COMMAND$(0)

View file

@ -0,0 +1 @@
appname = *__FB_ARGV__(0)

View file

@ -0,0 +1,2 @@
SYS "GetCommandLine" TO cl%
PRINT $$cl%

View file

@ -0,0 +1,10 @@
#include <iostream>
using namespace std;
int main(int argc, char **argv) {
char *program = argv[0];
cout << "Program: " << program << endl;
return 0;
}

View file

@ -0,0 +1,7 @@
#include <stdio.h>
int main(int argc, char **argv) {
printf("Executable: %s\n", argv[0]);
return 0;
}

View file

@ -0,0 +1,8 @@
#include <stdio.h>
int main()
{
printf("This code was in file %s in function %s, at line %d\n",\
__FILE__, __FUNCTION__, __LINE__);
return 0;
}

View file

@ -0,0 +1,37 @@
/* 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;
}

View file

@ -0,0 +1,57 @@
#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;
}

View file

@ -0,0 +1,12 @@
":";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*)))

View file

@ -0,0 +1,6 @@
;;; Play nice with shebangs
(set-dispatch-macro-character #\# #\!
(lambda (stream character n)
(declare (ignore character n))
(read-line stream nil nil t)
nil))

View file

@ -0,0 +1,30 @@
#!/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)))

View file

@ -0,0 +1,7 @@
#!/usr/bin/env rdmd
import std.stdio;
void main(in string[] args) {
writeln("Program: ", args[0]);
}

View file

@ -0,0 +1,3 @@
$ dmd scriptname.d
$ ./scriptname
Program: ./scriptname

View file

@ -0,0 +1,2 @@
$ ./scriptname.d
Program: /tmp/.rdmd/Users/andrew/Desktop/src/scriptname/scriptname.d.D3B32385A31B968A3CF8CAF1E1426E5F

View file

@ -0,0 +1,6 @@
#!/usr/bin/env dart
main() {
var program = new Options().script;
print("Program: ${program}");
}

View file

@ -0,0 +1,8 @@
program ProgramName;
{$APPTYPE CONSOLE}
begin
Writeln('Program name: ' + ParamStr(0));
Writeln('Command line: ' + CmdLine);
end.

View file

@ -0,0 +1,8 @@
:;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)))

View file

@ -0,0 +1,5 @@
-module(scriptname).
main(_) ->
Program = ?FILE,
io:format("Program: ~s~n", [Program]).

View file

@ -0,0 +1,2 @@
constant cmd = command_line()
puts(1,cmd[2])

View file

@ -0,0 +1,8 @@
#! /usr/bin/env factor
USING: namespaces io command-line ;
IN: scriptname
: main ( -- ) script get print ;
MAIN: main

View file

@ -0,0 +1,2 @@
0 arg type cr \ gforth or gforth-fast, for example
1 arg type cr \ name of script

View file

@ -0,0 +1,10 @@
package main
import (
"fmt"
"os"
)
func main() {
fmt.Println("Program:", os.Args[0])
}

View file

@ -0,0 +1,5 @@
#!/usr/bin/env groovy
def program = getClass().protectionDomain.codeSource.location.path
println "Program: " + program

View file

@ -0,0 +1 @@
println this.class.getName()

View file

@ -0,0 +1,4 @@
import System (getProgName)
main :: IO ()
main = getProgName >>= putStrLn . ("Program: " ++)

View file

@ -0,0 +1,3 @@
procedure main()
write(&progname) # obtain and write out the program name from the keyword &progname
end

View file

@ -0,0 +1,9 @@
#!/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)

View file

@ -0,0 +1,13 @@
#!/usr/bin/env jconsole
program =: monad : 0
if. (#ARGV) > 1 do.
> 1 { ARGV
else.
'Interpreted'
end.
)
echo 'Program: ', program 0
exit ''

View file

@ -0,0 +1,6 @@
public class ScriptName {
public static void main(String[] args) {
String program = System.getProperty("sun.java.command").split(" ")[0];
System.out.println("Program: " + program);
}
}

View file

@ -0,0 +1,6 @@
public class ScriptName {
public static void main(String[] args) {
Class c = new Object(){}.getClass().getEnclosingClass();
System.out.println("Program: " + c.getName());
}
}

View file

@ -0,0 +1,6 @@
public class ScriptName {
public static void main(String[] args) {
Class c = System.getSecurityManager().getClassContext()[0];
System.out.println("Program: " + c.getName());
}
}

View file

@ -0,0 +1,6 @@
public class ScriptName {
public static void main(String[] args) {
String program = Thread.currentThread().getStackTrace()[1].getClassName();
System.out.println("Program: " + program);
}
}

View file

@ -0,0 +1,3 @@
function foo() {
return arguments.callee.name;
}

View file

@ -0,0 +1 @@
(function(){alert(arguments.callee.name);}())

View file

@ -0,0 +1,9 @@
#!/usr/bin/env node
/*jslint nodejs:true */
function main() {
var program = __filename;
console.log("Program: " + program);
}
if (!module.parent) { main(); }

View file

@ -0,0 +1,6 @@
$ make
llvm-as scriptname.ll
llc -disable-cfi scriptname.bc
gcc -o scriptname scriptname.s
./scriptname
Program: ./scriptname

View file

@ -0,0 +1,10 @@
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

View file

@ -0,0 +1,10 @@
@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
}

View file

@ -0,0 +1,12 @@
#!/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

View file

@ -0,0 +1,12 @@
#!/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]

View file

@ -0,0 +1,8 @@
/* NetRexx */
options replace format comments java crossref symbols nobinary
package org.rosettacode.samples
say 'Source: ' source
say 'Program:' System.getProperty('sun.java.command')
return

View file

@ -0,0 +1,3 @@
let () =
print_endline Sys.executable_name;
print_endline Sys.argv.(0)

View file

@ -0,0 +1,16 @@
#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;
}

View file

@ -0,0 +1,3 @@
$ gcc -o scriptname -framework foundation scriptname.m
$ ./scriptname
Program: ./scriptname

View file

@ -0,0 +1,6 @@
function main()
program = program_name();
printf("Program: %s", program);
endfunction
main();

View file

@ -0,0 +1 @@
__FILE__

View file

@ -0,0 +1,4 @@
<?php
$program = $_SERVER["SCRIPT_NAME"];
echo "Program: $program\n";
?>

View file

@ -0,0 +1,8 @@
program ScriptName;
var
prog : String;
begin
prog := ParamStr(0);
write('Program: ');
writeln(prog)
end.

View file

@ -0,0 +1 @@
say $*PROGRAM_NAME;

View file

@ -0,0 +1,11 @@
#!/usr/bin/env perl
use strict;
use warnings;
sub main {
my $program = $0;
print "Program: $program\n";
}
unless(caller) { main; }

View file

@ -0,0 +1,2 @@
: (cmd)
-> "/usr/bin/picolisp"

View file

@ -0,0 +1,9 @@
#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

View file

@ -0,0 +1 @@
appname = EXE.NAMEX$

View file

@ -0,0 +1,6 @@
If OpenConsole()
PrintN(ProgramFilename())
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf

View file

@ -0,0 +1,10 @@
#!/usr/bin/env python
import sys
def main():
program = sys.argv[0]
print "Program: %s" % program
if __name__=="__main__":
main()

View file

@ -0,0 +1,10 @@
#!/usr/bin/env python
import inspect
def main():
program = inspect.getfile(inspect.currentframe())
print "Program: %s" % program
if __name__=="__main__":
main()

View file

@ -0,0 +1,12 @@
#!/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")

View file

@ -0,0 +1,4 @@
/* Rexx */
Parse source . . pgmPath
Say pgmPath

View file

@ -0,0 +1,2 @@
#!/bin/sh
rexxbit.rexx $0 $*

View file

@ -0,0 +1 @@
say "The program is called " arg(1)

View file

@ -0,0 +1,5 @@
/*REXX program RANG1 in PDS N561985.PRIV.CLIST W. Pachl */
Parse Source a b c
Say 'a='a
Say 'b='!!b
Say 'c='c

View file

@ -0,0 +1,15 @@
/*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.*/

View file

@ -0,0 +1,6 @@
#!/usr/bin/env racket
#lang racket
(define (program) (find-system-path 'run-file))
(module+ main (printf "Program: ~a\n" (program)))

View file

@ -0,0 +1,4 @@
#!/usr/bin/env ruby
puts "Path: #{$0}"
puts "Name: #{File.basename $0}"

View file

@ -0,0 +1,3 @@
fn main() {
io::println(fmt!("Program: %s", os::args()[0]));
}

View file

@ -0,0 +1,3 @@
$ rustc scriptname.rs
$ ./scriptname
Program: ./scriptname

View file

@ -0,0 +1,19 @@
$ 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>

View file

@ -0,0 +1,18 @@
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)
}
}

View file

@ -0,0 +1,25 @@
#!/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))))

View file

@ -0,0 +1,10 @@
$ 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;

View file

@ -0,0 +1,8 @@
"exec" "gst" "-f" "$0" "$0" "$@"
"exit"
| program |
program := Smalltalk getArgv: 1.
Transcript show: 'Program: ', program; cr.

View file

@ -0,0 +1,4 @@
| program |
program := Smalltalk commandLine first.
Transcript show: 'Program: ', program; cr.

View file

@ -0,0 +1,7 @@
#!/usr/bin/env sml
let
val program = CommandLine.name ()
in
print ("Program: " ^ program ^ "\n")
end;

View file

@ -0,0 +1,10 @@
#!/usr/bin/env tclsh
proc main {args} {
set program $::argv0
puts "Program: $program"
}
if {$::argv0 eq [info script]} {
main {*}$::argv
}

View file

@ -0,0 +1,3 @@
#!/bin/sh
echo "Program: $0"

View file

@ -0,0 +1 @@
Debug.Print Application.Name

View file

@ -0,0 +1,5 @@
public static void main(string[] args){
string command_name = args[0];
stdout.printf("%s\n", command_name);
}

View file

@ -0,0 +1 @@
appname = App.EXEName 'appname = "MyVBapp"

View file

@ -0,0 +1,9 @@
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