I have a situation where I need to mock an executable (pip) with a shell script I wrote (mock_pip) for a unit test, so I use the subprocess module to get access to the shell. I've tried a lot of things like:
subprocess.Popen("alias pip='/some/dir/mock_pip'", shell=True) # Create alias
subprocess.Popen("pip", shell=True) # Try to use new alias, but still points towards real pip instead
subprocess.Popen("alias pip='/some/dir/mock_pip'"; "pip", shell=True)
# Once again it uses the real pip instead of mock
I even tried this method by changing the ~/.bashrc file in my home directory (also during the unit test using subprocess) but that doesn't work either.
I'm imagining the problem is that subprocess erases the environment after every command that is called, meaning my alias doesn't exist when I try calling it.
How can I cause mock_pip to be used instead of pip in a bash script started from my Python process?
shell=True, but I guess it will not carry over for different popens. Why not make a python function that calls the appropriate pip?subprocessdoes not erase the environment, the operating system does. Add the alias to.bashrc, but aliases are not normally expanded in scripts, they are a support nightmare and generally considered to be bad practice (functions are preferred), you have toshopt -s expand_aliases(again, in.bashrc).shell=True. What do you mean create a function to call the appropriate pip though?subprocess.Popen()argument list itself.subprocess.Popen(..., env={'PATH': '/directory/with/new/stub:' + os.environ['PATH']})subprocess.Popen, rather than about alias persistence.