2
In python, when I want to use a user-given string in the command line, I use the method sys.argv
.
For example, let’s say I have an executable called 2name.py
consisting of the following code:
import sys
lista_nomes = [sys.argv[k] for k in range(len(sys.argv))]
print("Seu segundo nome é {}".format(lista_nomes[2]))
On the linux terminal, when I type:
python 2name.py Édson Arantes do Nascimento
Returns:
Seu segundo nome é Arantes
I’d like to do this with bash files too, but I’m not getting it. In my search I found only how to use user input using command read
(equivalent of input()
python), but I want to use the input that is given directly on the command line, as well as the sys.argv
. How do I do?
There is also the
$@
(https://www.gnu.org/software/bash/html_node/Special-Parameters.html#index-_0024_0040) - see more details here. But in your case, use$2
it seems to me to go more directly to the point that you need. And just for the record, I didn’t need to create another list, just do itprint("Seu segundo nome é {}".format(sys.argv[2]))
(or, if using Python >= 3.6:print(f"Seu segundo nome é {sys.argv[2]}")
). But if you want to create a copy ofargv
, can dolista_nomes = sys.argv[:]
(fountain)– hkotsubo