繁体   English   中英

如何从命令行进行 python 进程输入?

[英]How to make python process inputs from command line?

我有一个 python 脚本,最终将转换为.exe文件。 The way it is supposed to work is that a user will drag an excel file and drop it on to the python file, which will run, and create another output excel file.

但是,它需要来自用户的 2 个输入: groupssize

当我删除 excel 文件时,命令提示符会自动打开,并提示我输入。 但是,提交值后,命令提示符会自动关闭,而不执行脚本的 rest。

如果我在不提示用户的情况下对groupssize的值进行硬编码,问题就会消失。

这是代码:

import pandas as pd 
import sys

x = sys.argv[1]
file = pd.read_excel(x)
file = file.sample(frac=1).reset_index(drop=True)
file['Order'] = file.groupby('GENDER').cumcount()
file = file.sort_values(['Order', 'GENDER'], ascending=[True,False]).reset_index(drop=True)

groups = input ("Group number?") 
size = input ("Group size?") 
out = {}
count = 1
students = len(file)
std_sorted = 0

for i in range (0, len(file)-size, size): 
    if count != groups: 
        out["group"+str(count)] = file[i:(i+size)]
    else: 
        out["group"+str(count)] = file[i:]       
    count += 1 
    std_sorted += size 


if std_sorted != students: 
    out["group"+str(count)] = file[std_sorted:]

index = 0
writer = pd.ExcelWriter('output.xlsx')
for i in out:
    out[i].pop("Order")
    x = pd.DataFrame(out[i])
    x.to_excel(writer, index = False, sheet_name="Sheet"+str(index))
    workbook = writer.book # Access the workbook
    worksheet= writer.sheets["Sheet"+str(index)] # Access the Worksheet

    header_list = x.columns.values.tolist() # Generate list of headers
    for i in range(0, len(header_list)):
        worksheet.set_column(i, i, len(header_list[i])+2) # Set column widths based on len(header)

    index += 1

writer.save()

我可以通过将您的代码复制粘贴到 Pycharm 甚至不运行它来找到您的问题(Pycharm 在代码检查方面做得很好)......

该行:

for i in range (0, len(file)-size, size): 

总是会引发TypeError异常。 发生这种情况是因为len(...)是一个 int,但size是一个字符串,因为它是一个输入。 您需要将输入更改为:

groups = int(input("Group number?"))
size = int(input("Group size?"))

尝试

groups = int(input ("Group number?")) size = int(input ("Group size?"))

代替

groups = input ("Group number?") size = input ("Group size?")

我认为这是一个类型转换问题。 试试吧,也许它可以解决你的问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM