通过将参数作为变量传递,从另一个 python 文件执行 python 文件

Execute python file from another python file by passing argument as variable

在下面的代码中,我试图获取路径名(包括文件名)并将它们转换为带有文本文件的另一个路径名。

现在我想将两个变量都作为参数传递给另一个 py,它将把它作为参数

import os

thisdir=[os.path.join(r,file) for r,d,f in 
os.walk("C:\Users\vnitin\OneDrive - NetApp Inc\IDP\Files\") for file 
in f]
for i in range(len(thisdir)):
    text_path = thisdir[i].replace('pdf', 'txt')
    print(text_path)
    os.system('py pdf2txt.py -o text_path thisdir[i]')

但是 pdf2txt.py 的单个命令效果很好。

py .\pdf2txt.py -o 'C:\Users\vnitin\OneDrive - NetApp Inc\IDP\Files.txt'  
'C:\Users\vnitin\OneDrive - NetApp Inc\IDP\Files.pdf'

由于thisdir[i]在执行过程中没有转换成它的值,所以报错No such file or directory

替换os.system('py pdf2txt.py -o text_path thisdir[i]')

os.system("python ./pdf2txt.py -o {0} {1}".format(text_path,thisdir[i]))

两种解决方案: 1)可以直接导入并调用main方法带params

data = pdf2txt.main(['pdf2txt.py',filename])

2) 形成一个字符串并作为命令传递

    string ="py .\pdf2txt.py -o" +" C:\Users\vnitin\OneDrive - NetApp Inc\IDP\Files.txt"+" C:\Users\vnitin\OneDrive - NetApp Inc\IDP\Files.pdf"

使用SubProcess module

import subprocess
subprocess.Popen("python ./pdf2txt.py -o {0} {1}".format(text_path,thisdir[i])", shell=True)

现在,stdin、stdout 和 stderr 也可以重定向。