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
pat = "d:\info2.txt"
In Python and most other programming languages, \
is an escape character, which is not included in a string unless doubled. Either use a raw string or escape the escape character:
pat = "d:\\info2.txt"
Escape the \
with \\
:
pat = "d:\\info2.txt"
or use "raw" strings:
pat = r"d:\info2.txt"
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.
The 'type' command doesn't run because it's an internal command - internal to the command interpreter/shell called CMD.EXE. You have to call "cmd.exe type filename" instead. The exact code is:
call(['cmd','/C type abc.txt'])