CWD 跟踪 — reference/06-bash-engine.md 问题: 命令里可能有 cd,但子进程的 cd 不会影响父进程。 如果用户执行 "cd src && ls",下一条命令应该在 src/ 目录下。 解决方案: 每条命令结尾追加 pwd -P,把当前目录写到临时文件。 命令执行完后读取这个文件,更新 CWD。
()
| 602 | |
| 603 | |
| 604 | def demonstrate_cwd_tracking(): |
| 605 | """CWD 跟踪 — reference/06-bash-engine.md |
| 606 | |
| 607 | 问题: 命令里可能有 cd,但子进程的 cd 不会影响父进程。 |
| 608 | 如果用户执行 "cd src && ls",下一条命令应该在 src/ 目录下。 |
| 609 | |
| 610 | 解决方案: 每条命令结尾追加 pwd -P,把当前目录写到临时文件。 |
| 611 | 命令执行完后读取这个文件,更新 CWD。 |
| 612 | """ |
| 613 | print("\n=== CWD 跟踪机制 ===") |
| 614 | |
| 615 | cwd_file = tempfile.mktemp(prefix="claude-cwd-") |
| 616 | |
| 617 | user_command = "cd /tmp && echo 'now in /tmp'" |
| 618 | # 真实的命令包装: |
| 619 | tracked_command = f"{user_command} && pwd -P >| {cwd_file}" |
| 620 | |
| 621 | print(f"用户命令: {user_command}") |
| 622 | print(f"追踪命令: {tracked_command}") |
| 623 | |
| 624 | # 执行 |
| 625 | result = subprocess.run( |
| 626 | ["sh", "-c", tracked_command], |
| 627 | capture_output=True, text=True |
| 628 | ) |
| 629 | print(f"输出: {result.stdout.strip()}") |
| 630 | |
| 631 | # 读取新的 CWD |
| 632 | try: |
| 633 | with open(cwd_file, "r") as f: |
| 634 | new_cwd = f.read().strip() |
| 635 | print(f"新的 CWD: {new_cwd}") |
| 636 | os.unlink(cwd_file) |
| 637 | except FileNotFoundError: |
| 638 | print("CWD 文件不存在(命令可能失败了)") |
| 639 | |
| 640 | |
| 641 | def demonstrate_auto_background(): |
no test coverage detected