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:\Python27\MyPython\MyCode.py", line 7, in <module>
runcmd("dir")
File "C:\Python27\MyPython\MyCode.py", line 4, in runcmd
x = subprocess.Popen(cmd, stdout=subprocess.PIPE)
File "C:\Python27\lib\subprocess.py", line 679, in __init__
errread, errwrite)
File "C:\Python27\lib\subprocess.py", line 893, in _execute_child
startupinfo)
WindowsError: [Error 2] The system cannot find the file specified
What could I do to fix this?
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)
As far as I know, dir
is a built in command of the shell in Windows and thus not a file available for execution as a program. Which is probably why subprocess.Popen
cannot find it. But you can try adding shell=True
to the Popen()
construtor call like this:
def runcmd(cmd):
x = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
return x.communicate(stdout)
runcmd("dir")
If shell=True
doesn't help, you're out of luck executing dir
directly. But then you can make a .bat
file and put a call to dir
there instead, and then invoke that .bat
file from Python instead.
btw also check out the PEP8!
P.S As Mark Ransom pointed out in a comment, you could just use ['cmd', '/c', 'dir']
as the value of cmd
instead of the .bat
hack if shell=True
fails to fix the issue.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With