当我尝试在子进程中使用echo管道回复时,为什么命令会中断,但是当我手动将其输入命令提示符时,该命令工作正常?
注意我尝试使用和不使用间距并且结果是相同的,但是如果您在命令提示符中看到它是完全正确的,它可以工作而不是给出错误
WindowsError: [Error 2] The system cannot find the file specified
C:\Windows\System32>python
Python 2.7.13 (v2.7.13:a06454b1afa1, Dec 17 2016, 20:42:59) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import subprocess
>>> p = subprocess.Popen("echo y|cacls {0} /d SYSTEM".format("C:\\ProgramData\\Microsoft\\Diagnosis\\ETLLogs\\AutoLogger\\AutoLogger-Diagtrack-Listener.etl", stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python27\lib\subprocess.py", line 390, in __init__
errread, errwrite)
File "C:\Python27\lib\subprocess.py", line 640, in _execute_child
startupinfo)
WindowsError: [Error 2] The system cannot find the file specified
>>> p = subprocess.Popen("echo y|cacls {0} /d SYSTEM".format("C:\ProgramData\Microsoft\Diagnosis\ETLLogs\AutoLogger\AutoLogger-Diagtrack-Listener.etl", stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python27\lib\subprocess.py", line 390, in __init__
errread, errwrite)
File "C:\Python27\lib\subprocess.py", line 640, in _execute_child
startupinfo)
WindowsError: [Error 2] The system cannot find the file specified
>>> p = subprocess.Popen("echo y| cacls {0} /d SYSTEM".format("C:\\ProgramData\\Microsoft\\Diagnosis\\ETLLogs\\AutoLogger\\AutoLogger-Diagtrack-Listener.etl", stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python27\lib\subprocess.py", line 390, in __init__
errread, errwrite)
File "C:\Python27\lib\subprocess.py", line 640, in _execute_child
startupinfo)
WindowsError: [Error 2] The system cannot find the file specified
>>> p = subprocess.Popen("cacls {0} /d SYSTEM".format("C:\\ProgramData\\Microsoft\\Diagnosis\\ETLLogs\\AutoLogger\\AutoLogger-Diagtrack-Listener.etl", stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE))
>>> Are you sure (Y/N)?
请注意,当我完全删除回声时它最终会起作用,但是我实际上永远无法完成它的运行,因为它永远不会得到“是”(echo y|
)回复......并且没有不幸的是,/yes
切换内置在命令中。
答案 0 :(得分:0)
看起来这个问题与此类似:How to use Subprocess in Windows
“echo”不是程序,而是shell的内置功能,因此正确的功能需要指令“ shell = True ”,所以你的命令应该是:
p = subprocess.Popen("echo y|cacls {0} /d SYSTEM".format("C:\\ProgramData\\Microsoft\\Diagnosis\\ETLLogs\\AutoLogger\\AutoLogger-Diagtrack-Listener.etl", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE))
这也是错误的原因(因为回声)并且因为cacls是程序,然后它在生成错误后运行(没有你需要的echo y)