我想通过python中的命令行创建一个AVD (Android虚拟设备)。为此,我需要将一个字符串n传递给标准输入。我尝试过以下几种方法
emulator_create = str(subprocess.check_output([android,'create', 'avd', '-n', emulator_name, '-t', target_id, '-b', abi],stdin=PIPE))
emulator_create.communicate("n")但它会引发以下错误
raise CalledProcessError(retcode, cmd, output=output)
subprocess.CalledProcessError: Command '['/home/fahim/Android/Sdk/tools/android', 'create', 'avd', '-n', 'samsung_1', '-t', '5', '-b', 'android-tv/x86']' returned non-zero exit status 1
Process finished with exit code 1我能做什么?
发布于 2016-11-30 12:34:33
在你的例子中有些东西是不起作用的。subprocess.check_output()返回你想要执行的子进程的输出,a handle to this process。换句话说,您将获得一个string对象(或者可能是bytes对象),您不能使用它来操作子进程。
可能发生的情况是,您的脚本将使用subprocess.check_output()执行子进程,并等待它完成,然后再继续。但是,由于您永远无法与它通信,它将以一个非零返回值结束,这将引发subprocess.CalledProcessError
现在,使用grep作为等待标准输入执行某些操作的命令示例(因为我没有安装Android Virtual Device creator ),您可以这样做:
#!/usr/bin/env python2.7
import subprocess
external_command = ['/bin/grep', 'StackOverflow']
input_to_send = '''Almost every body uses Facebook
You can also say that about Google
But you can find an answer on StackOverflow
Even if you're an old programmer
'''
child_process = subprocess.Popen(args=external_command,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
universal_newlines=True)
stdout_from_child, stderr_from_child = child_process.communicate(input_to_send)
print "Output from child process:", stdout_from_child
child_process.wait()它将打印"Output from StackOverflow: But you can find an答案on StackOverflow",这是grep的输出。
在这个例子中,我有
subprocess.Popen类创建子进程的句柄stdin和stdout的值设置为subprocess.PIPE,使我们能够在以后与此进程进行通信
.communicate()方法将字符串发送到其标准输入。在同一步骤中,我检索了它的标准输出和在上一步中检索到的标准输出的标准错误(只是为了表明它实际上完成了该子进程is output.在Python3.5中,它甚至更简单:
#!/usr/bin/env python3.5
import subprocess
external_command = ['/bin/grep', 'StackOverflow']
input_to_send = '''Almost every body uses Facebook
You can also say that about Google
But you can find an answer on StackOverflow
Even if you're an old programmer
'''
completed_process_result = subprocess.run(args=external_command,
input=input_to_send,
stdout=subprocess.PIPE,
universal_newlines=True)
print("Output from child process:", completed_process_result.stdout)在这个例子中,我有:
subprocess.run()来执行该命令。input参数是我们发送给子流程的标准输入的字符串
现在,您必须根据您的情况调整此代码。
https://stackoverflow.com/questions/40443263
复制相似问题