【问题标题】:Using Script = argv in Python3在 Python3 中使用 Script = argv
【发布时间】:2018-06-26 18:20:55
【问题描述】:

我正在使用 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.")

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

【问题讨论】:

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

标签: python python-3.x argv sys


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-19
      • 1970-01-01
      • 2014-12-28
      • 2012-03-06
      • 1970-01-01
      • 1970-01-01
      • 2012-05-27
      • 2010-10-21
      相关资源
      最近更新 更多