有没有想过写一个脚本,在执行时打印出自己的名字。这很简单。你一定注意到了主函数是这样写的程序
null
int main(int argc, char** argv)
你一定想知道这两个论点是什么意思。
- 第一个 argc 是传递给程序的参数数。
- 第二个 argv 是一个数组,其中包含传递到程序中的所有参数的名称。
- 除了这些参数,还有一条额外的信息存储在该数组的数组第一个单元格中,即argv[0],它是包含代码的文件的完整路径。
要打印程序名,我们只需将文件名从该路径中切掉。
实施
下面是上述想法的python实现。假设脚本的名称是print_my_name。
# Python program to prints it own name upon execution import sys def main(): program = sys.argv[ 0 ] # argv[0] contains the full path of the file # rfind() finds the last index of backslash # since in a file path the filename comes after the last '' index = program.rfind( "" ) + 1 # slicing the filename out of the file path program = program[index:] print ( "Program Name: % s" % program) # executes main if __name__ = = "__main__" : main() |
Output: print_my_name.py
注: 在Geeksforgeks在线编译器上运行时,输出会有所不同。
本文由 帕拉什尼甘酒店 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 贡献极客。组织 或者把你的文章寄到contribute@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。
如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END