2

I'm playing around with Python3 and every time I run the code Python3 ex14.py below and I print the (f"Hi {user_name}, I'm the {script} script.") I get the {user_name} right but the {script} shows the file I'm running plus the variable {user_name}

from sys import argv

script = argv
prompt = '> '

# If I use input for the user_name, when running the var script it will show the file script plus user_name
print("Hello Master. Please tell me your name: ")
user_name = input(prompt)

print(f"Hi {user_name}, I'm the {script} script.")

How can I print just the file I'm running?

2
  • use script = argv[0] Commented Jun 26, 2018 at 10:03
  • Include how exactly you are calling your script. The way you are describing the error I understand that you are getting the username from the command line and from an input call. Why both? Commented Jun 26, 2018 at 10:09

2 Answers 2

5

argv collects all the command line parameters, including the name of the script itself. If you want to exclude the name, use argv[1:]. If you want just the filename, use argv[0]. In your case: script = argv[0].

Sign up to request clarification or add additional context in comments.

Comments

0

The answer of timgeb is correct, but if you want to get rid of the path of the file you can use os.path.basename(__file__) from the os lib.

In your code it would be something like :

from sys import argv
import os

script = argv
prompt = '> '

# If I use input for the user_name, when running the var script it will show the file script plus user_name
print("Hello Master. Please tell me your name: ")
user_name = input(prompt)

script = os.path.basename(__file__)
print(f"Hi {user_name}, I'm the {script} script.")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.