I’m using Windows 7, and I’ve tried this under Python 2.6.6 and Python 3.2.
So I’m trying to call this command line from Python:
netstat -ano | find ":80"
under Windows cmd, this line works perfectly fine.
So,
-
1st attempt:
output = subprocess.Popen( [r'netstat -ano | find ":80"'], stdout=subprocess.PIPE, shell=True ).communicate()An error is raised that ‘find’ actually didn’t receive correct parameter (e.g. ‘find “:80” \’):
Access denied - \ -
2nd attempt:
#calling netstat cmd_netstat = subprocess.Popen( ['netstat','-ano'], stdout = subprocess.PIPE ) #pipelining netstat result into find cmd_find = subprocess.Popen( ['find','":80"'], stdin = cmd_netstat.stdout, stdout = subprocess.PIPE )Again, the same error is raised.
Access denied - \
What did I do wrong? 🙁
EDIT:
-
3rd attempt (As @Pavel Repin suggested):
cmd_netstat = subprocess.Popen( ['cmd.exe', '-c', 'netstat -ano | find ":80"'], stdout=subprocess.PIPE ).communicate()Unfortunately, subprocess with [‘cmd.exe’,’-c’] results in something resembling deadlock or a blank cmd window. I assume ‘-c’ is ignored by cmd, resulting in communicate() waiting indefinitely for cmd termination. Since this is Windows, my bet bet is cmd only accepts parameter starting with slash (/). So I substituted ‘-c’ with ‘/c’:
cmd_netstat = subprocess.Popen( ['cmd.exe', '/c', 'netstat -ano | find ":80"'], stdout=subprocess.PIPE ).communicate()And…back to the same error:
Access denied - \
EDIT:
I gave up, I’ll just process the string returned by ‘netstat -ano’ in Python. Might this be a bug?
So I revisited this question, and found two solutions (I switched to Python 2.7 sometime ago, so I’m not sure about Python 2.6, but it should be the same.):
Replace find with findstr, and remove doublequotes
But this doesn’t explain why “find” cannot be used, so:
Use string parameter instead of list
or
The problem arise from the fact that: [‘find’,'”:80″‘] is actually translated into [‘find,’\”:80\”‘].
Thus the following command is executed in Windows command shell:
Proof:
Running:
returns:
Running:
returns: