Skip to main content
 首页 » 编程设计

python之如何使用 python 子进程模块执行包含脚本的字符串

2025年05月04日23JustinYoung

我收到一个字符串中的脚本,并试图找到一种使用 python 的子进程模块执行它的方法。例如

import subprocess 
script = """#!/usr/bin/python 
            print "inside script" 
         """ 
subprocess.Popen(script) 

这会抛出一个 OSError:说没有这样的文件或目录,这很公平,因为我认为它正在尝试寻找命令名称。

然后我尝试了 subprocess.Popen(script, shell=True) ,它只适用于 shell 命令并且完全忽略了 #!在脚本的顶部。有没有办法让 suprocess 运行我存储在字符串中的脚本,就像它的可执行文件一样?

请您参考如下方法:

此解决方案基于 -c(编译)Python 解释器 cmdline 参数。它完全忽略了使用 shell 属性。

Popen 可以用类似的方式创建。 subprocess.call 用于显示脚本实际上已执行,python 解释器返回代码被执行的代码更改。

import subprocess 
 
executable_code = """ 
print 'inside script' 
print 123 
""" 
 
code_with_exception = """ 
raise Exception() 
""" 
 
ok_rc = subprocess.call(['python', '-c', executable_code]) 
assert ok_rc == 0 
 
bad_rc = subprocess.call(['python', '-c', code_with_exception]) 
assert bad_rc == 1 

其他改进是跳过“python”硬编码字符串并使用 sys.executable .

A string giving the absolute path of the executable binary for the Python interpreter, on systems where this makes sense. If Python is unable to retrieve the real path to its executable, sys.executable will be an empty string or None.

import sys 
import subprocesss 
code = "raise Exception()" 
bad_rc = subprocess.call([sys.executable, '-c', code]) 
assert bad_rc == 1