Command line execution in different folder

后端 未结 3 1178
眼角桃花
眼角桃花 2020-12-10 00:20

I\'m calling a command line program in python using the os.system(command) call.

How can I call this command passing a different folder for execution? T

3条回答
  •  忘掉有多难
    2020-12-10 01:04

    Here, I made a little function to change the path you're working on :

    import os
    def make_path(r_path):  
        ack = 1
        try:
            root = os.path.dirname(__file__)
            rel_path = os.path.join("..", r_path)
    
            abs_path = os.path.join(root, rel_path)
            os.chdir(abs_path)
            ack = 0
        except Exception as details:
            print('problem to get to the path '+r_path+' (0001) : ' + str(details))
        return ack
    

    So here, r_path is the relative path you want to go to. I added ".." to the path.join() methode so, if you're in a folder and want to exit it before searching for your path, it does it automatically. So, if your relative directory looks like this :

    -path_to_reach
        -a_random_file.txt
    -your_current_folder
        -your_program.py
    

    you can do those lines to go inside the path_to_reach and make your command, in exemple :

    command = ls
    make_path('path_to_reach/')
    os.system(command)
    

    This command would not be useful, but you see the idea!

提交回复
热议问题