Nitin
Nitin

Reputation: 476

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

In the below code, I am trying to take the path name (inclusive of file name) and converting them to another path name with text file.

Now I would like to pass both variable as argument for another py which will take it as argument

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]')

But individual command for pdf2txt.py works very well.

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

Upvotes: 0

Views: 357

Answers (3)

Abhishake Gupta
Abhishake Gupta

Reputation: 3170

Use SubProcess module

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

Now, stdin, stdout, and stderr can also be redirected.

Upvotes: 0

Abhishake Gupta
Abhishake Gupta

Reputation: 3170

since thisdir[i] is not converted to its value during execution, so the error No such file or directory

Replace os.system('py pdf2txt.py -o text_path thisdir[i]') with

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

Upvotes: 1

Hari
Hari

Reputation: 334

Two Solutions: 1)You can directly import and call the main method with params

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

or

2) Form a string and pass it as a command

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

Upvotes: 0

Related Questions