注册 登录
编程论坛 Python论坛

[求助]请协助看看这个语句的输出对不对

卜酷塔2 发布于 2017-03-29 09:57, 1761 次点击
count2.py
#! /usr/bin/python
import os
import sys
import subprocess
import time

input='ps -ef | grep ' + sys.argv[1] +' | grep -v grep | wc -l'
a=os.popen(input).read()
time.sleep(1)
b=os.popen(input).read()
c= int(a) + int(b)
print a,b,c

说明如下:
该语句为查询系统中是否存在某个进程,如果存在返回1,输出两个返回值相加结果
存在问题:
执行该代码添加一个不存在的进程时,a,b均显示1(应该显示0),是我的逻辑有问题,还是写法有问题。



3 回复
#2
卜酷塔22017-03-29 12:42
太冷清了吧。
使用commands问题依旧
另:
python编辑器中返回结果正常
跑脚本出现问题。

#! /usr/bin/python
import os
import sys
import subprocess
import time
import commands

x=sys.argv[1]
print x
input='ps -ef |grep '+str(x)+' | grep -v grep | wc -l'
print input
a=commands.getoutput(input)
print "this is a",a
time.sleep(1)
b=commands.getoutput(input)
print "this is b",b
c= int(a) + int(b)
print c
#3
test30262017-04-06 15:42
太冷清了吧。
使用commands问题依旧
另:
python编辑器中返回结果正常
跑脚本出现问题。

#! /usr/bin/python
import os
import sys
import subprocess
import time
import commands

x=sys.argv[1]
print x
input='ps -ef |grep '+str(x)+' | grep -v grep | wc -l'
print input
a=commands.getoutput(input)
print "this is a",a
time.sleep(1)
b=commands.getoutput(input)
print "this is b",b
c= int(a) + int(b)
print c
#4
sunb32017-04-24 13:27
input是关键字,还是避免被挪作他用吧……
你这个是因为os.popen打开的是管道,管道也是一行,所以wc -l肯定要多记一行的数,最简单的改法:

程序代码:

#! /usr/bin/python
import os
import sys
import time

cmd='ps -ef | grep ' + sys.argv[1] +' | grep -v grep | wc -l'
a=int(os.popen(cmd).read())-1
b=int(os.popen(cmd).read())-1
c= a + b
print(a,b,c)


另外我个人认为这个最好还是用bash写……
1