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

如何将变量从一个Python脚本传递到另一个Python脚本?,python,python-3.x,Python,Python 3.x,我试图在Python 3.6.8上将一个文件名/位置为的变量从一个Python文件传递到另一个Python文件。 我尝试了以下代码,但不起作用: executor.py(此文件是第一个文件,由用户运行)我输入code.ntx,因为这是我要使用的文件[我不需要放置C:\stuff,因为我的文件与executor.py位于同一文件夹中]: print('您想打开什么文件?(例如C:\\Users\\JohnDoe\\Documents\\helloworld.ntx):') filename=inp

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

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

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

print('您想打开什么文件?(例如C:\\Users\\JohnDoe\\Documents\\helloworld.ntx):')
filename=input()
打印('加载'+filename+'…'))
进口氮化硅001
NiNiNix001.py代码(以及与此相关的部件)

从主导入*
如果文件名==“”:
#用户可以将其设置为文件名。
filename=“lang.ntx”
#打开实际文件。我们在“for”循环中使用它。
File=open(f“{filename}”,“r”)
#
字符=“”
#整数,表示语言正在读取的程序行。
直线=1
#变量,用于检查程序当前是否在Paranthese中。
args=False
#在文件的每一行上运行“for”循环。
对于文件中的线条数据:
打印(f'\n运行行{Line}:{LineData}')
如果不是LineData.StartWith(“#”):
当我运行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
回溯(最近一次呼叫最后一次):
文件“main.py”,第1行,在
导入执行器
文件“/home/runner/executor.py”,第16行,在
进口氮化硅001
文件“/home/runner/nitix001.py”,第3行,在
如果文件名==“”:
名称错误:未定义名称“filename”

不要这样做。构建一个真正的接口并导入它,不要使用
import
来运行可执行脚本

#executor.py
文件名=输入(“…”)
进口氮化硅001
nitix001.main(文件名)
#nitrix001
def main(文件名):
打开(文件名)为f时:
对于f中的行:
#做事
@William

我不知道怎样才能达到你想要达到的目标。我会用函数代替

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)
然后在NiNix001.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('#'):

这通常不是在文件之间传递变量的好做法,事实上,您试图做的是窃取
\uuuu main\uuuu
的全局变量,因此这与被传递的相反,加上您得到的是所有变量,而不仅仅是文件名

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

执行人

import nitrix001

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

nitrix001.run(filename)
氮化001.py

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

您是否尝试在第二个文件中创建def,导入该def并使用文件名作为参数调用?对第一个文件的代码执行相同操作可能是一个好主意。我不确定您的意思