0

我有一段代码可以读取两个文件,将它们转换为集合,然后从另一个中减去一个集合。我想将字符串变量(installedPackages)用于“a”而不是文件。我还想为“c”写一个变量。

a = open("/home/user/packages1.txt")
b = open("/home/user/packages.txt")
c = open("/home/user/unique.txt", "w")

for line in set(a) - set(b):
    c.write(line)

a.close()
b.close()
c.close()

我尝试了以下方法,但它不起作用:

for line in set(installedPackages) - set(b):

我曾尝试使用 StringIO,但我认为我使用不当。

最后,这是我创建的方式installedPackages

stdout, stderr = p.communicate()
installedPackages = re.sub('\n$', '', re.sub('install$', '', re.sub('\t', '', stdout), 0,re.MULTILINE))

packages.txt 示例:

humanity-icon-theme
hunspell-en-us
hwdata
hyphen-en-us
ibus
ibus-gtk
ibus-gtk3
ibus-pinyin
ibus-pinyin-db-android
ibus-table
4

3 回答 3

2

如果要写入字符串缓冲区文件,请使用StringIO

>>> from StringIO import StringIO
>>> installed_packages = StringIO()
>>> installed_packages.write('test')
>>> installed_packages.getvalue()
'test'
于 2012-05-15T23:29:50.783 回答
1

set 数据类型以可迭代对象作为参数,因此如果 installedPackages 包含多个项目的字符串,则需要用分隔符将其拆分。例如,以下代码将用所有逗号分割字符串:

for line in set(installedPackages.split(',')) - set(b):
    c.write(line)
于 2012-05-15T23:31:05.757 回答
1

像下面这样的东西?

编辑:经过几次迭代:

from subprocess import Popen, PIPE

DEBUG = True
if DEBUG:
    def log(msg, data):
        print(msg)
        print(repr(data))
else:
    def log(msg, data):
        pass

def setFromFile(fname):
    with open(fname) as inf:
        return set(ln.strip() for ln in inf)

def setFromString(s):
    return set(ln.strip() for ln in s.split("\n"))

def main():
    # get list of installed packages
    p = Popen(['dpkg', '--get-selections'], stdout=PIPE, stderr=PIPE)
    stdout, stderr = p.communicate()
    installed_packages = setFromString(stdout)

    # get list of expected packages
    known_packages = setFromFile('/home/john/packages.txt')

    # calculate the difference
    unknown_packages = installed_packages - known_packages
    unknown_packages_string = "\n".join(unknown_packages)

    log("Installed packages:", installed_packages)
    log("Known packages:", known_packages)
    log("Unknown packages:", unknown_packages)

if __name__=="__main__":
    main()
于 2012-05-16T00:05:28.000 回答