帮助用 Python 封装命令行工具
我真的遇到了一个问题,我希望有人可以帮助我。我正在尝试在 Python3.1 中为名为 spooky
的命令行程序创建一个包装器。我可以在命令行上成功运行这个程序,如下所示:
$ spooky -a 4 -b .97
我对 spooky 的第一次 Python 包装尝试如下所示:
import subprocess
start = "4"
end = ".97"
spooky_path = '/Users/path/to/spooky'
cmd = [spooky_path, '-a', start, '-b', end]
process = subprocess.Popen(cmd, stdout=subprocess.PIPE)
process.wait()
print('Done')
上面的代码打印 Done
,但不执行程序 spooky
接下来我尝试在命令行上执行程序,如下所示:
$ /Users/path/to/spooky -a 4 -b .97
上面的代码也失败了,并且没有提供任何有用的错误。
我的问题是:如何通过向命令行发送 spooky -a 4 -b .97
来让 Python 运行该程序?我非常感谢您能提供的任何帮助。提前致谢。
I'm really stuck with a problem I'm hoping someone can help me with. I'm trying to create a wrapper in Python3.1 for a command line program called spooky
. I can successfully run this program on the command line like this:
$ spooky -a 4 -b .97
My first Python wrapper attempt for spooky looked like this:
import subprocess
start = "4"
end = ".97"
spooky_path = '/Users/path/to/spooky'
cmd = [spooky_path, '-a', start, '-b', end]
process = subprocess.Popen(cmd, stdout=subprocess.PIPE)
process.wait()
print('Done')
The above code prints Done
, but does not execute the program spooky
Next I tried to just execute the program on the command line like this:
$ /Users/path/to/spooky -a 4 -b .97
The above code also fails, and provides no helpful errors.
My question is: How can I get Python to run this program by sending spooky -a 4 -b .97
to the command line? I would VERY much appreciate any help you can provide. Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试将命令变成单个字符串:
Try making your command into a single string:
您需要删除 stdout=subprocess.PIPE。这样做会断开进程的 stdout 与 Python 的 stdout 的连接,并使其可以使用 Popen.communicate() 函数检索,如下所示:
要使其直接打印,您可以在不使用 stdout 参数的情况下使用它:
或者您可以使用 call 函数:
You need to drop the stdout=subprocess.PIPE. Doing that disconnects the stdout of your process from Python's stdout and makes it retrievable using the Popen.communicate() function, like so:
To make it print directly you can use it without the stdout argument:
Or you can use the call function: