运行 一个 python 脚本在另一个脚本中使用子进程

Running one python script within another script using subprocess

我正在编写一个脚本来遍历目录,并将所有 python2 文件转换为 python3。 有一个实用程序 (2to3.py) 可以实现这一点。 (我正在使用 python2.7 解释器)

我有以下代码:

import os
import subprocess
import pathlib

APP_FOLDER = 'C:/Users/XXXX/Test/'

for dirpath, dirnames, filenames in os.walk(APP_FOLDER):
    for inputFile in filenames:
        if pathlib.Path(inputFile).suffix == ".py":
            file_path = os.path.join(dirpath, inputFile)
            with open(file_path) as f:
                num_lines = len(f.readlines())
            print dirpath
            print inputFile
            print "lines of code: ", num_lines
            print "converting to python 3"
            cmd ="py C:\Python27\Tools\Scripts\2to3.py "+inputFile+" -w"
            p1=subprocess.Popen(cmd,shell=True)
            p1.wait()
            if p1.returncode ==0:
                print "Success"
            else:
                print "failure"

在提到的路径中,我有一个名为“FolderA”的子目录,其中有一个简单的 python 文件,其语法为 python2 和一个除法运算。

我收到如下错误:

C:/Users/XXXX/Test/FolderA
Sample.py
lines of code:  7
converting to python 3
RefactoringTool: Skipping optional fixer: buffer
RefactoringTool: Skipping optional fixer: idioms
RefactoringTool: Skipping optional fixer: set_literal
RefactoringTool: Skipping optional fixer: ws_comma
RefactoringTool: Can't open Sample.py: [Errno 2] No such file or directory: 'Sample.py'
RefactoringTool: No files need to be modified.
RefactoringTool: There was 1 error:
RefactoringTool: Can't open Sample.py: [Errno 2] No such file or directory: 'Sample.py'
failure
-------------------*************--------------------

我做错了什么?

尝试使用,cmd ="py C:\Python27\Tools\Scripts\2to3.py "+file_path+" -w"

尝试将其更改为:

import os
import subprocess
import pathlib

APP_FOLDER = 'C:/Users/XXXX/Test/'

for dirpath, dirnames, filenames in os.walk(APP_FOLDER):
    for inputFile in filenames:
        if pathlib.Path(inputFile).suffix == ".py":
            file_path = os.path.join(dirpath, inputFile)
            with open(file_path) as f:
                num_lines = len(f.readlines())
            print dirpath
            print inputFile
            print "lines of code: ", num_lines
            print "converting to python 3"
            cmd = "py C:\Python27\Tools\Scripts\2to3.py "+file_path+" -w"
            p1=subprocess.Popen(cmd,shell=True)
            p1.wait()
            if p1.returncode ==0:
                print "Success"
            else:
                print "failure"

您还需要将 dirpathinputFile 组合用于命令。对于您的情况,将 inputFile 替换为 file_path 应该可以修复错误,因为您已经在代码中定义了 file_path = os.path.join(dirpath, inputFile)

此外,代码中还存在这些问题,在某些情况下可能会导致错误:

  1. cmd 中的某些 \ 个字符未转义。要解决此问题,您可以使用原始字符串文字语法,例如 r'''path\no\need\to\escape''';
  2. 您确实应该为 Popen 函数使用 list 输入格式,否则如果您的文件路径包含空格,命令将失败。 Popen(['/path/to/py', 'arg1', 'arg2' ...])