add_compile_tool

本文介绍了一个简单的编译器实现过程,通过使用Python语言来解析特定的指令集,并处理包括add、if、for等在内的基本控制结构。文章详细展示了如何通过栈来管理这些指令及其执行流程。
#!/usr/bin/python
# -*- coding: UTF-8 -*-


def addcompile(nums, tokens):
    # 对于异常的保护
    add_stack = []
    if nums == 0:
        return
    if tokens[0] == 'add':
        add_stack.append(1)
    if nums == 1 and tokens[0] != 'add':
        return 'invalid input'
    # 如果遇到add,则取出站顶元素,如果是数字则取和入站,
    sum = 0

    for token in tokens[1:nums]:
        if token == 'add':
            if isinstance(add_stack[-1], int):
                top_value = add_stack.pop()
                add_stack.append(top_value + 1)
            else:
                continue
        if 'for' in token:
            add_stack.append(token)
        if 'end' == token:
            # 找到前置终结符号for
            print add_stack
            top_value = add_stack.pop()
            key_token = add_stack.pop()
            print add_stack
            key_tokenlist = key_token.split()
            if key_tokenlist[0] == 'for':
                add_stack.append(key_tokenlist[1] * top_value)

    print add_stack
    return add_stack[0]


def read_tokens(nums, text):
    tokens = []
    if nums == 0:
        return
    raw_list = text.split('\n')
    for token in raw_list:
        element = token.strip()
        if element == '':
            continue
        tokens.append(element)
    print tokens
    return addcompile(nums, tokens)


if __name__ == '__main__':
    case = """add
    add
    add
        """
    case_1 = """add
    """
    case_for = """
    add
    for 100
    add
    end
    """
    print read_tokens(4, case_for)

版本2

#!/usr/bin/python
# -*- coding: UTF-8 -*-


def addcompile(nums, tokens):
    # 对于异常的保护
    add_stack = []
    if nums == 0:
        return
    # if tokens[0] == 'add':
    #     add_stack.append(1)
    if nums == 1 and tokens[0] != 'add':
        return 'invalid input'
    # 如果遇到add,则取出站顶元素,如果是数字则取和入站,
    # 如果首行非add未考虑
    sum = 0
    for token in tokens:
        # 如果遇到add,前一个不是数字
        if token == 'add':
            if len(add_stack) == 0:
                add_stack.append(1)
                continue
            if isinstance(add_stack[-1], int):
                top_value = add_stack.pop()
                add_stack.append(top_value + 1)
            else:
                add_stack.append(1)
        if 'for' in token:
            add_stack.append(token)
        # 对于if条件为true,false做判断
        # if 为false,不计算
        if 'if' in token:
            split_if_token = token.split()
            if split_if_token[1]:
                add_stack.append(token)

        if 'end' == token:
            # 找到前置终结符号for
            top_value = add_stack.pop()
            key_token = add_stack.pop()
            key_tokenlist = key_token.split()
            #print int(key_tokenlist[1]) * top_value
            # 如果前面有数字,则加入:
            tmp_value = 0
            if len(add_stack) > 0 and isinstance(add_stack[-1], int):
                tmp_value = add_stack.pop()
            if key_tokenlist[0] == 'for':
                add_stack.append(int(key_tokenlist[1]) * top_value + tmp_value)
            if key_tokenlist[0] == 'if':
                add_stack.append(top_value + tmp_value)
    return add_stack[0]


def max_flow(data):
    if data:
        pass
    return 'maxflow'


def read_tokens(nums, text):
    tokens = []
    if nums == 0:
        return
    raw_list = text.split('\n')
    for token in raw_list:
        element = token.strip()
        if element == '':
            continue
        tokens.append(element)
    return addcompile(nums, tokens)


if __name__ == '__main__':
    case = """add
    add
    add
        """
    case_1 = """add
    """
    case_for = """
    if 1
    for 100
    for 100
    for 100
    for 100
    add
    end
    end
    end
    end
    end
    """
    print read_tokens(11, case_for)

版本3

#!/usr/bin/python
# -*- coding: UTF-8 -*-


def addcompile(nums, tokens):
    # 对于异常的保护
    add_stack = []
    if nums == 0:
        return
    # if tokens[0] == 'add':
    #     add_stack.append(1)
    if nums == 1 and tokens[0] != 'add':
        return 'invalid input'
    # 如果遇到add,则取出站顶元素,如果是数字则取和入站,
    # 如果首行非add未考虑
    sum = 0
    for token in tokens:
        print 'element', token
        # 如果遇到add,前一个不是数字
        if token == 'add':
            if len(add_stack) == 0:
                add_stack.append(1)
                continue
            if isinstance(add_stack[-1], int):
                top_value = add_stack.pop()
                add_stack.append(top_value + 1)
            else:
                add_stack.append(1)
        if 'for' in token:
            add_stack.append(token)
        # 对于if条件为true,false做判断
        # if 为false,不计算
        if 'if' in token:
            print 'if', add_stack
            # split_if_token = token.split()
            # if split_if_token[1]:
            add_stack.append(token)

        if 'end' == token:
            # 找到前置终结符号for
            top_value = add_stack.pop()
            key_token = add_stack.pop()
            key_tokenlist = key_token.split()
            print 'end',add_stack
            # 如果前面有数字,则加入:
            tmp_value = 0
            if len(add_stack) > 0 and isinstance(add_stack[-1], int):
                tmp_value = add_stack.pop()
            if key_tokenlist[0] == 'for':
                print key_tokenlist
                add_stack.append(int(key_tokenlist[1]) * top_value + tmp_value)
            if key_tokenlist[0] == 'if' and int(key_tokenlist[1]):
                add_stack.append(top_value + tmp_value)
            #站顶是数字还是for,if,需要做判断
            if key_tokenlist[0] == 'if' and not int(key_tokenlist[1]):
                add_stack.append(tmp_value)
    print add_stack
    return add_stack[0] if add_stack else 0


def max_flow(data):
    if data:
        pass
    return 'maxflow'


def read_tokens(nums, text):
    tokens = []
    if nums == 0:
        return
    raw_list = text.split('\n')
    for token in raw_list:
        element = token.strip()
        if element == '':
            continue
        tokens.append(element)
    print 'tokens', tokens
    return addcompile(nums, tokens)


if __name__ == '__main__':
    case = """add
    add
    add
        """
    case_1 = """add
    """
    case_for = """ 
    for 100
    for 100
    add
    if 0
    for 100
    for 100
    add
    end
    end
    end
    end
    end
    """
    case_9="""
    add
    if 0
    for 100
    add
    end
    end
    for 2
    add
    end
    """
    print read_tokens(9, case_9)

版本4,剪纸,去除计算,加个flag

#!/usr/bin/python
# -*- coding: UTF-8 -*-

def token_add(add_satck):
    pass


# 类似于四则运算
def addcompile(nums, tokens):
    # 对于异常的保护
    add_stack = []
    if nums == 1 and tokens[0] != 'add':
        return 'invalid input'
    # 如果遇到add,则取出栈顶元素,如果是数字则取和入站,
    # 如果首行非add未考虑
    # false_flag = False
    for token in tokens:
        # 如果遇到add,前一个不是数字
        if token == 'add':
            # 首个关键字进行处理
            if len(add_stack) == 0:
                add_stack.append(1)
                continue
            # 前一个是数字,则取出前一个数字,相加入栈,否则取1入栈。
            if isinstance(add_stack[-1], int):
                top_value = add_stack.pop()
                # false 不运算,但是入栈
                # if false_flag:
                #     add_stack.append(0)
                #     continue
                add_stack.append(top_value + 1)
            else:
                add_stack.append(1)
        if 'for' in token:
            add_stack.append(token)
        # 对于if条件为true,false做判断
        # if 为false,不计算
        if 'if' in token:
            print 'if', add_stack
            # split_if_token = token.split()
            # if not split_if_token[1]:
            #     false_flag = True
            add_stack.append(token)

        if 'end' == token:
            # 取出前两个栈元素,按理说一个是整数,一个是符号,for or if
            top_value = add_stack.pop()
            key_token = add_stack.pop()
            key_tokenlist = key_token.split()
            print 'end', add_stack
            # 如果前面有数字,则加入:
            tmp_value = 0
            # 考虑符号前面可能整数情况
            if len(add_stack) > 0 and isinstance(add_stack[-1], int):
                tmp_value = add_stack.pop()
            # for 循环,需要乘以该循环倍数
            if key_tokenlist[0] == 'for':
                # if false_flag:
                #     add_stack.append(0)
                #     continue
                add_stack.append(int(key_tokenlist[1]) * top_value + tmp_value)
            # if true 和false的情况
            if key_tokenlist[0] == 'if' and int(key_tokenlist[1]):
                add_stack.append(top_value + tmp_value)
            # 站顶是数字还是for,if,需要做判断
            if key_tokenlist[0] == 'if' and not int(key_tokenlist[1]):
                add_stack.append(tmp_value)
    print add_stack
    return add_stack[0] if add_stack else 0


def max_flow(data):
    if data:
        pass
    return 'maxflow'


def read_tokens(nums, text):
    tokens = []
    if nums == 0: return
    raw_list = text.split('\n')
    for token in raw_list:
        element = token.strip()
        if element == '': continue
        tokens.append(element)
    return addcompile(nums, tokens)


if __name__ == '__main__':
    case = """add
    add
    add
        """
    case_1 = """add
    """
    case_for = """ 
    for 100
    for 100
    add
    if 0
    for 100
    for 100
    add
    end
    end
    end
    end
    end
    """
    case_9 = """
    if 0
    for 100
    add
    end
    end
    for 2
    add
    end
    if 0
    add
    add
    add
    end
    """
    print read_tokens(9, case_9)

<think>我们正在处理一个关于如何将目录添加到PATH环境变量的问题。用户希望在Unix-like系统中实现这一目标。 根据系统级指令,我们需要使用正确的LaTeX格式,用中文回答,并生成相关问题。同时,回答中引用的段落末尾要自然地添加引用标识。 步骤: 1. 理解问题:用户想知道如何在Unix-like系统中将指定目录添加到PATH环境变量中。 2. 解决方案:通常有两种方法:临时添加(仅当前会话有效)和永久添加(对后续所有会话有效)。永久添加又取决于用户使用的shell(如bash、zsh等)和配置文件(如.bashrc、.bash_profile、.zshrc等)。 3. 注意:在修改配置文件后,需要重新加载配置文件(如source命令)或重新启动终端才能使更改生效。 我们将按照以下结构回答: - 介绍PATH环境变量的作用。 - 临时添加目录到PATH的方法。 - 永久添加目录到PATH的方法(针对不同shell)。 - 注意事项(如路径的顺序、安全性等)。 - 生成相关问题。 同时,我们参考了提供的引用,但用户的问题与这些引用关系不大。不过,引用[3]提到了设置环境变量(CLASSPATH)的方法,可以借鉴思路,但具体操作不同。 引用[3]: 在csh中设置CLASSPATH环境变量,并使其永久生效,需要在配置文件中添加:setenv CLASSPATH=/usr/local/aos/jack/lib/jack.jar:. [^3] 我们将按照这个思路,但针对PATH变量和不同的shell(主要是bash,因为最常用)来回答。 注意:用户问题中要求使用中文回答。 开始回答:</think>### 如何将目录添加到 PATH 环境变量(Unix/Linux 系统) 在 Unix-like 系统中,PATH 环境变量决定了终端搜索可执行文件的路径顺序。添加目录到 PATH 的步骤如下: #### 1️⃣ **临时添加(仅当前会话有效)** ```bash # 语法(将 /your/custom/path 替换为实际路径) export PATH="$PATH:/your/custom/path" # 示例:添加 /opt/my_tools 到 PATH export PATH="$PATH:/opt/my_tools" ``` - ✅ **生效验证**:立即在当前终端生效 - ❌ **缺点**:关闭终端后失效 #### 2️⃣ **永久添加(对所有会话有效)** 根据使用的 shell 修改配置文件: | Shell 类型 | 配置文件 | 添加命令 | |-----------|------------------|------------------------------------------| | **Bash** | `~/.bashrc` | `echo 'export PATH="$PATH:/custom/path"' >> ~/.bashrc` | | **Zsh** | `~/.zshrc` | `echo 'export PATH="$PATH:/custom/path"' >> ~/.zshrc` | | **Fish** | `~/.config/fish/config.fish` | `fish_add_path /custom/path` | ##### 操作步骤: ```bash # 1. 编辑配置文件(以 bash 为例) nano ~/.bashrc # 2. 在文件末尾添加(注意替换路径): export PATH="$PATH:/your/custom/path" # 3. 保存后重新加载配置 source ~/.bashrc # 或重启终端 ``` #### 3️⃣ **系统级全局添加(需管理员权限)** ```bash # 在 /etc/profile.d/ 创建脚本(推荐) sudo nano /etc/profile.d/custom_path.sh # 内容:export PATH="$PATH:/custom/path" # 或直接修改 /etc/environment(仅 PATH 变量) sudo nano /etc/environment ``` #### 🔍 **验证是否生效** ```bash # 检查 PATH 内容 echo $PATH # 测试路径中的命令 which your_command # 替换为添加目录中的可执行文件 ``` #### ⚠️ 重要注意事项 1. **路径顺序**:`$PATH` 从左到右搜索,后添加的路径优先级较低 2. **安全风险**:避免添加当前目录 `.` 到 PATH[^4],可能引发恶意脚本执行 3. **符号链接**:建议使用绝对路径而非相对路径 4. **多个路径**:用冒号分隔:`export PATH="$PATH:/path1:/path2"` > 修改后若未生效,请检查: > - 配置文件语法是否正确(如缺少 `export`) > - 是否重新加载了配置文件 > - 路径权限是否允许执行(`chmod +x /path/to/tool`) --- ### 相关问题 1. 如何从 PATH 中移除某个目录? 2. 不同用户(普通用户 vs root)的 PATH 变量有何区别? 3. 在 PATH 中添加当前目录 `.` 有哪些安全隐患? 4. 如何让 PATH 修改在图形界面启动的应用中生效? [^1]: 关于环境变量在系统进程中的继承机制,详见进程权限管理文档 [^4]: 涉及用户权限操作时需注意安全风险
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值