在Python 3.6.8上,我试图将一个带有文件名/位置的变量从一个Python文件传递到另一个Python文件。
我尝试了以下代码,但不起作用:
你知道吗执行人.py(此文件是我输入的第一个文件,由用户运行)代码.ntx因为这就是我想要使用的文件[我不需要把C:\的东西放在同一个文件夹中,因为我的文件和执行人.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('#'):
当我运行时执行人.py并在输入中填入代码.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
别这样。构建一个真正的接口并导入它,不要使用
import
来运行可执行脚本。你知道吗@威廉
我不知道怎样才能达到你的目的。我会用函数代替
然后在nitrix001.py上:
这通常不是在文件之间传递变量的好做法,事实上,您要做的是窃取
__main__
的全局变量,这与传递的结果相反,再加上您得到的是所有变量,而不仅仅是文件名。你知道吗您应该做的是导入第一个脚本顶部的第二个文件。在第二个文件中,有一个函数,其中包含要传入的参数。然后可以从主脚本调用该函数。你知道吗
你知道吗执行人.py你知道吗
亚硝酸盐001.py
相关问题 更多 >
编程相关推荐