Search code examples
pythonsubprocessoutputstdout

Python Subprocess.Run() outputcontrol


Hellow exports.

I am new to python. and to explain my problem I simply the script.

I built 2 python files. The first one is like the below file name is "random.py"

p1 =[1,2,'bob']
p2 =[1,2,'eric']
p3 =[2,1,'dimitar']
p4 =[2,2,'kyle']

l1 = [p1,p2,p3,p4]

print(l1)

and the result will be like this : (double list)

[[1, 2, 'bob'], [1, 2, 'eric'], [2, 1, 'dimitar'], [2, 2, 'kyle']]

The Second file is for running the first python file. using Run() function.

import subprocess
res = subprocess.run("python random.py", shell=True,capture_output=True )
print(res.stdout)

and the result will be like this :

b"[[1, 2, 'bob'], [1, 2, 'eric'], [2, 1, 'dimitar'], [2, 2, 'kyle']]\r\n"

My question is that how I can to get Result same as first result (and if it's possible, I just want to get double List but not string)

My basic idea is to run some program and get the output it creates. in this case, I run the first python file. and get output(l1) from the Second python file.


Solution

  • import subprocess
    import ast
    res = subprocess.run("python random.py", shell=True, capture_output=True)
    k = res.stdout.decode()
    newlist = ast.literal_eval(k)
    print(newlist)
    print(type(newlist))
    

    you can try to use this code. result