python - 如何使用 subprocess 来执行 Python 程序

标签 python python-3.x

你好,我正在使用 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”。

此外,您似乎在写入文件后将打开的文件用作标准输入。那行不通。

>>> 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 会更好。

要与子进程对话,您可以在管道上使用 communicate(),而不是 read()。

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

关于python - 如何使用 subprocess 来执行 Python 程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4801798/

相关文章:

c++ - python sys.stdout 和 C++ iostreams::cout

python - 在 Pandas 中合并索引上的数据帧效率更高

python - 使用 pytest 并行运行具有多个配置的单个测试

sql - 如何使用默认值将列添加到数据库

python - Python中变量和函数的命名约定是什么?

python - 模块未找到错误: No module named 'markdown' when running lektor server

python - 如何计算两个时间字符串之间的时间间隔

python - 使用 BeautifulSoup 获取 div 的分隔内容

Python http.client.RemoteDisconnected

python - 崇高包 : 'No SSL support included in this Python' when try to send a mail python3