如何使用Python在外部控制台中编写/执行命令

时间:2018-02-18 06:23:12

标签: python for-loop cmd subprocess

我是Python的新手,无法找到以下问题的解决方案:

我想写python脚本,让我们说打开cmd并在for循环中执行几个命令。启动cmd(例如subprocess.run())并使用Python(v.3.6)进行预定义命令。

import subprocess
_path = "C:\\..."
_exe = "...\\cmd.exe"
subprocess.run(_path + _exe)
for i in range (1,100,1)
   ...

但是我怎样才能将Python中的命令写入cmd?结果呢?我怎么能得到一个信号,我的cmd命令是否被执行所以我可以启动一个新的命令(比如for循环)

感谢您的帮助和最诚挚的问候,

Andreas买家

1 个答案:

答案 0 :(得分:0)

您可能想要使用Popen.communicate(input=None, timeout=None)并将 shell arg设置为true。然后,您要等待进程输出流以响应您的命令。注意:Popen.communicate要求输入是字节编码的。 Popen.communicate的输出也是字节编码的,所以你需要在它上面执行str.decode()来提取编码的字符串。

所有这些都在Python API中完整记录。我建议你阅读手册。

或者,您可以使用像this one这样的库来包装所有这些东西。

import subprocess

proc = subprocess.Popen('ls', stdout=subprocess.PIPE, stdin=subprocess.PIPE)
try:
    outs, errs = proc.communicate(timeout=15) # use input= param if you need to
    proc.wait()
except TimeoutExpired:
    proc.kill()
    outs, errs = proc.communicate()

print ('%s, %s' % (outs, errs))

输出并与实际'ls'输出进行比较:

$ python popen_ex.py 
b'__pycache__\npopen_ex.py\n', None
$ ls
__pycache__ popen_ex.py

您需要发送到popen的任何其他命令都可以在proc.communicate中发送。

如果您真的想要与交互式shell进行通信,Popen.communicate()允许一次写入stdin并从stdout / stderr读取。在调用Popen.communicate()之后,输入/输出/错误流由子进程关闭。如果你想要一个完全互动的外壳,你必须自己写一个,或者使用一个库,就像我链接的那样。

import subprocess
proc = subprocess.Popen('sh', stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE)
try:
    outs, errs = proc.communicate(input='ls'.encode('ascii'), timeout=15)
    proc.wait()
    print ('%s, %s' % (outs, errs))

    proc = subprocess.Popen('sh', stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE)
    outs, errs = proc.communicate(input='ps'.encode('ascii'), timeout=15)
    proc.wait()
    print ('%s, %s' % (outs, errs))
except TimeoutError:
    proc.kill()
    outs, errs = proc.communicate()

输出并与实际'ls','ps'进行比较

$ python popen_ex.py 
    b'__pycache__\npopen_ex.py\n', b''
    b'  PID TTY           TIME CMD\n  879 ttys000    0:00.18 -bash\n 7063 ttys000    0:00.06 python popen_ex.py\n 7066 ttys000    0:00.00 sh\n  911 ttys001    0:00.06 -bash\n  938 ttys002    0:00.16 -bash\n 6728 ttys002    0:00.11 python\n  972 ttys004    0:00.06 -bash\n 1019 ttys005    0:00.06 -bash\n 1021 ttys006    0:00.06 -bash\n 1023 ttys007    0:00.06 -bash\n', b''
$ ls
    __pycache__ popen_ex.py
$ ps
      PID TTY           TIME CMD
      879 ttys000    0:00.19 -bash
      911 ttys001    0:00.06 -bash
      938 ttys002    0:00.16 -bash
     6728 ttys002    0:00.11 python
      972 ttys004    0:00.06 -bash
     1019 ttys005    0:00.06 -bash
     1021 ttys006    0:00.06 -bash
     1023 ttys007    0:00.06 -bash