繁体   English   中英

Python脚本执行外部命令

[英]Python script to execute external commands

我需要向当前正在执行的程序发出一些命令,并将当前(远程)正在执行的程序的输出输出到脚本中的某些字符串中。 我目前遇到的问题是我不知道每个命令的输出,因为可以从用户那里读取它的输出也会有所不同。

例如

  1. ./my_program
  2. print_output_1 [在my_program中使用 ]
  3. print_output_2 [在my_program中使用 ]
  4. 退出[与my_program中的一起 ]

如果我手动运行命令,终端将显示以下内容

bash$ ./my_programe
my_program: print_output_1
my_program:first_line_printed_with_unknown_length
my_program: print_output_2
my_program:second_line_printed_with_unknown_length
my_program: exit
bash$

所以我应该在像这样的python字符串中获得“ first_line_printed_with_unknown_length”和“ second_line_printed_with_unknown_length”

execute(my_program)
str1 = execute( print_output_1 )
str2 = execute( print_output_2 )
val = execute( exit )

您可以使用子流程模块执行外部命令。 最好先从简单得多的命令入手,以掌握所有内容。 下面是一个虚拟的示例:

import subprocess
from subprocess import PIPE

def main():
    process = subprocess.Popen('echo %USERNAME%', stdout=PIPE, shell=True)
    username = process.communicate()[0]
    print username #prints the username of the account you're logged in as

if __name__ == '__main__':
    main()

这将从echo %USERNAME%获取输出并将其存储。 只是为了给您大致的思路。

从上述文档中:

警告:使用shell = True可能存在安全隐患。 有关详细信息,请参见“常用参数”下的警告。

可以使用ssh(即ssh命令)进行操作,并且ssh可以像任何shell可执行命令一样包装在Python中,因此答案是肯定的。 这样的事情可能会起作用(我没有尝试):

import subprocess

remote_command = ['ls', '-l']
ssh_command = ['ssh', 'user@hostname.com'] + remote_command
proc = subprocess.Popen(ssh_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = proc.communicate()

# stdout now contains the output of the remote command
# stderr now contains the error stream from the remote command or from ssh

您还可以使用Paramiko,它是Python中的ssh实现,但是如果不需要交互性,则可能会过高。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM