你的代码中出现的错误NameError: name '__file__' is not defined表示Python无法找到__file__这个变量。__file__是一个特殊的变量,它包含了当前脚本的路径。然而,如果你的代码是在交互式环境中运行的(例如Jupyter notebook或Python shell),那么__file__变量可能并不存在。

你可以使用以下的解决方案:

  1. 如果你的代码是在一个Python脚本文件中运行的,你可以直接使用__file__变量。
  2. 如果你的代码是在交互式环境中运行的,你可以使用os.getcwd()函数来获取当前工作目录。以下是一个示例:
import os
import subprocess

def cmd_run(ItemNum: str, py: str = None):
    if not py:
        py = "query_ProductItems.py"
    ItemNum = str(ItemNum).encode("utf-8")

    current_path = os.getcwd()
    script_path = os.path.join(current_path, py)
    result = subprocess.run(["python", script_path], input=ItemNum, capture_output=True)
    
    output_data = result.stdout.decode("gbk", errors="ignore")
    error_message = result.stderr.decode("gbk", errors="ignore")
    return output_data, error_message

if __name__ == "__main__":
    ItemNum = "SY2002072400061"
    result = cmd_run(ItemNum)
    print(result)

在这个例子中,os.getcwd()函数会返回当前工作目录。然后,这个目录被用来构造脚本的路径。

希望这个答案对你有所帮助!如果你还有其他问题,欢迎随时向我提问。.