I am working on a script to walk over a directory, and convert all the python2 files to python3. There is a utitliy (2to3.py) to acheive that. ( I am using python2.7 interpreter)
I have the following code:
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"
At the path mentioned, I have a subdirectory named "FolderA" and within that there is a simple python file having the syntax of python2 and a division operation.
I receive an error as below:
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
-------------------*************--------------------
What am I doing wrong here?
Try using, cmd ="py C:\Python27\Tools\Scripts\\2to3.py "+file_path+" -w"
try change it to this:
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"
You need to combine dirpath with inputFile for the command as well. For your case, replace inputFile with file_path should fix the error since you already have file_path = os.path.join(dirpath, inputFile) defined in the code.
Also there're these issues in the code that may cause error in certain cases:
\ characters in your cmd are not escaped. To fix this you may use the raw string literals syntax, like r'''path\no\need\to\escape''';list input format for the Popen function, otherwise the command would fail if your file path contains spaces. Popen(['/path/to/py', 'arg1', 'arg2' ...])