在 Python3 中使用 Script = argv
Using Script = argv in Python3
我在玩 Python3,每次我 运行 下面的代码 Python3 ex14.py
打印 (f"Hi {user_name}, I'm the {script} script.")
我得到 {user_name}
是的,但是 {script}
显示我正在 运行ning 加上变量 {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.")
如何只打印我正在 运行ning 的文件?
argv
收集所有命令行参数,包括脚本本身的名称。如果要排除名称,请使用 argv[1:]
。如果只需要文件名,请使用 argv[0]
。在你的情况下:script = argv[0]
.
timgeb 的答案是正确的,但是如果你想摆脱文件的路径,你可以使用 os 库中的 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.")
我在玩 Python3,每次我 运行 下面的代码 Python3 ex14.py
打印 (f"Hi {user_name}, I'm the {script} script.")
我得到 {user_name}
是的,但是 {script}
显示我正在 运行ning 加上变量 {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.")
如何只打印我正在 运行ning 的文件?
argv
收集所有命令行参数,包括脚本本身的名称。如果要排除名称,请使用 argv[1:]
。如果只需要文件名,请使用 argv[0]
。在你的情况下:script = argv[0]
.
timgeb 的答案是正确的,但是如果你想摆脱文件的路径,你可以使用 os 库中的 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.")