Импорт скрипта Python и передача аргументов для запуска в другом скрипте - PullRequest
0 голосов
/ 16 января 2019

Итак, у меня есть мой основной скрипт на 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 голосов
/ 16 января 2019

Пока у меня есть следующее:

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. При этом я получаю сообщение об ошибке «Ошибка чтения файла конфигурации»

0 голосов
/ 16 января 2019

Предполагая, что файлы сценариев не нужно использовать по отдельности, то есть: 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()

В проекте вы должны стремиться иметь только одну основную функцию и соответственно разделить ее.
Позже будет намного легче изменить части программы, когда все разделится равномерно.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...