如何在导入的模块/脚本中引用主脚本中的变量? [英] How do I refer to a variable from the main script in an imported module/script?

查看:71
本文介绍了如何在导入的模块/脚本中引用主脚本中的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的导入脚本'scan.py'中,我想引用之前在主脚本中创建和初始化的变量的值。这是主脚本中的代码:

In my imported script 'scan.py' I want to refer to a value of a variable created and initialized before in the main script. Here's the code from the main script:

Input = EJ.get()
       os.system ('python scan.py')
       FileName = str(r"C:\\Users\\Admin\\Documents\\HPython\\WESMFG\\POnumber\\" + Input + ".pdf")





以及scan.py脚本的相关代码:



and the relevant code of the scan.py script:

output_file = Input
print("Output file: %s" % output_file)
.
.
.
print("Writing output file ...")
img = scan_session.images[0]
img.save(output_file, "JPEG")
print("Done")



'输入'存储来自我的Tkinter GUI的Entry小部件EJ的输入。因此我希望用户输入内容,因此此输入获取新扫描文档的名称。

运行主脚本时,它告诉我输入未定义。

因为我对python编程很陌生,也许我错误地忽略了


'Input' stores the Input of the Entry widget EJ from my Tkinter GUI. So I want the user to type in something, so this input gets the name of the new scanned document.
When running the main script, it tells me 'Input' is not defined.
Since I'm kind of new to programming on python, maybe I'm falsely ignoring

if __name__ == "__main__":
    pyinsane2.init()
    try:
        main()
    finally:
        pyinsane2.exit()

在scan.py结尾处。这对我的问题有什么影响吗?



我尝试过的事情:



at the end of scan.py. Does this matter in any way to my question?

What I have tried:

import __main__

main_global1= __main__.global1

但由于'Input'在函数中,它告诉我main中没有变量名为'input'

but since 'Input' is in a function it tells me there is no variable in main called 'Input'

推荐答案

您不能在自己的环境中运行的程序中使用局部变量。您需要将值作为参数传递给系统调用;请参阅 29.1。 sys - 特定于系统的参数和函数 - Python 3.6.4文档 [ ^ ]



您的代码应该是:

You cannot use a local variable in a program that is running in its own environment. You need to pass the value as a parameter on your system call; see 29.1. sys — System-specific parameters and functions — Python 3.6.4 documentation[^]

Your code should be:
Input = EJ.get()
# do not use 'r' prefix if the string uses escape sequences
FileName = str("C:\\Users\\Admin\\Documents\\HPython\\WESMFG\\POnumber\\" + Input + ".pdf")
os.system ('python scan.py ' + FileName)


这篇关于如何在导入的模块/脚本中引用主脚本中的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆