在Python3中使用Script = argv

A S*_*anz 2 python sys argv python-3.x

我正在玩Python3,每次我运行Python3 ex14.py下面的代码,我打印(f"Hi {user_name}, I'm the {script} script.")我得到的{user_name}权利,但{script}显示我正在运行的文件加上变量{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.")
Run Code Online (Sandbox Code Playgroud)

如何打印我正在运行的文件?

tim*_*geb 5

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