简体   繁体   中英

Execute sh in subdirectory from main.py script?

I am trying to do the following thing. I have a python project with this dir-tree:

Project dir
  |
  |___main.py
  |___module
       |
       |__a.py
       |__a.sh

a.py has a class with a method that runs the script:

class A():
    def run():
        os.system('a.sh')

And a.sh creates a file:

touch a.txt

And main.py instantiates an object of class A and calls run() :

a = A()
a.run()

When main is called, I get an error saying that the script a.sh is not found . I get why that happens, it's because the working dir is equal to the project root path, but how can I make it work so that the file created ends up in the root path?

I want to call main.py and end up with this configuration.

Project dir
  |
  |___a.txt
  |___main.py
  |___module
       |
       |__a.py
       |__a.sh

I could replace the call to a.sh in a.py to

os.system('module/a.sh')

And it would work, but it does not look clean to me.

Code in the a.py module can extract the name of the directory it is in and use that in the os.system() call. This is what I mean:

File a.py :

import os

class A():
    def run(self):
        my_directory = os.path.dirname(__file__)
        script_path = os.path.join(my_directory, 'a.sh')
        os.system(script_path)

a = A()
a.run()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM