看到一個挺有意思的例子,用sys實現程序自己輸出自己,由於sys.argv[0]爲Python的腳本名,所以在程序中將sys.argv[0]作爲要讀取的文件就能實現程序輸出自己。以下是代碼:
'''
功能:程序輸出自己(out_put_self)
'''
import sys
#讀取並輸出的就是該程序文件out_put_self.py
f_name = sys.argv[0]
with open(f_name,'r',encoding='utf-8') as f:
line_int = 0
while True:
line_int += 1
line_str = f.readline()
#如果讀到的行爲空,就結束
if line_str:
print('{}:'.format(line_str))
else:
break
可以在文件目錄下按住shift+鼠標右鍵選擇 在此次打開PowerShell 窗口,然後輸入 python out_put_self.py