导入python脚本并传递参数以在其他脚本中运行

时间:2019-01-16 09:33:42

标签: python python-2.7 parsing arguments

所以我有我运行的主要python脚本,并且基本上将-p,-e-d三个参数传递给另一个python脚本。为了理解这一点,我一直在使用subprocess

我要实现的不是使用subprocess,而是要import第二个文件'generate_json.py',并且能够将三个参数传递给它的main()函数。如何像在subprocess调用中那样传递三个参数?

我的主脚本代码如下:

import generate_json as gs


def get_json_location(username=os.getlogin()):
    first = "/Users/"
    last = "/Desktop/data-code/Testdata"
    result = first + username + last
    return result

2 个答案:

答案 0 :(得分:0)

假定脚本文件不必单独使用,即:generate_json.py可以从命令行上单独使用。

我认为更干净的方法是包装generate_json.py函数并将其放入类中。


在这种情况下,我将generate_json.py重命名为ConfigurationHandling.py

import os
import json
from functions import read_config

class ConfigurationHandler(object):
    def __init__(self, new_parameter_file, new_export_data_file, new_export_date):
        self._parameter_file = new_parameter_file
        self._export_data_file = new_export_data_file
        self._export_date = new_export_date
        self._parsed_configuration = self.read_configuration()

        self._perform_some_action1()
        self._perform_some_action2()

    def _read_configuration(self):
        """Uses lower level function `read_config` in function.py file to read configuration file"""
        parsed_configuration = read_config(self.export_data_file)
        return parsed_configuration

    def _perform_some_action1(self):
        pass

    def _perform_some_action2(self):
    #     Logic code for parsing goes here.
        pass

    def get_config(self):
        """Returns configuration"""
        return [self.parameter_file, self.parsed_configuration, self.export_date]


    def json_work(self):
        cfg = self.get_config()[0]  # json location
        data = self.get_config()[1]  # export_agent_core_agent.yaml
        date = self.get_config()[2]  # synthetic data folder - YYYY-MM-DD

        if not date:
            date = ""
        else:
            date = date + "/"

        json_location = cfg  # json data path
        json_database = data["config"]["database"]
        json_collection = data["config"]["collection"]
        json_path = "{0}/{1}{2}/{3}/{3}.json".format(json_location, date, json_database, json_collection)
        json_base_name = json_database + "/" + json_collection + "/" + os.path.basename(json_path)  # prints json filename
        current_day = date


        with open('dates/' + current_day + '.json', 'a') as file:
            data = {}


            if os.path.exists(json_path):
                json_file_size = str(os.path.getsize(json_path))  # prints json file size
                print("File Name:" " " + json_base_name + " " "Exists " + "\n")
                print("File Size:" " " + json_file_size + " " "Bytes " "\n")
                print("Writing to file")
                # if json_path is not False:
                data['File Size'] = int(json_file_size)
                data['File Name'] = json_base_name
                json.dump(data, file, sort_keys=True)
                file.write('\n')

            else:
                print(json_base_name + " " "does not exist")
                print("Writing to file")
                data['File Name'] = json_base_name
                data['File Size'] = None
                json.dump(data, file, sort_keys=True)
                file.write('\n')

        file.close()

然后在main.py

from ConfigurationHandler import ConfigurationHandler

def main():
    #Drive the program from here and add the functionality together.
    #Routine to do some work here and get the required variables
    parameter_file = "some_parameter"
    export_data_file = "some_file.yaml"
    new_export_date = "iso_8601_date_etc"

    conf_handl = ConfigurationHandler(parameter_file, export_data_file, new_export_date)
    configuration = conf_handl.get_config()
    conf_handl.json_work()


if __name__ == '__main__':
    main()

在项目中,您应该旨在仅拥有一个主要功能,并相应地拆分功能。
稍后,当所有内容均分后,更改程序的各个部分会容易得多。

答案 1 :(得分:0)

到目前为止,我有以下内容:

from genrate_jsonv2 import ConfigurationHandler
import os
import argparse

def get_json_location(username=os.getlogin()):
    first = "/Users/"
    last = "/Desktop/data-code/Testdata"
    result = first + username + last
    return result

def get_config():
    parser = argparse.ArgumentParser()
    parser.add_argument("-d", "--export-date", action="store", required=True)
    args = parser.parse_args()

    return [args.export_date]

yml_directory = os.listdir('yaml')
yml_directory.remove('export_config.yaml')
data = get_config()[0]

def main():

 for yml in yml_directory:
    parameter_file = get_json_location
    export_data_file = yml
    new_export_date = data

    conf_handl = ConfigurationHandler(parameter_file, export_data_file, new_export_date)
    configuration = conf_handl.get_config()
    conf_handl.json_work()


if __name__ == '__main__':
    main()

问题是在export_data_file内,我真的不想传递file_path位置,而是让它遍历yml目录中的每个file_name。这样做时,我收到一条错误消息,“读取配置文件时出错”