简体   繁体   中英

How to get the program name in an escript program?

I have an Erlang program meant to be run using escript :

% filename: myscript.erl
-export([main/1]).

main(Args) ->
    io:format("Args: ~p~n", [Args]).

When I run escript myscript.erl 123 456 , this is printed:

Args: ["123","456"]

This is good, but where is the name of the program (ie myscript.erl )?

In C, for example, in int main(int argc, char *argv[]) { ... } , argv[0] always contains the name of the program. How can I get the name of the program in Erlang?

From the erlang escript docs :

To retrieve the pathname of the script, call escript:script_name() from your script (the pathname is usually, but not always, absolute).

Here it is in action:

myescript.erl:

-export([main/1]).

main(Args) ->
    io:format("Args: ~p~n~p~n", [Args, escript:script_name()]).

In a bash shell:

~/erlang_programs$ escript myescript.erl 123 456
Args: ["123","456"]
"myescript.erl"

and:

~/erlang_programs$ cd

~$ escript erlang_programs/myescript.erl 123 456
Args: ["123","456"]
"erlang_programs/myescript.erl"

So, despite what the docs say, I get a path relative to the directory from which I issue the escript command, or equivalently the path I feed to the escript command.

Why is the pathname surrounded by double quotes? How can it be removed?

In erlang, the term "a" is a shorthand notation for the list [97] . Similarly, the term "erlang_programs/myescript.erl" is shorthand for the list [101, 114, ...108] . You must repeat that to yourself every time you see the shell print out something with double quotes. The fact that the shell outputs double quoted strings instead of the lists that they really represent is a terrible feature of the shell and leads to untold confusion for beginners and experienced erlangers alike. "Hey, let's print out the raw scores of the student on the last three tests, which were [97,98,99] :

9> io:format("Student scores: ~p~n", [[97,98,99]]).
Student scores: "abc"
ok

Wtf??!

Here are some ways to remove quotes for output:

1) When outputting with io:format/2 , you can use the control sequence ~s :

s : Prints the argument with the string syntax. The argument is ... an iolist(), a binary(), or an atom()... The characters are printed without quotes.

For example:

1> io:format("~s~n", ["hello"]).
hello
ok

2> 

(Credit goes to the op for that one down in the comments!)

2) You can convert a list (eg "abc") to an atom:

~$ erl
Erlang/OTP 20 [erts-9.3] [source] [64-bit] [smp:4:4] [ds:4:4:10] [async-threads:10] [hipe] [kernel-poll:false]
Eshell V9.3  (abort with ^G)

1> list_to_atom("a").
a

2> list_to_atom([97]).
a

3> "a" =:= [97].
true

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM