繁体   English   中英

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

[英]How can I pass a variable from one Python Script to another?

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

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

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

nitix001.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

不要这样做。 构建一个真实的界面并导入它,不要使用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

@威廉

我不知道有什么方法可以完成您想要实现的目标。 我会改用函数

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)

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

这通常不是在文件之间传递变量的好习惯,实际上你想要做的是窃取__main__的全局变量,因此与传递相反,并且你得到所有变量而不仅仅是文件名。

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

执行器.py

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM