Reputation: 5
I want to use python achieve following process:
[zz@bts01 ~]$ cd /opt/cdma-msc/
[zz@bts01 cdma-msc]$ ./sccli
SoftCore for CDMA CLI (c) Quortus 2010
RAN> show system
System Configuration
Software version: V1.31
System name: RAN
System location:
Shutdown code:
Emergency call dest:
Current date/time: Tue Feb 27 14:27:41 2018
System uptime: 20h 33m
Auto-provisioning: Enabled
RAN> exit
Bye.
[zz@bts01 cdma-msc]$
Please see above, I want to use python to call this /opt/cdma-msc/rancli process, which will open a secondary shell, and I want to capture the output of command "show license" in that shell. How can I achieve this in python? I tried with subprocess Popen, and was able to call the shell, but cannot enter anything into it. Anyone have some thought?
ran = subprocess.Popen(['/opt/cdma-msc/sccli'], shell = True, stdout = subprocess.PIPE)
hnb = subprocess.Popen(['show system'],stdin=ran.stdout )
above is the python module/command I tried, apparently the second line didn't take the output from first, casue it is calling another shell.
Upvotes: 0
Views: 425
Reputation: 189749
You want the command to be the input to the subprocess you created, not the name of a new subprocess.
If you have a new enough Python, try
output = subprocess.run(['/opt/cdma-msc/sccli'],
stdout = subprocess.PIPE,
input='show system',
check=True, universal_newlines=True).stdout
The result returned by run
is an object which encapsulates the result code and status of the subprocess as well as the output from it. Its stdout
member contains the text produced on standard output.
Unfortunately, run
was only introduced in Python 3.5 but it's enough of an improvement that you might want to not support older versions of Python. If you have to support older versions, the equivalent code is considerably clunkier:
p = subprocess.Popen(['/opt/cdma-msc/sccli'],
stdin=subprocess.PIPE, stdout=subprocess.PIPE)
stdout, stderr = p.communicate('show system')
Here, stdout
is simply a string with the output.
You should generally avoid raw Popen()
unless the higher-level wrappers absolutely cannot do what you want. There is also obviously no need for shell=True
when there are no wildcards, pipelines, rediections, or even argument parsing (you already broke the command line into a list of strings).
Upvotes: 1