0

I have a simple shell file that has this:

#! /bin/bash
echo "Hello"
echo "Full Name: $1";
echo "Age: $2";

I am calling this file from the python jupyter notebook like this:

import subprocess
filePath = 'testScript.sh'
arg1 = 'John Doe'
arg2 = 2
subprocess.run([filePath, arg1, str(arg2)], shell=True, check=True)

The file runs fine and I get this output:

CompletedProcess(args=['testScript.sh', 'John Doe', '2'], returncode=0)

While the code is running, it pops open a command line window and the output flashes for a second before the window closes. I was wondering is there a way to print output into python rather than only seeing the output in the command line window? Or is there a way to prevent the command line window from closing so I can see the output?

wjandrea
  • 28,235
  • 9
  • 60
  • 81
user5977110
  • 85
  • 1
  • 3
  • 9

2 Answers2

1

You can pass the capture_output keyword-argument to the subprocess.run() function. Like this:

subprocess.run(["ls", "-a"], capture_output=True)

This would return a CompletedProcess instance with a property called stdout, which contains all the output. In this case all the files and directories in the working directory.

Hyalunar
  • 102
  • 4
0

You can write it to a file:

subdir = ... #<========= Path of executable

fout = open(os.path.join(subdir, "out.txt"), "w")
ferr = open(os.path.join(subdir, "err.txt"), "w")
p = subprocess.run(file_to_run, cwd=subdir, stdout=fout, stderr=ferr,)

Alternatively, you could add a pause at the end of your script (in Windows/DOS batch files). Ref: How to prevent auto-closing of console after the execution of batch file

learner
  • 603
  • 1
  • 3
  • 15