4

I was trying to use sys.argv[0] to get the name of the script but it returned nothing. I guess that was because no script name was passed to the Python interpreter but I had no idea how to fix it.

my code:

import sys
print ("This is the name of the script: ", sys.argv[0])
sys.argv[0]

outputs:

>>> import sys
>>> print ("This is the name of the script: ", sys.argv[0])
This is the name of the script:
>>> sys.argv[0]
''

Thank you

Paul Rooney
  • 20,879
  • 9
  • 40
  • 61
Xiaoyu
  • 51
  • 5

2 Answers2

2

Well, that's well expected,

you're running your code on the interpreter, which is not any module nor file, so sys.argv knows that and gives you an empty string.

It's a good sign.

If you run it in an actual module or file, it will work perfectly, as expected.

U13-Forward
  • 69,221
  • 14
  • 89
  • 114
0

You should run your code in a shell, then the arguments fellow the python filename, just like: python3 test.py first second. then in the code, you can find the args in the file.

print(sys.argv[1]) -------> first<br>    
print(sys.argv[2]) -------> second

I hope it will be helpful.

Prashant Pokhriyal
  • 3,727
  • 4
  • 28
  • 40