0

I try to call a .py module within another script in python. My question is, how can I perform operations on the second script (script2) within the first one, more specifically, I want to read the df generated by the second script after calling it in the first script.

from subprocess import call
call(["python", "script2.py"])

Thank you

arhr
  • 1,505
  • 8
  • 16
Isa
  • 145
  • 8
  • 2
    Two ways: dump the result of script2.py into a file, and loaded data in your first script, or just change the second script, and make an orerdnary function call with return values – Menglong Li Feb 05 '21 at 09:07

1 Answers1

0

You can always utilise stdout

simple_panda.py

import pandas as pd

if __name__ == '__main__':
    print(pd.DataFrame({"col1":[1,2,3],"colb":[3,4,5]}).to_csv())

jupyter

import subprocess
import pandas as pd

def cmd(cmd:str="ls -al", assertfail=True) :
    up = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, close_fds=True)
    str = [o.rstrip().decode() for o in up.stdout]
    exitcode = up.wait()
    if assertfail: assert exitcode == 0, f"[{exitcode}] {cmd} {str}"
    return exitcode,  str

e, out = cmd("python3 simple_panda.py")
pd.read_csv(io.StringIO("\n".join(out)), index_col=0)

output

col1 colb
0 1 3
1 2 4
2 3 5
Rob Raymond
  • 29,118
  • 3
  • 14
  • 30
  • You really want to [avoid `shell=True`](https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess) whenever you can. This seems like a rather rickety reimplementation of `subprocess.check_output` anyway. – tripleee Feb 05 '21 at 09:53