set bash variable from python script

前端 未结 2 1114
礼貌的吻别
礼貌的吻别 2021-01-23 12:32

i\'m calling a python script inside my bash script and I was wondering if there is a simple way to set my bash variables within my python script.

Example:

My bas

相关标签:
2条回答
  • 2021-01-23 12:55

    shlex.quote() in Python 3, or pipes.quote() in Python 2, can be used to generate code which can be evaled by the calling shell. Thus, if the following script:

    #!/usr/bin/env python3
    import sys, shlex
    print('export foobar=%s' % (shlex.quote(sys.argv[1].upper())))
    

    ...is named setFoobar and invoked as:

    eval "$(setFoobar argOne)"
    

    ...then the calling shell will have an environment variable set with the name foobar and the value argOne.

    0 讨论(0)
  • 2021-01-23 13:17

    No, when you execute python, you start a new process, and every process has access only to their own memory. Imagine what would happen if a process could influence another processes memory! Even for parent/child processes like this, this would be a huge security problem.

    You can make python print() something and use that, though:

    #!/usr/bin/env python3
    
    print('Hello!')
    

    And in your shell script:

    #!/usr/bin/env bash
    
    someVar=$(python3 myscript.py)
    echo "$someVar"
    

    There are, of course, many others IPC techniques you could use, such as sockets, pipes, shared memory, etc... But without context, it's difficult to make a specific recommendation.

    0 讨论(0)
提交回复
热议问题