Python 和子进程

0 投票
1 回答
2274 浏览
提问于 2025-04-15 11:58

这是我正在做的一个脚本。它应该在下面的循环中运行一个 .exe 文件。(顺便说一下,不确定是否能看到,但 for el in ('90','52.6223',...) 是在循环外面的,它和其他部分形成了一个嵌套循环。)我不太确定顺序是否正确或者其他方面的问题。另外,当 .exe 文件运行时,它会输出一些内容,我需要把某一行打印到屏幕上(这就是你看到的 AspecificLine= ... 的原因)。如果有任何有用的回答,那就太好了!

for el in ('90.','52.62263.','26.5651.','10.8123.'):

    if el == '90.':
        z = ('0.')
    elif el == '52.62263.':
        z = ('0.', '72.', '144.', '216.', '288.')
    elif el == '26.5651':
        z = ('324.', '36.', '108.', '180.', '252.')
    else el == '10.8123':
        z = ('288.', '0.', '72.', '144.', '216.')

        for az in z:

            comstring = os.path.join('Path where .exe file is')
            comstring = os.path.normpath(comstring) 
            comstring = '"' + comstring + '"'

            comstringfull = comstring + ' -el ' + str(el) + ' -n ' + str(z)

            print 'The python program is running this command with the shell:'
            print comstring + '\n'

            process = Popen(comstring,shell=True,stderr=STDOUT,stdout=PIPE)
            outputstring = myprocesscommunicate()

            print 'The command shell returned the following back to python:'
            print outputstring[0]

                AspecificLine=linecache.getline(' ??filename??   ',     # ??
                sys.stderr.write('az', 'el', 'AREA' )           # ??

1 个回答

1

使用 shell=True 是不对的,因为这样会不必要地调用系统的命令行。

相反,你应该这样做:

for el in ('90.','52.62263.','26.5651.','10.8123.'):
    if el == '90.':
        z = ('0.')
    elif el == '52.62263.':
        z = ('0.', '72.', '144.', '216.', '288.')
    elif el == '26.5651':
        z = ('324.', '36.', '108.', '180.', '252.')
    else el == '10.8123':
        z = ('288.', '0.', '72.', '144.', '216.')

    for az in z:

        exepath = os.path.join('Path where .exe file is')
        exepath = os.path.normpath(comstring) 
        cmd = [exepath, '-el', str(el), '-n', str(z)]

        print 'The python program is running this command:'
        print cmd

        process = Popen(cmd, stderr=STDOUT, stdout=PIPE)
        outputstring = process.communicate()[0]

        print 'The command returned the following back to python:'
        print outputstring
        outputlist = outputstring.splitlines()
        AspecificLine = outputlist[22]   # get some specific line. 23?
        print AspecificLine

撰写回答