0

I am tasked with automating the process of running bash script using python. Unfortunately I am not responsible for the bash script itself, so I have no idea how it works. When I run the script directly in the terminal using source adastralrc.sh , it works perfectly and gives the desired output.

However when I try to get python to run the file by using subprocess and the exact same command as the argument:

import subprocess

commands = ['source' , 'adastralrc.sh']
p = subprocess.run(commands)

I get the following error:

Traceback (most recent call last):
  File "test2.py", line 6, in <module>
    p = subprocess.call(commands)
  File "/usr/lib64/python3.6/subprocess.py", line 287, in call
    with Popen(*popenargs, **kwargs) as p:
  File "/usr/lib64/python3.6/subprocess.py", line 729, in __init__
    restore_signals, start_new_session)
  File "/usr/lib64/python3.6/subprocess.py", line 1364, in _execute_child
    raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] No such file or directory: 'source adastralrc.sh': 'source adastralrc.sh'
(venv-c3dns) [vivegab@adl20213d1bld01 vivegab] (cth01/dns_mano_dev)

I am fairly inexperienced with subprocess but I thought that it was just an improved version of os.system() and should just enter the commands as if they were being typed by a person. So why am I getting the error above and what can be done to fix this?

Maurio
  • 172
  • 3
  • 13
  • 3
    Does this answer your question? [Calling the "source" command from subprocess.Popen](https://stackoverflow.com/questions/7040592/calling-the-source-command-from-subprocess-popen) – Maurice Meyer May 10 '21 at 14:39

1 Answers1

1
def shell_source(script):
    """Sometime you want to emulate the action of "source" in bash,
    settings some environment variables. Here is a way to do it."""
    import subprocess, os
    pipe = subprocess.Popen(". %s; env" % script, stdout=subprocess.PIPE, shell=True)
    output = pipe.communicate()[0]
    env = dict((line.split("=", 1) for line in output.splitlines()))
    os.environ.update(env)

shell_source(adastralrc.sh)

Looks like a duplicate

Avinash_cdns
  • 165
  • 7
  • This works. But the shell script also requires a password to be input at some point. Any idea how to make subprocess enter this password when prompted? – Maurio May 11 '21 at 12:25