I have a python script that works perfectly in the Thonny IDE, but fails in terminal

  linux, pexpect, python-3.x, raspberry-pi, raspbian

Firstly, here’s the code:

import re, pexpect, os

file = '/home/homebridge/flags/Restart.flag'
f = open(file, 'w')
os.system("sudo systemctl stop homebridge")
os.system("sudo chmod -R a+rwx /var/lib/homebridge")
child = pexpect.spawn('tuya-cli wizard')
data = child.read()
data = data.decode("utf-8")
devices = data.split('},')
devicesO = []
class device:
    name = ""
    ID = ""
    key = ""
    def __init__(self, name, ID, key):
        self.name = name
        self.ID = ID
        self.key = key
    def __lt__(self, other):
        return self.name < other.name

for i in devices:

    n = re.search("name: '(.*)'", str(i)).group(1)
    I = re.search("id: '(.*)'", str(i)).group(1)
    k = re.search("key: '(.*)'", str(i)).group(1)
    if n != ("Clock"):
        devicesO.append(device(n, I, k))

entries = []
for device in devicesO:
    if "phone charger" not in device.name:
        s1 = "{n"name": "" + device.name + "",n"id": "" + device.ID + "",n"key": "" + device.key + "","
        s2 = """
"type": "RGBTWLight",
"manufacturer": "SmartLife",
"model": "Light",
"dpPower": "20",
"dpMode": "21",
"dpBrightness": "22",
"dpColorTemperature": "23",
"dpColor": "24",
"colorFunction": "HSB",
"scaleBrightness": 1000
        s1 = "{n"name": "" + device.name + "",n"id": "" + device.ID + "",n"key": "" + device.key + "","
        s2 = """
"type": "Outlet",
"manufacturer": "SmartLife",
"model": "Outlet",
"dpPower": "1"
    entries.append(s1 + s2)
string = ",n".join([str(entry) for entry in entries])
config = open('/var/lib/homebridge/config.json', 'r+')
x = config.read()
x = re.sub(""TuyaLan",n.*"devices": [((.|n)*?)]", ""TuyaLan",n"devices": [n" + string + "n]", x)
#x = re.sub(""TuyaLan",n.*"devices": [((.|n)*?)]", ""TuyaLan",n.*"devices": [nTESTn]", x)
config = open('/var/lib/homebridge/config.json', 'w+')
config = open('/var/lib/homebridge/config.json', 'r+')
print (config.read())
os.system("sudo systemctl restart homebridge")

This executes as expected in the IDE, stopping the homebridge service, pulling relevant data from the tuya-cli utility, regex and text replacement, all of it. However, when I try and run it in the terminal without sudo, the first regex search returns an empty object and the script fails. When I run it with sudo, it stalls for a while then times out on the pexpect step at the beginning. I’ve researched before posting, but I have no clue how to solve this one. It doesn’t appear to be a path issue, I used pip3 to install both re and pexpect, and os is obviously packaged with the raspbian install. Any clues would be great.
Error without sudo:

[email protected]:~ $ /home/homebridge/scripts/updateConfig.py
Traceback (most recent call last):
  File "/home/homebridge/scripts/updateConfig.py", line 34, in <module>
    n = re.search("name: '(.*)'", str(i)).group(1)
AttributeError: 'NoneType' object has no attribute 'group'

With sudo:

[email protected]:~ $ sudo /home/homebridge/scripts/updateConfig.py
Traceback (most recent call last):
  File "/home/homebridge/scripts/updateConfig.py", line 10, in <module>
  File "/usr/local/lib/python3.7/dist-packages/pexpect/spawnbase.py", line 344, in expect
    timeout, searchwindowsize, async_)
  File "/usr/local/lib/python3.7/dist-packages/pexpect/spawnbase.py", line 372, in expect_list
    return exp.expect_loop(timeout)
  File "/usr/local/lib/python3.7/dist-packages/pexpect/expect.py", line 181, in expect_loop
    return self.timeout(e)
  File "/usr/local/lib/python3.7/dist-packages/pexpect/expect.py", line 144, in timeout
    raise exc
pexpect.exceptions.TIMEOUT: Timeout exceeded.
<pexpect.pty_spawn.spawn object at 0x766c4510>
command: /usr/bin/tuya-cli
args: ['/usr/bin/tuya-cli', 'wizard']
buffer (last 100 chars): b'x1b[32m?x1b[39m x1b[1mThe API key from tuya.com:x1b[22mx1b[0m x1b[0mx1b[29Dx1b[29C'
before (last 100 chars): b'x1b[32m?x1b[39m x1b[1mThe API key from tuya.com:x1b[22mx1b[0m x1b[0mx1b[29Dx1b[29C'
after: <class 'pexpect.exceptions.TIMEOUT'>
match: None
match_index: None
exitstatus: None
flag_eof: False
pid: 1470
child_fd: 5
closed: False
timeout: 30
delimiter: <class 'pexpect.exceptions.EOF'>
logfile: None
logfile_read: None
logfile_send: None
maxread: 2000
ignorecase: False
searchwindowsize: None
delaybeforesend: 0.05
delayafterclose: 0.1
delayafterterminate: 0.1
searcher: searcher_re:
    0: re.compile(b'rn')

Source: Python-3x Questions