簡體   English   中英

在Python3中使用Script = argv

[英]Using Script = argv in Python3

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

如何僅打印正在運行的文件?

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM