【问题标题】:How to pass a new variable to python script using 'for' loop如何使用'for'循环将新变量传递给python脚本
【发布时间】:2016-11-29 09:13:30
【问题描述】:

我正在尝试编写一个 python 脚本,它将遍历一个列表,然后将一个新变量传递给另一个 python 脚本。这是我的代码:

脚本:ENCViewer.py

 # import necessary modules
 import os

 # list of all ENCS
 root = os.listdir('/home/cassandra/desktop/file_formats/ENC_ROOT')
 root.sort()
 root = root[2:]

 for ENC in root:
      # pass new instance of variable 'ENC' to ENCReader.py
     import ENCReader.py

脚本:ENCReader.py

from __main__ import *
print ENC
.... # remaining script

目前,在执行第一个代码ENCViewer.py时,它只会执行一次然后退出。如何将“ENC”的新实例变量传递给 ENCReader.py,以便它在代码的第一个 sn-p 中看到的整个“for”循环中执行?

谢谢。

【问题讨论】:

  • 明确一点,“其他python脚本”是指另一个进程?如果是这样,那么您需要某种形式的进程间通信,例如管道、套接字或消息队列。

标签: python variables for-loop main


【解决方案1】:

我不知道你问的是否可能,但我认为你错过了理解创建模块和导入代码的想法。达到相同结果的“标准”方式如下:

ENCReader.py

def printer(var):
    print(var)
    # your code..

ENCViewer.py

 import os
 from ENCReader import printer

 # list of all ENCS
 root = os.listdir('/home/cassandra/desktop/file_formats/ENC_ROOT')
 root.sort()
 root = root[2:]

for ENC in root:
    printer(ENC)

【讨论】:

  • 我认为你的意思是 ENC?
猜你喜欢
  • 1970-01-01
  • 2014-10-05
  • 1970-01-01
  • 2011-12-03
  • 2013-10-24
  • 2017-04-01
  • 1970-01-01
  • 2021-05-31
  • 1970-01-01
相关资源
最近更新 更多