如何使用子进程执行Python程序

2024-10-02 22:26:13 发布

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

你好,我用的是子流程.Popen当我尝试在终端上执行一个程序时,我尝试在终端上执行一个成功的命令。在

代码如下:

            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

以及来自保存css.py在

^{pr2}$

顺便说一句:没有输出。。。在

提前谢谢。在


Tags: nameselflog终端returnifargsextract
2条回答

您应该使用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参数。如果您自己提供完整的命令行(作为一个序列),则应该始终忽略该参数。在

好吧,我忽略了你的代码不能运行(无论你尝试执行的脚本,还是主脚本实际上都不起作用),然后看看你在做什么:

或者不想执行脚本。在

另外,您似乎正在使用一个打开的文件作为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,但我认为。在

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

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

相关问题 更多 >