相关疑难解决方法(0)

如何在Python中使用子进程重定向输出?

我在命令行中做了什么:

cat file1 file2 file3 > myfile
Run Code Online (Sandbox Code Playgroud)

我想用python做什么:

import subprocess, shlex
my_cmd = 'cat file1 file2 file3 > myfile'
args = shlex.split(my_cmd)
subprocess.call(args) # spits the output in the window i call my python program
Run Code Online (Sandbox Code Playgroud)

python subprocess

87
推荐指数
3
解决办法
8万
查看次数

从subprocess.Popen获取整个输出

我通过调用subprocess.Popen获得了一个有点奇怪的结果,我怀疑这与我对Python的全新特性有很大关系.

args = [ 'cscript', '%USERPROFILE%\\tools\\jslint.js','%USERPROFILE%\\tools\\jslint.js' ]
p = Popen(args, stdout=PIPE, shell=True).communicate()[0]
Run Code Online (Sandbox Code Playgroud)

输出结果如下(尾随双\ r \n是否存在,以防它重要)

Microsoft (R) Windows Script Host Version 5.8
Copyright (C) Microsoft Corporation. All rights reserved.\r\n\r\n
Run Code Online (Sandbox Code Playgroud)

如果我从交互式Python shell运行该命令,它看起来像这样

>>> args = ['cscript', '%USERPROFILE%\\tools\\jslint.js', '%USERPROFILE%\\tools\jslint.js']
>>> p = subprocess.Popen(args, stdout=subprocess.PIPE, shell=True).communicate()[0]
Lint at line 5631 character 17: Unexpected /*member 'OpenTextFile'.
f = fso.OpenTextFile(WScript.Arguments(0), 1),

...

Lint at line 5649 character 17: Unexpected /*member 'Quit'.
WScript.Quit(1);
Run Code Online (Sandbox Code Playgroud)

所以我真正关心的是所有输出,但如果我转储"p"变量的值,我只需设置...

>>> p
'Microsoft (R) Windows Script Host Version 5.8\r\nCopyright (C) Microsoft Corpor …
Run Code Online (Sandbox Code Playgroud)

python subprocess stdout

2
推荐指数
1
解决办法
4453
查看次数

标签 统计

python ×2

subprocess ×2

stdout ×1