首页 > 解决方案 > Using Script = argv in Python3

问题描述

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?

标签: pythonpython-3.xargvsys

解决方案


argv收集所有命令行参数,包括脚本本身的名称。如果要排除名称,请使用argv[1:]. 如果您只想要文件名,请使用argv[0]. 在你的情况下:script = argv[0]


推荐阅读