How do Python subshell and Linux shell produce different results?

Ondřej Doležal :

I have a folder with subfolders containing .pp Puppet manifest files. I found out that I can use puppet strings tool to convert .pp files into json.

This can be easily achieved using Unix terminal, running command puppet strings generate --format json file_name.pp.

I wrote a simple python script to iterate over all the files in the specific directory and its subdirectories and run this command on every file.

Sadly, I am getting only empty puppet strings template without any content when running the script, (I implemented printing out the commands that are called), however using the commands works perfectly fine inside Unix terminal.

Please, what am I doing wrong that the commands work in Unix shell but not inside Python's subshell?

Here is the code:

import os


def generate_json():
    for dirpath, dirnames, filenames in os.walk(
            '/home/odolezal/PycharmProjects/puppet_parser/files/'):
        for filename in [f for f in filenames if f.endswith(".pp")]:
            print(os.path.join(dirpath, filename))
            print('puppet strings generate --format json ' + filename)
            os.system('puppet strings generate --format json ' + str(filename))

if __name__ == "__main__":
    generate_json()
Ondřej Doležal :

I found the answer - changing the last function line to os.system('puppet strings generate --format json ' + os.path.join(dirpath, filename)) works perfectly as I forgot the script does not change the current dir when operating on subdirectories and files inside them.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=220386&siteId=1