通过一个非常简单的例子来理解子进程

时间:2018-04-14 20:17:20

标签: python python-3.x subprocess

好的,我试图了解如何使用子进程。

我在练习方面遇到了一些问题,我无法做到。 我想要做的是:ping google然后执行“cd”命令

所以基本上我想看到ping命令返回值,然后是程序所在的目录

这可能是很多信息,所以你可以跳转到最后一个代码部分。 ______________________________跳转______________________________________

我尝试了很多版本的代码。我设法用“运行”命令做了一半,但返回“CompletedProcess”,我不能使用它。

首先尝试ping谷歌

result=subprocess.run('ping google.com', stdout=subprocess.PIPE)
print(result.stdout.decode('utf-8'))

这个工作正常,然后我提出“'ping google.com'”为“'cd',shell = True” 并且finnaly用cd代替dir,而decode无法解码输出(为什么?)。

好的,之后我尝试了:

result=subprocess.run(['cd ..'], shell=True, stdout=subprocess.PIPE)
result.run(['cd'], shell=True, stdout=subprocess.PIPE)
print(result.stdout.decode('utf-8'))

得到了:

AttributeError: 'CompletedProcess' object has no attribute 'run'

正如所料。 所以这引导我去了Popen,所以我开始用它:

result=subprocess.Popen('ping google.com',  stdout=subprocess.PIPE)
print(result.communicate()[0].decode('utf-8'))

_____________________停止跳转____________________________

现在我想在ping之后发送“cd”,我尝试了多种方法,例如:

result=subprocess.Popen('ping google.com',shell=True, stdin=subprocess.PIPE,stdout=subprocess.PIPE)
a='cd\n'
result.communicate(a.encode('utf-8'))
print(result.communicate()[0].decode('utf-8'))

这只打印ping。 我尝试删除“[0] .decode('utf-8')” - 没有cd输出

我希望看到ping结果,然后是cd输出,我该怎么办?

最终我想运行几个依赖于前一个输出的命令。

奖金问题:我想将使用Popen的程序应用到raspbian终端,这是正确的吗?

编辑:我的问题不是关于cd,它关于在同一个终端中运行多个命令,cd可能只是ping不同的ip

1 个答案:

答案 0 :(得分:0)

如果您尝试通过同一终端执行两个命令,则必须先启动shell,然后逐个输入命令:

import subprocess
p = subprocess.Popen('cmd.exe', stdin=subprocess.PIPE,
         stdout=subprocess.PIPE)
p.stdin.write(b'ping www.google.com' + '\n') #b in front to denote bytes object
p.stdin.write(b'cd ..' + b'\n') #stdin doesn't take strings
p.stdin.close()
a = p.stdout.read()
for i in a.split(b'\n'):
    print(i)

你会得到这样的东西:

b'Microsoft Windows [Version 10.0.16299.371]\r'
b'(c) 2017 Microsoft Corporation. All rights reserved.\r'
b'\r'
b'C:\\Users\\Jason\\.PyCharmCE2017.3\\config\\scratches>ping www.google.com'
b'\r'
b'Pinging www.google.com [172.217.12.196] with 32 bytes of data:\r'
b'Reply from 172.217.12.196: bytes=32 time=5ms TTL=56\r'
b'Reply from 172.217.12.196: bytes=32 time=5ms TTL=56\r'
b'Reply from 172.217.12.196: bytes=32 time=6ms TTL=56\r'
b'Reply from 172.217.12.196: bytes=32 time=7ms TTL=56\r'
b'\r'
b'Ping statistics for 172.217.12.196:\r'
b'    Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),\r'
b'Approximate round trip times in milli-seconds:\r'
b'    Minimum = 5ms, Maximum = 7ms, Average = 5ms\r'
b'\r'
b'C:\\Users\\Jason\\.PyCharmCE2017.3\\config\\scratches>cd ..'
b'\r'
b'C:\\Users\\Jason\\.PyCharmCE2017.3\\config>'
相关问题