Reputation: 633
I am trying to execute a bash
command in python
The bash command I want to execute is: kubectl get ns | grep -E '(^|\s)OK($|\s)'
And in python I do this like this:
is_namespace_exists = subprocess.call(["kubectl", "get", "ns", "|", "grep", "-E", "\'(^|\s)"+NAMESPACE+"($|\s)\'"])
and
is_namespace_exists = subprocess.call(["kubectl", "get", "ns", "|", "grep", "-E", "'(^|\s)"+NAMESPACE+"($|\s)'"])
But I get this error:
unknown shorthand flag: 'E' in -E
Can someone tell me what is going wrong?
Upvotes: 0
Views: 2542
Reputation:
The following code should work:
import subprocess
NAMESPACE = "..." # Define NAMESPACE variable here
proc1 = subprocess.Popen(['kubectl', 'get', 'ns'], stdout=subprocess.PIPE)
proc2 = subprocess.Popen(["grep", "-E", "\'(^|\s)"+NAMESPACE+"($|\s)\'"], stdin=proc1.stdout, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
proc1.stdout.close() # Allow proc1 to receive a SIGPIPE if proc2 exits.
out, err = proc2.communicate()
print('out: {0}'.format(out))
print('err: {0}'.format(err))
Basically an adaptation of this post. Adapt according to your needs.
Upvotes: 2