2014-12-01 28 views
0

我試圖使用與pkexec一起運行一個命令,但是說沒有找到這樣的文件。使用子進程和pkexec

process = subprocess.Popen(["pkexec cat", "/dev/input/event4"], stdout=subprocess.PIPE) 
for line in iter(process.stdout.readline, ''): 
    sys.stdout.write(line) 

OSError: [Errno 2] No such file or directory

然而,路徑是否正確以及該文件是存在的。

+0

你要求它搜索一個名爲'pkexec cat'的可執行文件位於'PATH'上。儘管這種事情不存在,但這不太可能。因此ENOENT錯誤。 – abarnert 2014-12-01 22:45:24

回答

3

你可能想使用:

subprocess.Popen(["pkexec", "cat", "/dev/input/event4"]) 

由於subprocess.Popen報價列表中的每個條目;所以你的例子是一樣的命令行使用此:

$ "pkexec cat" /dev/input/event4 

相反的:

$ pkexec cat /dev/input/event4 

the documentation(重點煤礦):

args is required for all calls and should be a string, or a sequence of program arguments. Providing a sequence of arguments is generally preferred, as it allows the module to take care of any required escaping and quoting of arguments (e.g. to permit spaces in file names). If passing a single string, either shell must be True (see below) or else the string must simply name the program to be executed without specifying any arguments.

+0

太快了,謝謝!我會在幾分鐘內將您的答案標記爲正確。 – Kenny 2014-12-01 22:37:19

+0

實際上,你不能傳遞一個字符串而不是一個列表(除非你也使用'shell = True',在這種情況下shell而不是Python解析字符串)。查看[常用參數]下的'args'(https://docs.python.org/3/library/subprocess.html#frequently-used-arguments)。 – abarnert 2014-12-01 22:44:24

+0

@abarnert謝謝!當我測試它時,我也注意到了這一點(因爲我很少使用它),並刪除了這個註釋。 – Carpetsmoker 2014-12-01 22:45:08