【发布时间】:2019-03-10 07:05:37
【问题描述】:
我的问题是,如果我使用两个函数,这段代码不接受两个输入参数。
我也尝试在第二个函数中插入和删除点击命令和点击选项,但我总是得到主应用程序要求额外的参数(需要给出 2)或者代码没有执行第二个功能。 ("add_new_column")
我在这里做错了什么?
import pandas as pd
@click.command()
@click.option('--infile', prompt='Your input TSV filename', help='Write your tab separated value filename.')
@click.option('--out', prompt='Your output CSV filename', help='Write your new comma separated value filename.')
def convert_tsv_to_csv(infile, out):
"""Converting a Tab Separated Value into a Comma Separated Value for given files in cli arguments"""
df = pd.read_csv(infile, delimiter='\t')
df.to_csv(out, sep=',')
# @click.command()
# @click.option('--out', prompt='Your output CSV filename', help='Write your new comma separated value filename.')
# def add_new_column(out):
# """Adding a new column named "price_edited" """
# df = pd.read_csv(out, delimiter=',')
# # this line creates a new cloned column from price column, which is a Pandas series.
# # we then add the series to the dataframe, which holds our parsed CSV file
# df['price_edited'] = df['price']
# # save the dataframe to CSV
# df.to_csv(out, sep=',')
if __name__ == '__main__':
convert_tsv_to_csv()
#add_new_column()```
第二次尝试:
import click
import pandas as pd
@click.command()
@click.option('--infile', prompt='Your input TSV filename', help='Write your tab separated value filename.')
@click.option('--out', prompt='Your output CSV filename', help='Write your new comma separated value filename.')
def convert_tsv_to_csv(infile, out):
"""Converting a Tab Separated Value into a Comma Separated Value for given files in cli arguments"""
df = pd.read_csv(infile, delimiter='\t')
df.to_csv(out, sep=',')
def add_new_column():
"""Adding a new column named "price_edited" """
df = pd.read_csv(out, delimiter=',')
# this line creates a new cloned column from price column, which is a Pandas series.
# we then add the series to the dataframe, which holds our parsed CSV file
df['price_edited'] = df['price']
# save the dataframe to CSV
df.to_csv(out, sep=',')
if __name__ == '__main__':
convert_tsv_to_csv()
add_new_column()
【问题讨论】:
-
您的第二次尝试在我的机器上运行。没有错误。
-
但它没有执行“添加新列”功能
-
第二个例子永远不会像你期望的那样工作,see here。 Click 是一个实现命令行的工具。你希望你的命令行是什么样的?
-
@StephenRauch, python runme.py --infile 1.csv --out 2.csv 我也想将这两个参数传递给第二个函数(我实际上只需要传递 out在这个特定的第二个功能案例中......)
-
啊,我明白了。只需将“添加新列”功能传入您的点击功能即可。请参阅下面的我的工作解决方案。只需添加 1 行:add_new_column(out)
标签: python python-3.x command-line-interface python-click