简单Python脚本执行不正确

2024-04-26 05:52:26 发布

您现在位置:Python中文网/ 问答频道 /正文

代码如下:

    fh = tempfile.NamedTemporaryFile(delete=False,suffix = '.py')
    stream = io.open(fh.name,'w',newline='\r\n')
    stream.write(unicode(script))
    stream.flush()
    stream.close()
    proc = subprocess.Popen(
        [path,fh.name], 
        shell=True,
        stdin=subprocess.PIPE,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
    )
    proc.stdin.close()
    proc.stderr.close()
    out = proc.stdout.readline()
    print out

脚本是一个包含子进程代码的字符串,在本例中是一个简单的hello world。因为它有unix文件结尾,所以我不得不使用io.打开以便为windows正确编写它。路径是通向python.exe在我的机器上。文件已生成,在记事本中看起来很好:

    def main():
        print 'hello world'

但是,当我运行程序时,子进程将执行而不执行任何操作。 这不是可执行路径的问题,我已经用其他程序测试过了,所以它必须是临时文件本身,或者其中的文本。Delete设置为false以检查文件的内容以进行调试。这个代码有什么明显的错误吗?我对使用Popen有点陌生。你知道吗


Tags: 文件代码nameioclosestreamstderrstdin
1条回答
网友
1楼 · 发布于 2024-04-26 05:52:26

程序中的主要问题是,在指定shell=True时,需要将整个命令作为字符串而不是列表提供。你知道吗

考虑到这一点,您真的没有必要使用shell=True,而且,除非绝对必要,否则您不应该使用shell=True,这是一种安全隐患,这在documentation as well -中给出

Executing shell commands that incorporate unsanitized input from an untrusted source makes a program vulnerable to shell injection, a serious security flaw which can result in arbitrary command execution. For this reason, the use of shell=True is strongly discouraged in cases where the command string is constructed from external input:

另外,如果您不想使用stdin/stderr(因为您一开始就关闭这些进程),那么就不需要对它们使用PIPE。你知道吗

示例-

fh = tempfile.NamedTemporaryFile(delete=False,suffix = '.py')
stream = io.open(fh.name,'w',newline='\r\n')
stream.write(unicode(script))
stream.flush()
stream.close()
proc = subprocess.Popen(
    [path,fh.name], 
    stdout=subprocess.PIPE,
)
out = proc.stdout.readline()
print out

还有,剧本-

def main():
    print 'hello world'

无法运行,因为需要调用main()才能运行。你知道吗

相关问题 更多 >