2
#!/usr/bin/env python
import os, sys, subprocess, time
while True:    
    print subprocess.call("xsel", shell=True);
    time.sleep(1);

每 1 秒从剪贴板获取一个条目并打印一次。

结果:

copied0
entry0
from0
clipboard0

我不知道为什么它返回最后的 0,但它显然阻止了我使用字符串条(int 没有条),因此 0 使字符串成为整数?

如何在上面的结果中从 python 字符串中去除最后的 0?

我是转换为 python 的 BASH 脚本编写者。

4

6 回答 6

4

编辑subprocess.call不是返回一个字符串,而是一个 int -0你看到的(在 xsel 的实际输出之后)。改用:

print subprocess.Popen('xsel', stdout=subprocess.PIPE).communicate()[0]
于 2009-12-08T04:45:02.807 回答
4

正如马克指出的那样,subprocess.call()不做你想做的事

像这样的东西应该工作

#!/usr/bin/env python
import os, sys, subprocess, time
while True:
    p=subprocess.Popen(["xsel"],stdout=subprocess.PIPE)
    print p.stdout.read()
    time.sleep(1)
于 2009-12-08T04:54:24.090 回答
2

"copied0".rstrip("0")应该管用

实际上,你最好这样做,它不会在屏幕上显示返回码

import os, sys, subprocess, time
while True:    
    _ = subprocess.call("dir", shell=True);
    time.sleep(1);
于 2009-12-08T04:36:59.827 回答
2

在我看来,它正在运行“xsel”,它将其结果打印到标准输出,然后将返回码 (0) 打印到标准输出。您没有从 python 获得剪辑结果。

您可能想要 subprocess.popen 并捕获标准输出。

于 2009-12-08T04:42:44.933 回答
2

每行的0换行符和换行符是 python print 命令打印的唯一内容,其中零是来自subprocess.call. shell 本身首先将它的结果打印到标准输出,这就是你看到这个词的原因。

编辑:关于顿悟,请参阅 S Mark 帖子中的评论。

于 2009-12-08T04:54:09.893 回答
1

如果零总是在字符串的末尾,因此您总是希望删除最后一个字符,只需执行st=st[:-1].

或者,如果您不确定最后是否会出现零,您可以执行if st[-1]==0: st=st[:-1].

于 2009-12-08T04:43:28.957 回答