简体   繁体   English

python:如何从另一个程序中使用命令行调用(以用户的键击作为输入)运行程序?

[英]python: how to run a program with a command line call (that takes a user's keystroke as input) from within another program?

I can run one program by typing: python enable_robot.py -e in the command line, but I want to run it from within another program. 我可以通过在命令行中键入: python enable_robot.py -e来运行一个程序,但我想从另一个程序中运行它。

In the other program, I imported subprocess and had subprocess.Popen(['enable_robot', 'baxter_tools/scripts/enable_robot.py','-e']) , but I get an error message saying something about a callback. 在另一个程序中,我导入了subprocess.Popen(['enable_robot', 'baxter_tools/scripts/enable_robot.py','-e'])并且有subprocess.Popen(['enable_robot', 'baxter_tools/scripts/enable_robot.py','-e']) ,但是我收到一条错误消息,说明了一些关于回调的信息。

If I comment out this line, the rest of my program works perfectly fine. 如果我注释掉这一行,我的程序的其余部分就可以正常工作了。

Any suggestions on how I could change this line to get my code to work or if I shouldn't be using subprocess at all? 有关如何更改此行以使我的代码工作或者我不应该使用子进程的任何建议?

If enable_robot.py requires user input, probably it wasn't meant to run from another python script. 如果enable_robot.py需要用户输入,可能并不意味着从另一个python脚本运行。 you might want to import it as a module: import enable_robot and run the functions you want to use from there. 您可能希望将其作为模块import enable_robotimport enable_robot并从那里运行您要使用的函数。

If you want to stick to the subprocess, you can pass input with communicate : 如果您想坚持使用子进程,可以通过communicate传递输入:

p = subprocess.Popen(['enable_robot', 'baxter_tools/scripts/enable_robot.py','-e'])
p.communicate(input=b'whatever string\nnext line')

communicate documentation , example . communicate 文档例子

Your program enable_robot.py should meet the following requirements: 您的程序enable_robot.py应符合以下要求:

  • The first line is a path indicating what program is used to interpret the script. 第一行是指示用于解释脚本的程序的路径。 In this case, it is the python path. 在这种情况下,它是python路径。
  • Your script should be executable 您的脚本应该是可执行的

A very simple example. 一个非常简单的例子。 We have two python scripts: called.py and caller.py 我们有两个python脚本:called.py和caller.py

Usage: caller.py will execute called.py using subprocess.Popen() 用法:caller.py将使用subprocess.Popen subprocess.Popen()执行called.py

File /tmp/called.py 文件/tmp/called.py

#!/usr/bin/python
print("OK")

File /tmp/caller.py 文件/tmp/caller.py

#!/usr/bin/python
import subprocess
proc = subprocess.Popen(['/tmp/called.py'])

Make both executable: 使两者都可执行:

chmod +x /tmp/caller.py
chmod +x /tmp/called.py

caller.py output: caller.py输出:

$ /tmp/caller.py $ /tmp/caller.py

$ OK 好的

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

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