I'm trying the following and its failing with an error. I've tried to run it from Python shell/from a script/ on the windows console by invoking python on console. Nothing seems to work. Always the same error.
from subprocess import call
>>>pat = "d:\info2.txt"
>>> call(["type",pat])
>>>Traceback (most recent call last):
File "<pyshell#56>", line 1, in <module>
call(["type",pat])
File "C:\Python27\lib\subprocess.py", line 493, in call
return Popen(*popenargs, **kwargs).wait()
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
does anyone know what is wrong here.!!???
even the simple call(["date"]]
without any arguements also fails with the same error.
I'm using : Python 2.72 32bit version on a windows 7 machine.
To start a new process, or in other words, a new subprocess in Python, you need to use the Popen function call. It is possible to pass two parameters in the function call. The first parameter is the program you want to start, and the second is the file argument.
Popen is more general than subprocess. call . Popen doesn't block, allowing you to interact with the process while it's running, or continue with other things in your Python program. The call to Popen returns a Popen object.
Subprocess call():Subprocess has a method call() which can be used to start a program. The parameter is a list of which the first argument must be the program name. The full definition is: subprocess.call(args, *, stdin=None, stdout=None, stderr=None, shell=False) # Run the command described by args.
Python method popen() opens a pipe to or from command. The return value is an open file object connected to the pipe, which can be read or written depending on whether mode is 'r' (default) or 'w'. The bufsize argument has the same meaning as in open() function.
Add shell=True
to call:
>>> import subprocess
>>> subprocess.call('dir', shell=True)
0
As you see, it gives as value the return code, not the output of dir
. Also, it waits till the command completes, so doing
>>> subprocess.call('date', shell=True)
will wait for you to enter a new date.
edit: If you want to capture the output, use subprocess.check_output
. The DOS command type
for example prints out the contents of a file. So, suppose that your file info2.txt
contains your username, you would do:
>>> import subprocess
>>> path = r'd:\info2.txt'
>>> output = subprocess.check_output(['type', path], shell=True)
>>> print output
Vinu
For all the ways to call external commands in Python, see this comprehensive overview to a related question, for more about subprocess
specifically, see this article by Doug Hellmann.
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