【问题标题】:How do I pass variables between two different python scripts I have如何在我拥有的两个不同 python 脚本之间传递变量
【发布时间】:2016-12-04 19:35:12
【问题描述】:

我正在尝试在两个不同的 python 脚本之间传递信息。它们很长,所以为了简化起见,这里有两个我遇到相同问题的脚本:

a.py

f = open('test.txt', 'w+')
num = int(raw_input('How many are there: '))
tipe = raw_input('What kind are they: ')

if __name__ == '__main__':
    from b import fxn

    for x in xrange(num, num+11):
        fxn()
        num = x

    f.close()

b.py

from a import num, tipe

def fxn():  
    print num, tipe
    f.writelines(str(num)+', '+tipe)

我被要求输入 num 和 tipe 两次,然后第二次的条目被打印 11 次。

如何将 a.py 中的变量/文件传递给 b.py,在 b.py 中编辑/操作/操作,然后在 a.py 中传回/关闭?

另外,为什么我两次要求 num 和 tipe,然后 if name == 'ma​​in': 下的代码运行?

【问题讨论】:

  • 函数可以带参数。两次要求您输入的原因是这些 IO 操作在全局范围内,每次导入时都会执行。

标签: python variables import module


【解决方案1】:

您可以使用这种方式。

a.py

x=5
print x 

b.py

import a
print a.x

【讨论】:

    【解决方案2】:

    你可以通过函数传递它们

    a.py

    f = open('test.txt', 'w+')
    num = int(raw_input('How many are there: '))
    tipe = raw_input('What kind are they: ')
    
    if __name__ == '__main__':
        from b import fxn
    
        for x in xrange(num, num+11):
            fxn(num, tipe, f) # Pass parameters num, tipe and file handle
            num = x
    
        f.close()
    

    b.py

    # from a import num, tipe --> **This is not required**
    
    # receive inputs
    def fxn(num, tipe, f): 
        print num, tipe
        f.writelines(str(num)+', '+tipe)
    

    执行a.py会导致

    3 fruits
    3 fruits
    4 fruits
    5 fruits
    6 fruits
    7 fruits
    8 fruits
    9 fruits
    10 fruits
    11 fruits
    12 fruits
    

    3 fruits 打印两次,因为您首先调用函数,然后增加 num(通过重新分配)。相反,您可以让您的 a.py 如下所示仅打印一次 3 个水果:

    f = open('test.txt', 'w+')
    num = int(raw_input('How many are there: '))
    tipe = raw_input('What kind are they: ')
    
    if __name__ == '__main__':
        from b import fxn
    
        for x in xrange(num, num+11):
            fxn(x, tipe, f) # Pass parameters num, tipe and file handle
    
        f.close()
    

    【讨论】:

      【解决方案3】:

      在 Python 脚本之间传递变量时,请记住,当您调用脚本时,调用脚本可以访问被调用脚本的命名空间。

      话虽如此,您可以尝试一下:使用代码启动被调用的脚本

      from __main__ import *
      

      这将授予对调用者脚本的命名空间(变量和函数)的访问权限。由于这些实际上并不是您之前所说的要操作的文件,因此我将留给您将其应用于真实文件,希望对您有所帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-10-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-08-06
        • 1970-01-01
        • 2017-06-10
        • 1970-01-01
        相关资源
        最近更新 更多