在Python3中使用Script=argv

2024-09-24 16:41:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我在玩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.")

如何只打印正在运行的文件?你知道吗


Tags: 文件the代码namefrompyinputscript
2条回答

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

timgeb的答案是正确的,但是如果您想删除文件的路径,可以从os-lib使用os.path.basename(__file__)。你知道吗

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

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

相关问题 更多 >