本篇文章將會介紹如何用Python編寫一個能輸出複雜個人信息的程序。
一、準備工作
在開始編寫程序之前,需要確認已經安裝了Python編程語言的環境。可以通過以下命令檢查:
python --version
如果已經安裝了Python,將顯示其版本號。
另外,還需要使用到以下庫:
json:用於將Python對象轉化為JSON字符串
requests:用於發送HTTP請求
argparse:用於解析命令行選項
通過以下命令安裝:
pip install json requests argparse
二、程序設計
程序將會有一個命令行界面:
python myinfo.py -n David -a 20 -c US -h 1.80 -w 75
上述命令將輸出David的個人信息(年齡20歲,來自美國,身高1.80米,體重75kg):
{
"Name": "David",
"Age": 20,
"Country": "US",
"Height": 1.8,
"Weight": 75.0
}
也可以在命令行中輸入以下命令,將個人信息輸出到文件中:
python myinfo.py -n David -a 20 -c US -h 1.80 -w 75 -o output.json
上述命令將會將David的個人信息輸出到output.json文件中。
三、程序實現
下面是myinfo.py的完整代碼:
import json
import requests
import argparse
def get_args():
parser = argparse.ArgumentParser(description="Output personal information in JSON format")
parser.add_argument('-n', '--name', type=str, required=True, help='Name')
parser.add_argument('-a', '--age', type=int, required=True, help='Age')
parser.add_argument('-c', '--country', type=str, required=True, help='Country')
parser.add_argument('-h', '--height', type=float, required=True, help='Height')
parser.add_argument('-w', '--weight', type=float, required=True, help='Weight')
parser.add_argument('-o', '--output', type=str, help='Output file')
args = parser.parse_args()
return args
def output_info(name, age, country, height, weight, output=None):
data = {'Name': name, 'Age': age, 'Country': country, 'Height': height, 'Weight': weight}
json_data = json.dumps(data)
if output:
with open(output, 'w') as f:
f.write(json_data)
else:
print(json_data)
def main():
args = get_args()
output_info(args.name, args.age, args.country, args.height, args.weight, args.output)
if __name__ == '__main__':
main()
原創文章,作者:GWAPW,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/373284.html