You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中tn.write()双括号问题及执行Bash命令报错咨询

Hey there, let's work through these two tn.write() issues you're facing!

1. Handling Double Parentheses in tn.write()

When you need to send commands containing double parentheses (like Bash arithmetic expressions ((...))) via tn.write(), the main goal is to make sure Python doesn't mangle the parentheses before they reach the remote shell. Here's how to do it right:

  • Use raw strings to avoid accidental escaping: Raw strings (prefixed with r) tell Python not to interpret any special characters inside, so your parentheses stay exactly as you write them. For example:
    # Send a Bash arithmetic calculation command
    tn.write(r'echo $((10 + 5))\n')
    
  • Triple quotes for multi-line commands: If your command spans multiple lines and includes double parentheses, triple quotes let you write the command exactly as you would in a Bash terminal, preserving formatting:
    tn.write('''
    if (( $count > 10 )); then
        echo "Count is too high"
    fi\n
    ''')
    
  • Don't forget the newline: Terminal shells rely on a newline to execute commands, so always append \n at the end of your string to trigger execution.
2. Fixing the syntax error: a=$' unexpected` Issue

That error usually happens when the remote shell receives an incomplete or mangled version of your command. Let's break down the most common fixes:

Common Causes & Solutions:

  • You're using an f-string by accident: If you wrapped the command in an f-string (like f'a=$(lr 2>logp.txt)'), Python will try to parse $(lr ...) as a Python expression, which completely breaks the command. Stick to regular strings or raw strings instead:
    # ❌ Bad: f-string will mangle the $() syntax
    # tn.write(f'a=$(lr 2>logp.txt)\n')
    
    # ✅ Good: Regular string
    tn.write('a=$(lr 2>logp.txt)\n')
    
    # ✅ Also good: Raw string
    tn.write(r'a=$(lr 2>logp.txt)\n')
    
  • Missing newline at the end: Without a \n, the remote shell will wait for more input instead of executing the command, leading to unexpected syntax errors. Always append \n to tell the shell to run the command.
  • Remote shell is not Bash: If the default shell on the remote machine is sh (instead of bash), it might have limited support for $() syntax. Force the command to run with Bash explicitly:
    tn.write('bash -c "a=$(lr 2>logp.txt)"\n')
    
  • Extra whitespace or typos: Double-check that your command doesn't have trailing spaces or typos. The original command a=$(lr 2>logp.txt) is valid, but any extra characters can throw off the shell's parsing.

内容的提问来源于stack exchange,提问作者lin Joe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:00:25