1

I can open a linux terminal via python via

import subprocess
subprocess.run('xterm')

or

subprocess.run('gnome-terminal')

once these are open, or when they open, how can I use python to pass them input?

in case 1, how can I tell them to immediately on open, run "python3 "filename""

and if possible, case 2, how can I continue to give commands and input, in the case that the python file requires user input and I would like to automate it?

AlbinoRhino
  • 467
  • 6
  • 23
  • Does this answer your question? [Understanding Popen.communicate](https://stackoverflow.com/questions/16768290/understanding-popen-communicate) – buran Feb 01 '22 at 20:49
  • so far, it is not behaving as I wish. Im gonna try some other answers now, then circle back to this if needed – AlbinoRhino Feb 01 '22 at 21:14

1 Answers1

0

you can use subprocess.check_output to get immediately output

import subprocess
output = subprocess.check_output(['cat', 'test.txt'])
print(f"output file {output}")

you can use pexpect to continue to communicate with the terminal example:

# Import pexpect module

import pexpect

import os


# Run simple command

print("The current working directory: \n%s" %pexpect.run('pwd').decode("utf-8"))


# Retrieve the information of a particular file

filename = input("Enter an existing filename: ")

# Check the file exists or not

if os.path.exists(filename):

    output = pexpect.run("ls -l "+filename, withexitstatus=0)

    print("Information of a particular file: \n%s" %output.decode("utf-8"))

else:

    print("File does not exist.")


# Retrieve the files and folder of a particular directory using ssh command

output = pexpect.run("ssh fahmida@localhost 'ls web/'", events={'(?i)password':'12345\n'})

print("\nThe output of ssh command: \n%s" %output.decode("utf-8"))
tomerar
  • 805
  • 5
  • 10