繁体   English   中英

如何使用子流程通过Python执行程序

[英]How to use subprocess to execute programs with Python

您好,我正在使用subprocess.Popen()类,并且在终端上成功执行了命令,但是当我尝试执行例如以Python编写的脚本并尝试传递参数时,系统将失败。

这是代码:

            argPath = "test1"
            args = open(argPath, 'w')

            if self.extract.getByAttr(self.block, 'name', 'args') != None:
                args.write("<request>"+self.extract.getByAttr(self.block, 'name', 'args')[0].toxml()+"</request>")
            else:
                args.write('')

            car = Popen(shlex.split('python3.1 /home/hidura/webapps/karinapp/Suite/ForeingCode/saveCSS.py', stdin=args, stdout=subprocess.PIPE, stderr=subprocess.PIPE))
            args.close()

            dataOut = car.stdout.read().decode()
            log = car.stderr.read().decode()


            if dataOut!='':
                return dataOut.split('\n')

            elif log != '':
                return log.split('\n')[0]

            else:
                return None

还有来自saveCSS.py的代码

from xml.dom.minidom import parseString
import os
import sys

class savCSS:
        """This class has to save

    the changes on the css file.
    """

    def __init__(self, args):

        document = parseString(args)
        request = document.firstChild

        address = request.getElementsByTagName('element')[0]
        newdata = request.getElementsByTagName('element')[1]

        cssfl = open("/webapps/karinapp/Suite/"+address.getAttribute('value'), 'r')
        cssData = cssfl.read()
        cssfl.close()

        dataCSS = ''
        for child in newdata.childNodes:
            if child.nodeType == 3:
                dataCSS += child.nodeValue

        nwcssDict = {}

        for piece in dataCSS.split('}'):
            nwcssDict[piece.split('{')[0]] = piece.split('{')[1]


        cssDict = {}

        for piece in cssData.split('}'):
            cssDict[piece.split('{')[0]] = piece.split('{')[1]


        for key in nwcssDict:
            if key in cssDict == True:
                del cssDict[key]

            cssDict[key] = nwcssDict[key]


        result = ''
        for key in cssDict:
            result += key+"{"+cssDict[key]+"}"


        cssfl = open(cssfl.name, 'a')
            cssfl.write(result)
            cssfl.close()



if __name__ == "__main__":
    savCSS(sys.stdin)

顺便说一句:没有输出...

提前致谢。

好的,我忽略了您的代码未运行(您尝试执行的脚本均未运行,而主脚本实际上未运行),而是查看您正在执行的操作:

它会执行脚本,否则会出现错误,例如“ bin / sh:foo:not found”。

同样,在写入文件后,您似乎正在使用打开文件作为stdin。 那不行

>>> thefile = open('/tmp/foo.txt', 'w')
>>> thefile.write("Hej!")
4
>>> thefile.read()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IOError: not readable

您需要关闭文件,然后将其重新打开为读取文件。 我认为,尽管在这种情况下最好使用StringIO。

要与子进程通信,请在管道上使用communication(),而不要使用read()。

我不确定在这里为什么要使用shell = True,似乎没有必要,如果我是我,我会删除它,除非您实际上需要shell来做,否则它只会使事情变得复杂。 具体来说,你应该使用shell时= TRUE,该命令拆分成一个列表。 您的代码实际上在做什么,正在启动Python提示符。

您应该使用communicate()而不是.stdout.read()

而且您发布的代码甚至都不正确:

Popen(shlex.split('python3.1 /home/hidura/webapps/karinapp/Suite/ForeingCode/saveCSS.py', stdin=args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)

缺少括号,并且从stdout / stderr参数中可以清楚地看到,您没有输出到控制台,而是输出到管道(如果这就是“没有输出...”的意思)。

您的代码实际上将在Windows上运行,但是在Linux上,您必须删除shell=True参数。 如果您自己提供完整的命令行(按顺序),则应始终忽略该参数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM