Python 如何使子进程station在os.walk(path)下执行
我希望脚本进入Python 如何使子进程station在os.walk(path)下执行,python,Python,我希望脚本进入os.walk()中提到的特定文件路径,然后对该位置下的所有文件执行grep命令,并将输出重定向到文件。下面是我创建的脚本,但是子进程在当前目录下执行ls-al命令,但是打印语句向我显示os.walk的内容。因此,我还需要子进程来执行os.walk路径下的命令 with open('ipaddressifle.out', 'w') as outfile: for pdir, dir, files in os.walk(r'/Users/skandasa/perforc
os.walk()
中提到的特定文件路径,然后对该位置下的所有文件执行grep
命令,并将输出重定向到文件。下面是我创建的脚本,但是子进程
在当前目录下执行ls-al
命令,但是打印
语句向我显示os.walk
的内容。因此,我还需要子进程
来执行os.walk
路径下的命令
with open('ipaddressifle.out', 'w') as outfile:
for pdir, dir, files in os.walk(r'/Users/skandasa/perforce/projects/releases/portal-7651'):
for items in files:
print(items)
#subprocess.call(['ls', '-al'])
process = subprocess.Popen(['ls', '-al'], shell= True, stdout=outfile, stderr=outfile)
#process = subprocess.Popen(['grep', 'PORTALSHARED','*', '|', 'awk', '-F', '[','{print', '$1}'], shell= True, stdout=outfile, stderr=outfile)
[output, err] = process.communicate()
除了将cd
命令添加到子流程
调用之外,还有其他方法吗。您可以使用更改当前工作目录
我修改了您的代码片段,用于调用命令并检索其标准输出。我还使用将命令写入单个字符串,并将其正确拆分为Popen
脚本执行os.walk(DIRECTORY)
并将每个子目录中的ls-la
的输出写入output\u文件
:
import os
import shlex
from subprocess import check_output
DIRECTORY = '/tmp'
OUTPUT_FILE = '/tmp/output.log'
with open(OUTPUT_FILE, 'w') as output:
for parent, _, _ in os.walk(DIRECTORY):
os.chdir(parent)
output.write(check_output(shlex.split('ls -al')))
:
如果cwd不是None,则在执行子目录之前,子目录的当前目录将更改为cwd。
我尝试过,但它似乎不起作用。