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

导入python脚本并传递参数以在其他脚本中运行,python,python-2.7,parsing,arguments,Python,Python 2.7,Parsing,Arguments,因此,我运行了我的主python脚本,并将三个参数传递给另一个python脚本,它们分别是-p、-e和-d。我一直在使用子流程,以了解这一点 我想要实现的不是使用subprocess,而是导入第二个文件'generate_json.py',并能够将三个参数传递给它的main()函数。如何像在子流程调用中那样传递这三个参数 我的主脚本代码如下所示: import generate_json as gs def get_json_location(username=os.getlogin()):

因此,我运行了我的主python脚本,并将三个参数传递给另一个python脚本,它们分别是
-p
、-
e
-d
。我一直在使用
子流程
,以了解这一点

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

我的主脚本代码如下所示:

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

假设脚本文件不必单独使用,即:
generate_json.py
从命令行独立使用

我认为更简洁的方法是包装
生成_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()

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()
然后在
main.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()

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()
在项目中,您的目标应该是只有一个主功能,并相应地将功能拆分。

以后,当所有内容都被平均分配时,更改程序的某些部分会容易得多。

到目前为止,我已获得以下信息:

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中,我并不想传递文件路径位置,而是让它在yml目录中的每个文件名之间循环。执行此操作时,我会收到一个错误,提示“错误读取配置文件”

我可以理解您正在尝试执行的操作,但是我的generate_json文件在其中具有更多功能,它将在目录中的每个文件中循环,并将其分配给导出_data_文件。我已经在问题中更新了上面的generate_json文件。此main.py需要通过命令行上的参数运行。它将在命令行上使用参数-p、-e和-dOnly运行命令行参数-d对不起,-p和-e将被设置如果您需要更多功能,您可以在类中为您正在寻找的特定工作添加另一个函数。希望这有帮助。但我不认为对每个文件使用
main
函数是正确的方法。您可以发送所需命令的映射,而不是发送参数。好的。谢谢你的帮助。我将尝试一下,看看我得到的是什么,它实际上不起作用,因为get_config中的参数将被传递到变量中。如果你看看我的问题,我已经更新了我的代码