【问题标题】:How to increment a variable in another script through importing?如何通过导入增加另一个脚本中的变量?
【发布时间】:2017-03-23 20:39:28
【问题描述】:

我处理 2 个文件,比如 ba.py 和 2.py

ba.py:

import sys

count  = 1 # This is global count

def callme():
    pass
    # Doing Some operation

2.py

import ba
print ba.count ## This is working fine
ba.callme() ## This is also working fine.

我正在运行这样的自动化工作:

for i in $(find /home/some/SomeElse/HeyMore -type f); do python 2.py $i; done

此命令的作用是从指定文件夹中获取文件并将其作为参数传递给2.py 中的函数。

在内部,我想在 python 中打开文件并执行一些操作。但是,我不想让我的系统超载,所以在 10 个作业之后我想睡 10 秒。我在ba.py 中使用count 维护计数。第一次调用后,应该递增到2,以此类推。

但是,当它达到 10 时,它应该休眠,因为我的逻辑如下所示。

print ba.count
ba.count = ba.count + 1  ## Here increment should happen
if ba.count % 10 == 0:
        time.sleep(10)
else:
        ba.callme()

每次我运行这个自动化脚本,我只看到1的,并且脚本在10秒后没有休眠。

关于如何解决这个问题有什么建议吗?

【问题讨论】:

  • 我观察到的唯一一件事是每次脚本执行完毕时计数被重置为 1。
  • 每次您执行python scriptname 时,您都在开始一个新的过程。不保留来自先前过程的变量。如果您需要在脚本运行之间保留数据,则应将其放入文件中。

标签: python django scope automation global


【解决方案1】:

2.py 为每个文件运行,并且不知道先前运行中设置的计数器。一种解决方案是仅运行 2.py 一次并通过管道输入您要处理的文件:

import sys
import time

def callme(filename):
    print filename

for count,line in enumerate(sys.stdin):
    if count and not(count % 10):
        print('sleeping')
        time.sleep(1) # I got bored.... make that 10
    callme(line.strip())

你的脚本变成了

find /home/some/SomeElse/HeyMore -type f | python 2.py

如果您不希望 find 一直在抽取数据,您可以一次提取所有文件,然后处理它们

filenames = [line.strip() for line in sys.stdin.readlines()]
...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-27
    • 2023-02-21
    • 2017-01-03
    • 2017-01-05
    • 2015-07-01
    • 2020-01-15
    • 2014-12-20
    相关资源
    最近更新 更多