Python子进程在循环中调用时不输出到文件

2024-06-30 15:49:22 发布

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

有谁能解释一下,当我打开一个子进程并告诉它输出到文件时,它会工作的原因:

currentSharePath = '\\\Path1'
p = subprocess.Popen([r'powershell.exe',
              '-ExecutionPolicy',
              'Bypass',
              os.path.dirname(os.path.abspath(__file__))+'\subFoldersClassifier.ps1',
              '-sharePath',
              currentSharePath,
              '2>$null',
              '| Out-File -encoding utf8 -append classified_subFolders.txt'], 
              stdout=sys.stdout)
p.communicate()

但当我在循环中调用它时,输出显示在我的终端上,而不是文件上:

^{pr2}$

提前谢谢你


Tags: 文件path进程osstdout原因exesubprocess
1条回答
网友
1楼 · 发布于 2024-06-30 15:49:22

问题不在于循环,而是readlines()方法在每行的末尾插入一个换行符。在

因此,您的一个参数包含一个换行符,这可能足以结束命令行(并跳过下一行中完成的重定向,它不起任何作用)

可能的修复,strip后面的换行符:

for currentSharePath in content:
    currentSharePath = currentSharePath.rstrip()

或者像这样生成行列表:

^{pr2}$

相关问题 更多 >