简体   繁体   English

如何从Linux上运行的进程的命令行发出命令

[英]How to issue a command from the command line of a process running on Linux

Lets say I issue a command from the Linux command line. 假设我从Linux命令行发出命令。 This will cause Linux to create a new Process and lets say that the Process expects to receive the command from the user. 这将导致Linux创建一个新进程,并假设进程希望从用户接收命令。

For Example: I will run a python script test.py which will accept a command from the user. 例如:我将运行一个python脚本test.py,它将接受来自用户的命令。

$python test.py $ python test.py

TEST>addController(192.168.56.101) TEST> addController(192.168.56.101)

Controller added 控制器添加

TEST> TEST>

The question I have is can I write a script which will go into the command line (TEST>) and issue a command? 我的问题是我可以编写一个脚本进入命令行(TEST>)并发出命令吗? As far as I know if I write a script to run multiple commands it will wait for the first process to exit before running the next command. 据我所知,如果我编写一个脚本来运行多个命令,它将等待第一个进程退出,然后再运行下一个命令。

Regards, 问候,

Vinay Pai BH Vinay Pai BH

You should look into expect . 你应该考虑期待 It's a tool that is designed to automate user interaction with commands that need it. 它是一个工具,旨在自动化用户与需要它的命令交互。 The man page explains how to use it. 手册页介绍了如何使用它。

Seems like there is also pexpect , a Python version of similar functionality. 似乎还有pexpect ,类似功能的Python版本。

Assuming the Python script is reading its commands from stdin, you can pass them in with a pipe or a redirection: 假设Python脚本正在从stdin读取其命令,您可以使用管道或重定向传递它们:

$ python test.py <<< 'addController(192.168.56.101)'

$ echo $'addController(192.168.56.101)\nfoo()\nbar()\nbaz()' | python test.py

$ python test.py <<EOF
addController(192.168.56.101)
foo()
bar()
baz()
EOF

If you don't mind waiting for the calls to finish (one at a time) before returning control to your program, you can use the subprocess library. 如果在将控制权返回给程序之前不介意等待完成调用(一次一个),则可以使用子进程库。 If you want to start something running and not wait for it to finish, you can use the multiprocessing library. 如果要开始运行而不是等待它完成,可以使用multiprocessing库。

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

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