Reputation: 4766
I am using terminal command
while ! echo exit | nc 10.0.2.11 9445; do sleep 10; done
in my commandline to lookup port in my remote machine.( it is working fine). I want to do this operation inside my python script. I found subprocess and I want to know that how can I do this with subprocess ?
from subprocess import call
call(["while xxxxxxxxxxxxxxxxxxxxxxxxxxx"])
Upvotes: 0
Views: 236
Reputation: 6317
subprocess.call
does not by default use a shell to run its commands. Therefore, things like while
are unknown commands. Instead, you could pass shell=True
to call
(security risk with dynamic data and user input*) or call the shell directly (the same advice applies):
from subprocess import call
call("while ! echo exit | nc 10.0.2.11 9445; do sleep 10; done", shell="True")
or directly with the shell, this is (a) less portable (because it assumes a specific shell) and (b) more secure (because you can specify what shell is to be used as syntax is not unified over different shells, e.g. csh
vs. bash
, and usage on other shells may lead to undefined or unwanted behaviour):
from subprocess import call
call(["bash", "-c", "while ! echo exit | nc 10.0.2.11 9445; do sleep 10; done"])
The exact argument to the shell to execute a command (here -c
) depends on your shell.
You may want to have a look at the subprocess
docs, especially for other ways of invoking processes. See e.g. check_call
as a way of checking the return code for success, check_output
to get the standard output of the process and Popen
for advanced input/output interaction with the process.
Alternatively, you could use os.system
, which implicitly launches a shell and returns the return code (subprocess.check_call
with shell=True
is a more flexible alternative to this)
* This link is to the Python 2 docs instead of the Python 3 docs used otherwise because it better outlines the security problems
Upvotes: 1