我想做的是
$echo $PATH | python --remain-interactive "x = raw_input().split(':')"
>>>
>>> print x
['/usr/local/bin', '/usr/bin', '/bin']
我认为 ipython 解决方案是最好的。如果这无法实现,那么对于我想要处理各种其他命令的输出的情况,您的解决方案是什么?之前我在绝望的时候也用过subprocess来做,但是效果并不理想。
更新:所以这越来越接近最终结果:
echo $PATH > /tmp/stdout.txt; ipython -i -c 'stdout = open("/tmp/stdout.txt").read()'
现在我们如何将其弯曲成一种形式
echo $PATH | pyout
,其中 pyout
是“解决我所有问题的神奇解决方案”。它可能是一个 shell 脚本,用于写入管道输出,然后运行 ipython。由于 bp 所说的同样原因,所做的一切都失败了。
What I'd like to do is something like
$echo $PATH | python --remain-interactive "x = raw_input().split(':')"
>>>
>>> print x
['/usr/local/bin', '/usr/bin', '/bin']
I suppose ipython solution would be best. If this isn't achievable, what would be your solution for the situation where I want to process output from various other commands? I've used subprocess before to do it when I was desperate, but it is not ideal.
UPDATE: So this is getting closer to the end result:
echo $PATH > /tmp/stdout.txt; ipython -i -c 'stdout = open("/tmp/stdout.txt").read()'
Now how can we go about bending this into a form
echo $PATH | pyout
where pyout
is the "magic solution to all my problems". It could be a shell script that writes the piped output and then runs the ipython. Everything done fails for the same reasons bp says.
发布评论
评论(3)
在 IPython 中,你可以这样做 虽然
$
的双重转义很痛苦,但我想你可以这样做
In IPython you can do this
The double escape of
$
is a pain thoughYou could do this I guess
您要查找的
--remain-interactive
开关是-i
。您还可以使用-c
开关指定要执行的命令,例如__import__("sys").stdin.read().split(":")
。所以你会尝试的是:(不要忘记转义字符串!)但是,这就是将显示的全部内容:
那么为什么它不起作用?因为你是管道。 python 解释器尝试以交互方式从您正在读取参数的 sys.stdin 中读取命令。由于
echo
已执行完毕,sys.stdin
已关闭,无法进行进一步的输入。出于同样的原因,类似这样的事情
将会失败。
我要做的是:
毕竟,
open("spam.bar")
是一个文件对象,就像sys.stdin
一样:)The
--remain-interactive
switch you are looking for is-i
. You also can use the-c
switch to specify the command to execute, such as__import__("sys").stdin.read().split(":")
. So what you would try is: (do not forget about escaping strings!)However, this is all that will be displayed:
So why doesn't it work? Because you are piping. The python intepreter is trying to interactively read commands from the same
sys.stdin
you are reading arguments from. Sinceecho
is done executing,sys.stdin
is closed and no further input can happen.For the same reason, something like:
...will fail.
What I would do is:
After all,
open("spam.bar")
is a file object just likesys.stdin
is :)由于 Python 公理“应该有一种 - 最好只有一种 - 明显的方法来做到这一点”,我有理由确信,与其他进程交互的方式不会比
subprocess
模块。如果您能说出为什么类似以下“不理想”的内容可能会有所帮助:(
在您的具体示例中,您可以使用
os.environ
但我意识到这并不是您真正要问的。)Due to the Python axiom of "There should be one - and preferably only one - obvious way to do it" I'm reasonably sure that there won't be a better way to interact with other processes than the
subprocess
module.It might help if you could say why something like the following "is not ideal":
(In your specific example you could use
os.environ
but I realise that's not really what you're asking.)