简体   繁体   English

将 python 脚本中的变量导入另一个脚本会引发变量未定义的错误

[英]Importing variables from python script into another script is throwing errors that variables are undefined

I am currently writing automation scripts for a proprietary Windows desktop application at work using WinAppDriver with Python.我目前正在使用带有 Python 的 WinAppDriver 为专有的 Windows 桌面应用程序编写自动化脚本。 Our application has the user upload a handful of files, does some behind the scenes calculating based on the files uploaded and then spits out results.我们的应用程序让用户上传少量文件,根据上传的文件进行一些幕后计算,然后输出结果。 I have automation in place that uploads these files using the UI and am not having any issues with this specifically.我有使用 UI 上传这些文件的自动化功能,并且对此没有任何问题。 The process to do this is as follows:执行此操作的过程如下:

  1. Click the 'Choose File' button.单击“选择文件”按钮。 Browse to file location in pop up window在弹出窗口中浏览到文件位置 window

  2. Click in 'File Name' field and input the direct path to the file.单击“文件名”字段并输入文件的直接路径。 Click OK (This is being done with the Python Keyboard library)单击确定(这是通过 Python 键盘库完成的)

  3. Repeat previous steps for all necessary files对所有必要的文件重复前面的步骤

  4. Click 'Go'点击“开始”

To tidy up my scripts, I have set the file paths to variables instead of using their direct paths in my code.为了整理我的脚本,我将文件路径设置为变量,而不是在我的代码中使用它们的直接路径。 Then I just call the variable name for the file I need.然后我只需调用我需要的文件的变量名。

Eg file_to_upload_1: str = r”C:\Users\user\...\filename.txt例如file_to_upload_1: str = r”C:\Users\user\...\filename.txt

I have created a separate filePaths.py where all these file paths set to variables are stored so adding/modifying them in the future is easy and all in one place.我创建了一个单独的filePaths.py ,其中存储了所有这些设置为变量的文件路径,因此将来添加/修改它们很容易,而且都在一个地方。

The issue that I am running into with all of this is when I import this .py that contains my file paths set to variables.我遇到的所有这些问题是当我import这个包含设置为变量的文件路径的.py时。 Right now, I am doing from filePaths import * for simplicity sake.现在,为了简单起见,我正在from filePaths import *做。 This is generally frowned upon and VS Code throws warnings at me advising I have imported unused imports.这通常是不受欢迎的,VS Code 会向我发出警告,建议我导入了未使用的导入。 I went ahead and set my variables to separate classes and then tried to import them in the following way: from filePaths import dataset_1 When I do this I get the follow error: Undefined variable “variable_name” and my tests fail to run.我继续将变量设置为单独的类,然后尝试通过以下方式导入它们: from filePaths import dataset_1当我这样做时,我收到以下错误: Undefined variable “variable_name”并且我的测试无法运行。 It seems like I can only get this all to work if I import everything and I would like to avoid doing that if possible.似乎只有导入所有内容才能使这一切正常工作,并且如果可能的话,我想避免这样做。 All my scripts are in the same directory.我所有的脚本都在同一个目录中。 What am I missing here?我在这里想念什么?

Sample of code:代码示例:

from filePaths import * <-- THIS WORKS!
# from filePaths import class_1 <-- THIS DOES NOT

#Open App
desired_caps = {}
desired_caps["app"] = "C:\\Users\\Public\\Desktop\\Application_Being_Tested.lnk"
driver = webdriver.Remote("http://127.0.0.1:4723", desired_caps)

#Login
driver.find_element_by_accessibility_id("Username").send_keys("tester")
driver.find_element_by_accessibility_id("UserPassword").send_keys("password")
driver.find_element_by_accessibility_id("btnLogin").click()

###Upload Files###

#First File To Upload
driver.find_element_by_accessibility_id("ChooseFile").click()
time.sleep(.1)
driver.find_element_by_accessibility_id("FileName").click()
keyboard.write(filePaths_variable)
keyboard.press_and_release('enter')

You have three options:你有三个选择:

  1. Import everything using the wildcard (ie from filePaths import * )使用通配符导入所有内容(即from filePaths import *
  2. Import select objects (ie from filePaths import object1, object2, object3 #... )导入 select 对象(即from filePaths import object1, object2, object3 #...
  3. Use dot notation (ie import filePaths then filePaths.object1 #etc )使用点表示法(即import filePaths然后filePaths.object1 #etc

Some options may be considered better programming style than others.有些选项可能被认为比其他选项更好的编程风格。

The reason the wildcard works is because it is the same as option 2 from above if you had listed all created objects within filePaths on you import statement.通配符起作用的原因是,如果您在 import 语句的filePaths中列出了所有创建的对象,则它与上面的选项 2 相同。 In general, you should either selectively import only the methods and objects you need, or just import the script and use dot notation to selectively use methods and objects as needed.通常,您应该选择性地仅导入您需要的方法和对象,或者只导入脚本并使用点表示法根据需要选择性地使用方法和对象。

The following example code shows how to use dot notation.以下示例代码显示了如何使用点表示法。

file 1:文件 1:

# objects_to_import.py

bob = 127
string = 'my string'

def foo():
    print('bar')

def bar():
    print('foo')

def print_var(var):
    print(var)

file 2:文件 2:

# main.py in the same directory as objects_to_import.py

import objects_to_import

print(objects_to_import.bob)
objects_to_import.print_var(objects_to_import.bob)
objects_to_import.foo()
objects_to_import.bar()

try:
    print(string)
except NameError:
    print("You didn't import that variable or use correct notation!")

Then, running main.py outputs:然后,运行 main.py 输出:

"""
127
127
bar
foo
You didn't import that variable or use correct notation!
"""

The results are identical if main.py instead read:如果 main.py 改为读取,结果是相同的:

from objects_to_import import bob, foo, bar, print_var

print(bob)
print_var(bob)
foo()
bar()

try:
    print(string)
except NameError:
    print("You didn't import that variable or use correct notation!")

Note the if we add the following code to both versions of main.py:请注意,如果我们将以下代码添加到两个版本的 main.py:

if('bob' in globals()):
    print('Bob is in your globals!')
else:
    print("Can't find bob in your globals")

We find that bob is in your globals' space when explicitly imported, but is not present when using dot notation with the general non-explicit import statement.我们发现bob在显式导入时位于您的全局空间中,但在将点表示法与一般非显式导入语句一起使用时不存在。 There therefore might be pragmatic reasons to choose one import method over the other (eg if you program is long and complex and you would like to more easily manage potential name collisions, you should use dot notation).因此,选择一种导入方法而不是另一种可能有实际的原因(例如,如果您的程序又长又复杂,并且您希望更轻松地管理潜在的名称冲突,则应该使用点表示法)。

Alright I've come up with a solution!好吧,我想出了一个解决方案!

I have my filePaths.py module with class_1 in there containing a set of certain variables: var_1 , var_2 , etc. respectively...我的filePaths.py模块带有class_1 ,其中包含一组特定变量:分别为var_1var_2等...

In my script that wants these variables, I'm bringing the module in like so:在需要这些变量的脚本中,我将模块引入如下:

import filePaths

path = filePaths.class_1

When I call one of the variables in class_1 instead of just var_1 I call path.var_1 and it comes in with no issues.当我调用class_1中的一个变量而不是var_1时,我调用path.var_1并且它没有问题。 Thank you everyone for helping out with this!谢谢大家帮忙解决这个问题!

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

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