Home > front end >  How to set an environment variable in Pexpect spawn without getting an exception
How to set an environment variable in Pexpect spawn without getting an exception

Time:06-02

I am trying to set my HOME environment variable on an Ubuntu system in a pexpect.spawn() call, but am getting an exception. Example below:

import pexpect
pexpect.spawn('HOME=/home/myuser && <other command that pexpect is ok with>', cwd='/home/myuser/Desktop')

ExceptionPexpect:The command was not found or was not executable: HOME=/home/myuser

This seems to be an error in pexpect/pty_spawn.py. Any insight into this exception and how to resolve it in this context?

I've also tried running it in a bash script, such as

set_home.sh
#!/bin/bash
HOME=/home/myuser
<run other command that pexpect is ok with>

pexpect.spawn('./set_home.sh')

but then I'm facing the issue that it doesn't hold the HOME value for future commands so it doesn't take the effect that I need it to for the next command. I'm not sure whether this is a better path to take, but at the moment I can't get either approach to work.

CodePudding user response:

This seems to be an error in pexpect/pty_spawn.py

This is an error in your code. The documentation for pexpect.spawn says:

Remember that Pexpect does NOT interpret shell meta characters such as
redirect, pipe, or wild cards (``>``, ``|``, or ``*``). This is a
common mistake.  If you want to run a command and pipe it through
another command then you must also start a shell.

You're trying to use shell script syntax (VAR=value command ...), but pexpect.spawn doesn't use a shell.

If you want to set an environment variable for a command run with pexpect.spawn, just use the env parameter:

import os
import pexpect

pexpect.spawn('<other command that pexpect is ok with>', 
    cwd='/home/myuser/Desktop', 
    env=os.environ | {'HOME': '/home/myuser'})

The above example assumes Python 3.9 or later to add a value from HOME to the existing environment. If we were to write instead:

pexpect.spawn('<other command that pexpect is ok with>', 
    cwd='/home/myuser/Desktop', 
    env={'HOME': '/home/myuser'})

Then the command would start with only a single environment variable.

CodePudding user response:

You can explicitly use bash if you need to use shell syntax:

cmd = 'HOME=/home/myuser && ...'
pexpect.spawn('bash', ['-c', cmd], cwd=...)
  • Related