Tôi đang viết một trình bao bọc để tự động hóa một số lệnh shell ADB android thông qua Python (2.7.2). Vì, trong một số trường hợp, tôi cần chạy lệnh không đồng bộ, tôi đang sử dụng phương thức subprocess .Popen để đưa ra các lệnh shell.subprocess.Popen và định dạng shlex.split trong cửa sổ và linux
Tôi đã chạy vào một vấn đề với các định dạng của [command, args]
tham số của phương pháp Popen
, nơi có yêu cầu lệnh/args chia là khác nhau giữa Windows và Linux:
# sample command with parameters
cmd = 'adb -s <serialnumber> shell ls /system'
# Windows:
s = subprocess.Popen(cmd.split(), shell=False) # command is split into args by spaces
# Linux:
s = subprocess.Popen([cmd], shell=False) # command is a list of length 1 containing whole command as single string
Tôi đã cố gắng sử dụng shlex .split(), có và bằng cờ posix:
# Windows
posix = False
print shlex.split(cmd, posix = posix), posix
# Linux
posix = True
print shlex.split(cmd, posix = posix), posix
Cả hai trường hợp đều trả lại cùng một phần.
Có một phương pháp trong subprocess
hoặc shlex
để xử lý các định dạng hệ điều hành cụ thể đúng?
Đây là giải pháp hiện tại của tôi:
import os
import tempfile
import subprocess
import shlex
# determine OS type
posix = False
if os.name == 'posix':
posix = True
cmd = 'adb -s <serialnumber> shell ls /system'
if posix: # posix case, single command string including arguments
args = [cmd]
else: # windows case, split arguments by spaces
args = shlex.split(cmd)
# capture output to a temp file
o = tempfile.TemporaryFile()
s = subprocess.Popen(args, shell=False, stdout=o, stderr=o)
s.communicate()
o.seek(0)
o.read()
o.close()
Tôi không nghĩ shlex.split()
đang làm bất cứ điều gì ở đây, và cmd.split()
đạt được kết quả giống hệt nhau.
Bạn đã đánh máy trong câu hỏi. shlex vs shelx. – jgritty
@jgritty cảm ơn. Đã sửa. –
tại sao bạn sử dụng 'shell = True'? – jfs