如何将两个python代码粘合(缝合)在一起?

时间:2019-06-26 22:05:37

标签: python python-3.x

我想知道将来自不同python文件的代码组合到一个新的python文件中的最佳方法是什么。 假设第一个文件1.py包含:

def(...):
    a=1
    b=2
    return c=a+b

另一个文件2.py包含:

def(...):
    d = 4
    e = c*d
    return e

现在假设您有一个最终文件final.py,您希望将1.py2.py中的所有代码按特定的操作顺序逐字复制到该文件中,看起来如下。请注意,我了解我们可以在python中使用import函数,但是在这种情况下,我希望将某些定义的整个文本复制到新的python代码中。换句话说,将不同文件中的代码粘合在一起以构建新文件。

final.py:

def(...):
    a=1
    b=2
    return c=a+b
def(...):
    d = 4
    e = c*d
    return e

编辑:

上面重新描述:如果文件1具有100个定义,文件2具有100个定义,但是我希望将每个文件中的特定定义复制到文件3中,并以指定的顺序显示全文和语法。

4 个答案:

答案 0 :(得分:6)

如果您使用的是Unix shell:

cat 1.py 2.py > 3.py

答案 1 :(得分:2)

这是OS工具(而非Python)中的问题。您只需串联两个文本文件。您可以在操作系统中查找操作方法。如果您有喜欢的文本编辑器,请打开一个新文件。读入1.py;在其底部,读入2.py;将结果另存为3.py

答案 2 :(得分:2)

您可以在python本身中做到这一点!

假设您有所需定义的列表:

import re

files = ["1.py", "2.py"]  # ......
defs = ["func_1", "func_2"]

with open("final.py", 'w') as out_f:
    for path in files:
        with open(path) as in_f:
            lines = in_f.readlines()
            i = 0
            while i < len(lines):
                line = lines[i]
                r = re.search("^def\s+(\w+)\(", line)
                if r:
                    if r.group(1) in defs:
                        out_f.write(line)
                        while i < len(lines) and not re.search("^\w", lines[i+1]): # relying on python's indent syntax
                            out_f.write(lines[i+1])
                            i += 1
                i += 1

答案 3 :(得分:1)

这有点失控,但是我试图用适当的结构重新实现它,这就是我想出的:

#!/usr/bin/env python3

import re

def extract_functions(code_lines, names):

    # Checks if given line contains code
    def is_code_line(line):
        stripped = line.strip()
        if stripped.startswith('#'):
            return False
        if len(stripped) == 0:
            return False
        return True

    # Retreives the indentation pattern of given line
    def get_indentation(line):
        num_indent_chars = len(line) - len(line.lstrip())
        return line[:num_indent_chars]

    # Returns the function name if line has a function definition, else None
    function_name_extractor = re.compile(r'^def\s+(\w+)\s*\(')
    def get_function_name(line):
        match = function_name_extractor.match(line)
        if match is None:
            return None
        return match.group(1)

    extracted = list()
    in_function = False 

    for num, line in enumerate(code_lines):
        # Non-code lines don't end or start functions,
        # even if their indentation is wrong
        if not is_code_line(line):
            continue

        if in_function:
            # If this is the first line of the function, store the indentation
            if function_indent == None:
                function_indent = get_indentation(line)

            # If we match the indentation, we are still in the same function.
            # Store that the function includes the current line
            if line.startswith(function_indent):
                function_end = num + 1

            # If we detect the end of the current function, extract the
            # function lines and store them in 'extracted'.
            else:
                extracted.extend(code_lines[function_start:function_end])
                in_function = False

        # If we are currently not inside a function, check if current line
        # contains a function start.
        # Needs a separate 'if' and not just an 'else' because this code
        # needs to run if the previous 'if' detected the end of a function.
        if not in_function:
            line_function_name = get_function_name(line)
            if line_function_name is not None and line_function_name in names:
                in_function = True
                function_start = num
                function_end = num + 1
                function_indent = None

    # One more extraction if the function reaches all the way to the last line
    if in_function:
        extracted.extend(code_lines[function_start:function_end])

    return extracted




with open('1_and_2.py', 'w') as out_fil:
    with open('1.py', 'r') as fil:
        for line in extract_functions(fil.readlines(), ['func_a1', 'func_b1']):
            out_fil.write(line) 
        # It isn't guaranteed that our last line in the file ends with a newline,
        # Therefore add one manually
        out_fil.write('\n')
    with open('2.py', 'r') as fil:
        for line in extract_functions(fil.readlines(), ['func_a2', 'func_b2']):
            out_fil.write(line) 
        out_fil.write('\n')