如何将变量从一个Python脚本传递到另一个?

时间:2019-07-08 21:13:31

标签: python python-3.x

我正在尝试将具有文件名/位置的变量从一个Python文件传递到Python 3.6.8上的另一个文件。

我尝试了以下代码,但是它不起作用:

executor.py(此文件是第一个文件,由用户运行),我输入code.ntx,因为这是我要使用的文件[我不需要放C :\东西,因为我的文件与executor.py在同一文件夹中:

print('What file would you like to open? (ex. C:\\Users\\JohnDoe\\Documents\\helloworld.ntx): ')
filename = input()
print('Loading ' + filename + '...')

import nitrix001

nitrix001.py代码(以及与此相关的部分)

from __main__ import *

if filename == " ":
    # The user can set this to the name of the file.
    filename = "lang.ntx"
# Opens the actual file. We use this in the 'for' loop.
File = open(f"{filename}", "r")
#
Characters = ''
# Integer that indicates the line of the program the language is reading.
Line = 1
# Variable that checks if the program is currently inside parantheses.
args = False

# Runs a 'for' loop on each line of the file.
for LineData in File:
    print(f'\nRunning Line {Line}: {LineData}')
    if not LineData.startswith('#'):

当我运行该executor.py并用code.ntx填写输入时,出现以下错误:

Traceback (most recent call last):
  File "main.py", line 1, in <module>
    import executor
  File "/home/runner/executor.py", line 16, in <module>
    import nitrix001
  File "/home/runner/nitrix001.py", line 3, in <module>
    if filename == " ":
NameError: name 'filename' is not defined

3 个答案:

答案 0 :(得分:1)

不要这样做。构建一个真实的界面并导入它,不要使用import运行可执行脚本。

# executor.py
filename = input("...")

import nitrix001

nitrix001.main(filename)
# nitrix001
def main(filename):
    with open(filename) as f:
        for line in f:
            # do stuff

答案 1 :(得分:0)

@威廉

我不知道您要达到的目标。我会改用功能

print('What file would you like to open? (ex. C:\\Users\\JohnDoe\\Documents\\helloworld.ntx): ')
filename = input()
print('Loading ' + filename + '...')

from nitrix001 import myfunc
myfunc(filename)

然后在nitroix001.py上:

def myfunc(filename)
    if filename == " ":
        # The user can set this to the name of the file.
        filename = "lang.ntx"
    # Opens the actual file. We use this in the 'for' loop.
    File = open(f"{filename}", "r")
    #
    Characters = ''
    # Integer that indicates the line of the program the language is reading.
    Line = 1
    # Variable that checks if the program is currently inside parantheses.
    args = False

    # Runs a 'for' loop on each line of the file.
    for LineData in File:
        print(f'\nRunning Line {Line}: {LineData}')
        if not LineData.startswith('#'):

答案 2 :(得分:0)

这通常不是在文件之间传递变量的好习惯,实际上,您要尝试的是窃取__main__的全局变量,因此与传递的相反,而且您会获得所有变量,而不是只是文件名。

您应该做的是将第二个文件导入第一个脚本的顶部。在第二个文件中,有一个函数,该函数带有您要传入的参数。然后,您可以从主脚本中调用该函数。

executor.py

import nitrix001

filename = input('What file would you like to open? ')
print('Loading ' + filename + '...')

nitrix001.run(filename)

nitrix001.py

def run(filename):
    #do work with the file