Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
265 views
in Technique[技术] by (71.8m points)

python - How to use Subprocess in Windows

I am trying to save the result or function runcmd in the variable Result. Here is what I have tried: import subprocess

def runcmd(cmd):
  x = subprocess.Popen(cmd, stdout=subprocess.PIPE)
  Result = x.communicate(stdout)
  return Result
runcmd("dir")

When I run ths code, I get this result:

Traceback (most recent call last):
  File "C:Python27MyPythonMyCode.py", line 7, in <module>
    runcmd("dir")
  File "C:Python27MyPythonMyCode.py", line 4, in runcmd
    x = subprocess.Popen(cmd, stdout=subprocess.PIPE)
  File "C:Python27libsubprocess.py", line 679, in __init__
errread, errwrite)
  File "C:Python27libsubprocess.py", line 893, in _execute_child
    startupinfo)
WindowsError: [Error 2] The system cannot find the file specified

What could I do to fix this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I think what you are looking for is os.listdir()

check out the os module for more info

an example:

>>> import os
>>> l = os.listdir()
>>> print (l)
['DLLs', 'Doc', 'google-python-exercises', 'include', 'Lib', 'libs', 'LICENSE.txt', 'NEWS.txt', 'python.exe', 'pythonw.e
xe', 'README.txt', 'tcl', 'Tools', 'VS2010Cmd.lnk']
>>>

You could also read the output into a list:

result = []
process = subprocess.Popen('dir', 
    shell=True, 
    stdout=subprocess.PIPE, 
    stderr=subprocess.PIPE )
for line in process.stdout:
    result.append(line)
errcode = process.returncode
for line in result:
    print(line)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...