CLI命令,使用Python的Click包。

huangapple go评论112阅读模式
英文:

CLI command with Click package Python

问题

I am using click library in order to call function from one folder and read file and after that to write file.

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()

The problem that I stumble upon is when I call python script python path1/read_data.py ./path/data/f1.csv ./path/data/f2.xlsx

It does not write the pandas dataframe to the folder path. What I am doing wrong? Any help is welcome.

英文:

I am using click library in order to call function from one folder and read file and after that to write file.

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()

The problem that I stumble upon is when I call python script python path1/read_data.py ./path/data/f1.csv ./path/data/f2.xlsx

It does not write the pandas dataframe to the folder path. What I am doing wrong? Any help is welcome.

答案1

得分: 0

因为你定义的是Options,而不是Arguments。请按如下方式运行:

并且你需要为“writing”指定输出文件:

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

注意"w"click.File("w")的一个参数。

英文:

Because you define Options, not Arguments. Run it as:

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

And you need to specify the output file for "writing":

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

note the "w" as a parameter of click.File("w")

huangapple
  • 本文由 发表于 2023年6月12日 21:36:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/76457213.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定