在Python3中使用Script=argv

在Python3中使用Script=argv,python,python-3.x,argv,sys,Python,Python 3.x,Argv,Sys,我在玩Python3,每次我运行下面的代码python3ex14.py,我打印(f“Hi{user\u name},我是{script}脚本。”)我得到了{user\u name}正确,但是{script code}显示了我正在运行的文件和变量{user\u name} from sys import argv script = argv prompt = '> ' # If I use input for the user_name, when running the var scr

我在玩Python3,每次我运行下面的代码
python3ex14.py
,我打印
(f“Hi{user\u name},我是{script}脚本。”)
我得到了
{user\u name}
正确,但是
{script code}
显示了我正在运行的文件和变量
{user\u 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.")

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

argv
收集所有命令行参数,包括脚本本身的名称。如果要排除该名称,请使用
argv[1://code>。如果只需要文件名,请使用
argv[0]
。在您的情况下:
script=argv[0]
timgeb的答案是正确的,但是如果您想删除文件的路径,可以从os库中使用
os.path.basename(\uu file\uu)

在您的代码中,它类似于:

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.")

使用
script=argv[0]
包括您调用脚本的确切方式。根据您描述错误的方式,我知道您是从命令行和
输入调用中获取用户名的。为什么两者都有?