英文:
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")
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论