可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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 "", line 1, in 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.
回答1:
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.
回答2:
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'])
回答3:
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"
回答4:
Escape the \
with \\
:
pat = "d:\\info2.txt"
or use "raw" strings:
pat = r"d:\info2.txt"