CLI 命令与 Click 包 Python [已关闭]

问题描述 投票:0回答:1

我正在使用单击库来从一个文件夹调用函数并读取文件,然后写入文件。

import sys
import numpy as np
import pandas as pd

import click

def count_unique_port(df: pd.DataFrame) -> pd.DataFrame:    
    df = df.dropna()
    df = df.groupby(['A1', 'A2'], as_index=False).size()
    return port

@click.command(help="Pandas count")
@click.option("-i", "--input", "infile", type=click.File(), default=sys.stdin, help="Input file name")
@click.option("-o", "--output", "outfile", type=click.File("w"), default=sys.stdout, help="Output file name")

def main(infile, outfile):
    df = pd.read_csv(infile)
    temp = count_unique_port(df)
    print(temp)
    temp.to_excel(outfile, index=False)

if __name__ == "__main__":
    
    main()

我偶然发现的问题是当我调用 python 脚本时

python path1/read_data.py ./path/data/f1.csv ./path/data/f2.xlsx

它不会将 pandas 数据帧写入文件夹路径。我做错了什么?欢迎任何帮助。

python pandas command-line-interface python-click
1个回答
0
投票

因为您定义了Options,而不是Arguments。运行它:

python path1/read_data.py -i ./path/data/f1.csv -o ./path/data/f2.xlsx

并且需要指定“写入”的输出文件:

@click.option("-o", "--output", "outfile", type=click.File("w"), default=sys.stdout, help="Output file name")

注意

"w"
作为
click.File("w")

的参数
© www.soinside.com 2019 - 2024. All rights reserved.