使用子进程模块执行 python 脚本但从 IDLE 执行代码时出现 NameError

NameError when executing python script using subprocess module but code executing from IDLE

我最近在使用 subprocess 模块,它的 运行 方法仅通过 python 执行 os 命令并获取输出,因为我试图制作自定义命令提示符在 tkinter 中。

命令提示符处理我写入命令的方式如下-:

  1. 所以当我写一个命令作为输入时,我将它从空格中分离出来,例如

    输入:cmd exec python test.py

    输出:['cmd', 'exec', 'python', 'test.py'] # i.e. [cmd, arg1, arg2, ...]

  2. 现在我把上面的列表转换成一个有两个键的字典-:

    • 第一个键是 'name',其值为命令名称。
    • 第二个键是 'args',它是一个连接的字符串值(除第一个列表项之外的所有其他列表项的第一个 步骤)。

    所以变成-:

    command_input = {'name' : 'python', 'args' = 'test.py'} # i.e. {'name': cmd, 'args': concat_str_of_args}
    
  3. 现在第二个过程中制作的字典被传递到一个 模块,它解释命令并将其转换为 普通命令提示符命令(注意:以前该命令是基于我自己的自定义语法 cmd exec command_prompt_command 的自定义命令)在字符串形式和 returns 它作为一个名为的字典 command_output,它的 args 作为第 1 步中的列表([cmd, arg1, arg2.....]).

    像这样-:

    command_output = my_module.convert_to_cmd_form(command_input) # returns a dictionary like so -: {'args' : ['python', 'test.py']}
    

现在我尝试执行我制作的 python 脚本来测试它是否有效,测试文件的代码是 -:

# CODE FOR TEST FILE
print('This is a special test for the terminal cmd integration!')

并通过 IDLE 执行此文件,我得到了所需的输出,没有错误:

This is a special test for the interstellar terminal cmd integration!

当我对我的自定义命令提示符执行相同的操作时,它在后端使用特殊的子进程 python 脚本来 运行 这个 test.py 它给出了一个名称错误:

而且我无法正确理解执行脚本的代码有点像这样的原因:

os.environ["PYTHONUNBUFFERED"] = "1"
print([command_output['args'][0]], ' '.join(command_output['args'][1 : ]), ' '.join(command_output['args'][1 : ]).encode('utf-8'))
result = subprocess.run([command_output['args'][0]], input = ' '.join(command_output['args'][1 : ]).encode('utf-8'), stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell = True, env = os.environ, cwd = 'C:')

此处的打印语句用于调试以检查是否所有值都按预期进行了解析。

['python'] test.py b'test.py'

my special subprocess python script to run this test.py it gives a name error:

您在聊天讨论中的评论:

import subprocess

command_output = {'args':['python',r'test.py'] }
result = subprocess.run([command_output['args'][0]],
                        input = ' '.join(command_output['args'][1 : ]).encode('utf-8'),
                        stdout=subprocess.PIPE,
                        stderr=subprocess.STDOUT,
                        shell = True, env = os.environ, cwd = 'C:')

包含文件的完整路径以缓解 NameError: name \'test\' is not defined\r\n' 异常。

command_output = {'args':['python',r'c:\full\path\test.py'] }

对于以下解决方案,您需要适当地解析 command_output

这个表格有效

args = ['python', '-m', 'test']
other = subprocess.run([args,
                        stdout=subprocess.PIPE,
                        stderr=subprocess.STDOUT,
                        shell = True, env = os.environ, cwd = 'C:')

使用输入关键字参数,您需要发送 python 命令,如果您是 typing/executing 来自 python shell.

args = [b'python']
cmd = b'import test'
another = subprocess.run(args,
                         input = cmd,
                         stdout=subprocess.PIPE,
                         stderr=subprocess.STDOUT,
                         shell = True, env = os.environ, cwd = 'C:')

此答案由本回答提供 。同样,您可能需要包含文件的完整路径。

args = [b'python']
cmd = b'''exec(open("test.py").read())'''
another1 = subprocess.run(args,
                         input = cmd,
                         stdout=subprocess.PIPE,
                         stderr=subprocess.STDOUT,
                         shell = True, env = os.environ, cwd = 'C:')