将硬编码变量(文件名和标题)更改为参数

时间:2019-07-10 15:05:26

标签: python-3.x file graph arguments optional

我有以下代码,其中获得3个文件名,还对标题名称进行硬编码。我想将它们全部4个变量都更改为参数,以便在运行程序时可以给出名称和标题。

我需要在外壳程序中输入所需文件中的1个文件,但需要其他两个可选参数,并且我需要-title "New Title"可选参数来更改旧标题(否则为默认设置)。谁能帮我更改代码或提出建议?

我尝试按照以下方式进行编码,但是我不确定在未输入其中两个文件时应如何更改Python代码,因为它们是可选的。现在,当我不给所有3个文件作为参数时,它给我错误文件丢失。 我自己在下面的新代码中修复了Title选项

parser = argparse.ArgumentParser()

parser.add_argument('File1', help="Enter the file name to graph it")
parser.add_argument('File2', nargs='?', help="Enter the second file to graph both together")
parser.add_argument('File3', nargs='?', help="Enter the second file to graph all together")
parser.add_argument('-title',nargs='?', help="Overwrites the current title")

args=parser.parse_args()

file1 = args.File1
if args.File2:
    file2=args.File2
if args.File3:
    file3=args.File3


if args.title:
    plt.title("\n".join(wrap(args.title)), size = 12)
else:
    plt.title("\n".join(wrap("Performance for "+file1+' & '+file2 +' & '+file3)), size = 12)

以下是当前工作代码,其中包含3个必需文件。我尝试更改为,如果未输入其他2个可选文件,则该文件仅适用于一个文件。

from matplotlib import pyplot as plt
import numpy as np
from textwrap import wrap
import csv
import sys
import argparse #for optional arguments
parser = argparse.ArgumentParser()

parser.add_argument('File1', help="Enter the file name to graph it")
parser.add_argument('File2', nargs='?', help="Enter the second file to graph both together")
parser.add_argument('File3', nargs='?', help="Enter the second file to graph all together")
parser.add_argument('-title',nargs='?', help="Overwrites the current title")

args=parser.parse_args()

file1 = args.File1
if args.File2:
    file2=args.File2
if args.File3:
    file3=args.File3


if args.title:
    plt.title("\n".join(wrap(args.title)), size = 12)
else:
    plt.title("\n".join(wrap("Performance for "+file1+' & '+file2 +' & '+file3)), size = 12)

#Opens the sorted hostnum.csv file and reads it; replaces the quotation marks.
Dict = {} 
csv_file = []
csv_file.append("placeholder")
with open('hostnum.csv', 'rtU') as host:
    for line in host.readlines():
        line = line.replace('"', '')
        line = line.strip('\n')
        rank, value = line.split("\t")
        Dict[value] = rank
        csv_file.append(value)

#Opens the file and reads it
file_1 = []
with open(file1, 'r') as f:
    csvreader = csv.reader(f, delimiter='\t')
    for line in csvreader:
        file_1.append([Dict[line [2]], line[9]])

file_2 = []
with open(file2, 'r') as f:
    csvreader = csv.reader(f, delimiter='\t')
    for line in csvreader:
        file_2.append([Dict[line [2]], line[9]])

file_3 = []
with open(file3, 'r') as f:    
    csvreader = csv.reader(f, delimiter='\t')
    for line in csvreader:
        file_3.append([Dict[line [2]], line[9]])


#scatters (x,y,size_of_dots, color, label)
plt.scatter([int(item[0]) for item in file_1], [int(item[1]) for item in file_1], s=4, c='b', label=file1)
plt.scatter([int(item[0]) for item in file_2], [int(item[1]) for item in file_2], s=4, c='r', label=file2)
plt.scatter([int(item[0]) for item in file_3], [int(item[1]) for item in file_3], s=4, c='g', label=file3)

#indicates the label names at the given spot (if want to change size: prop={'size':8})
plt.legend(loc='upper right', shadow=True, edgecolor = 'grey') 

#Creates grid for x-y axises
#plt.grid(True, linewidth = 0.25)


#x-y labels for the graph
plt.xlabel("Node Names", fontsize = 12)
plt.ylabel("Run Times", fontsize = 12)

#ticks - x and y axisses' data format (change both ::? values in order to change the frequency)
#size is the font size; (start, end_value, frequency)
plt.xticks(np.arange(1,len(csv_file))[::5], [item[0:5] for item in csv_file[1::5]], rotation=90, size=8)
plt.yticks(np.arange(0,11000,1000), size=8)

#Saves a PNG file of the current graph to the folder and updates it every time
#(nameOfimage, dpi=(sizeOfimage),Keeps_Labels_From_Disappearing)
plt.savefig('./test.png', dpi=(250), bbox_inches='tight')

# Not to cut-off bottom labels(manually) - enlarges bottom
plt.gcf().subplots_adjust(bottom=0.23)


plt.show()

EDIT

from matplotlib import pyplot as plt
import numpy as np
from textwrap import wrap
import csv
import argparse # for optional arguments
parser = argparse.ArgumentParser()

#Argument |
#('arg_name', nargs='?' means optional arg., help="Help message when we run 'python name.py -h'")
parser.add_argument('File1', help="Enter the file name to graph it")
parser.add_argument('File2', nargs='?', help="Enter the second file to graph both together")
parser.add_argument('File3', nargs='?', help="Enter the second file to graph all together")
parser.add_argument('-title',nargs='?', help="Overwrites the current title")

args=parser.parse_args()

# Creates wrapped title for the graph using title arg.
if args.title:
    plt.title("\n".join(wrap(args.title)), size = 12)
else:
    plt.title("\n".join(wrap("Performance for "+file1+' & '+file2 +' & '+file3)), size = 12)

Dict = {} 
csv_file = []
csv_file.append("placeholder")
with open('hostnum.csv', 'rtU') as host:
    for line in host.readlines():
        line = line.replace('"', '')
        line = line.strip('\n')
        rank, value = line.split("\t")
        Dict[value] = rank
        csv_file.append(value)

# Opens the file and reads it
# Scatters (x,y,size_of_dots, color, label)

file1 = args.File1
file_1 = []
with open(file1, 'r') as f:
    csvreader = csv.reader(f, delimiter='\t')
    for line in csvreader:
        file_1.append([Dict[line [2]], line[9]])
plt.scatter([int(item[0]) for item in file_1], [int(item[1]) for item in file_1], s=4, c='b', label=file1)

if args.File2:
    file2=args.File2
    file_2 = []
    with open(file2, 'r') as f:
        csvreader = csv.reader(f, delimiter='\t')
        for line in csvreader:
            file_2.append([Dict[line [2]], line[9]])
    plt.scatter([int(item[0]) for item in file_2], [int(item[1]) for item in file_2], s=4, c='r', label=file2)

if args.File3:
    file3=args.File3
    file_3 = []
    with open(file3, 'r') as f:    
        csvreader = csv.reader(f, delimiter='\t')
        for line in csvreader:
            file_3.append([Dict[line [2]], line[9]])
    plt.scatter([int(item[0]) for item in file_3], [int(item[1]) for item in file_3], s=4, c='g', label=file3)

# Indicates the label names at the given spot (if want to change size: prop={'size':8})
plt.legend(loc='upper right', shadow=True, edgecolor = 'grey') 

# Creates grid for x-y axises
# plt.grid(True, linewidth = 0.25)

# x-y labels for the graph
plt.xlabel("Node Names", fontsize = 12)
plt.ylabel("Run Times", fontsize = 12)

# ticks - x and y axisses' data format (change both ::? values in order to change the frequency)
# size is the font size; (start, end_value, frequency)
plt.xticks(np.arange(1,len(csv_file))[::5], [item[0:5] for item in csv_file[1::5]], rotation=90, size=8)
plt.yticks(np.arange(0,11000,1000), size=8)

# Saves a PNG file of the current graph to the folder and updates it every time
# (nameOfimage, dpi=(sizeOfimage),Keeps_Labels_From_Disappearing)
plt.savefig('./test.png', dpi=(250), bbox_inches='tight')

# Not to cut-off bottom labels(manually) - enlarges bottom
plt.gcf().subplots_adjust(bottom=0.23)

plt.show()

1 个答案:

答案 0 :(得分:0)

答案我解决了以下问题

from IPython.display import HTML
HTML('''<script>
    var code_show=true; //true -> hide code at first

    function code_toggle() {
        $('div.prompt').hide(); // always hide prompt

        if (code_show){
            $('div.input').hide();
        } else {
            $('div.input').show();
        }
        code_show = !code_show
    }
    $( document ).ready(code_toggle);
</script>
''')