How to re-call a python script inside yourself

I am trying to find a better way to call a Python script inside myself. It currently works as http://github.com/benoitc/gunicorn/blob/master/gunicorn/arbiter.py#L285 . START_CTXcreated by http://github.com/benoitc/gunicorn/blob/master/gunicorn/arbiter.py#L82-86 .

The code is used as the "calling" sys.argv[0]code. However, this fails when it is called using:

python script.py ...

This case works:

python ./script.py ...

because the code uses os.chdirbefore running os.execlp.

I noticed os.environ["_"], but I'm not sure how reliable it will be. Another possible case is to check that sys.argv[0]it is not on PATHand is not executable, and use it sys.executablewhen calling os.execlp.

Any thoughts on a better approach to solving this problem?

+3
source share
2 answers

I think the real problem here is that the gunicorn / arbiter.py code wants to execute a Python script each time with the same environment. This is important because the Python script that is being called is unknown, and it is important that it be called exactly every time .

I feel that the problem you are facing is due to a change in environment between calls to the Python script by the arbiter.

os.environ - (.. PWD), ( ). , , , cwd START_CTX. , : invocation?

, :

#!/usr/bin/env python
import sys
import os

def main():
    """Execute twice"""

    cwd = os.getcwd()

    print cwd
    print sys.argv

    if os.path.exists("/tmp/started.txt"):
        os.unlink("/tmp/started.txt")
        print "Deleted /tmp/started.txt"
        print
        return

    args = [sys.executable] + sys.argv[:]
    os.system("touch /tmp/started.txt")
    print "Created /tmp/started.txt"
    print
    os.execvpe(sys.executable, args, os.environ)

if __name__ == '__main__':
    main()

, :

guest@desktop:~/Python/Test$ python selfreferential.py 
/Users/guest/Python/Test
['selfreferential.py']
Created /tmp/started.txt

/Users/guest/Python/Test
['selfreferential.py']
Deleted /tmp/started.txt

guest@desktop:~/Python/Test$ python ./selfreferential.py 
/Users/guest/Python/Test
['./selfreferential.py']
Created /tmp/started.txt

/Users/guest/Python/Test
['./selfreferential.py']
Deleted /tmp/started.txt

guest@desktop:~/Python/Test$ cd
guest@desktop:~$ python Python/Test/selfreferential.py 
/Users/guest
['Python/Test/selfreferential.py']
Created /tmp/started.txt

/Users/guest
['Python/Test/selfreferential.py']
Deleted /tmp/started.txt

guest@desktop:~$ python /Users/guest/Python/Test/selfreferential.py 
/Users/guest
['/Users/guest/Python/Test/selfreferential.py']
Created /tmp/started.txt

/Users/guest
['/Users/guest/Python/Test/selfreferential.py']
Deleted /tmp/started.txt

guest@desktop:~$ 

, , , . , , - . , , , -.

+1

. script , script, , .

0

Source: https://habr.com/ru/post/1745715/


All Articles