Using Python to open a shell environment, run a command and exit environment

前端 未结 5 1143
感动是毒
感动是毒 2020-12-19 04:39

I\'m trying to automate a process using python. If I am just in the terminal the workflow looks like:

user:> . /path/to/env1.sh
user:> python somethin         


        
相关标签:
5条回答
  • 2020-12-19 05:11

    subprocess calls (particular Popen) accepts an env argument which is a mapping of environement variables to values. You can use that. e.g.

    env = {'FOO': 'Bar', 'HOME': '/path/to/home'}
    process = subprocess.Popen(['python', 'something.py'], env=env)
    

    Of course, usually, it's better to just call some functions after *import*ing something.py instead of spawning a whole new process.

    0 讨论(0)
  • 2020-12-19 05:18

    Here is a help for you.... For running command you could do:

    1)

    from subprocess import call
    call(["ls", "-l"])
    

    2)

    import os
    os.system("command")
    

    Example:

    import os
    f = os.popen('date')
    now = f.read()
    print "Today is ", now
    

    For enabling terminal you can import os module:

    import os
    os.system('python script.py')
    

    Or as mentioned you can use import subprocess

    0 讨论(0)
  • 2020-12-19 05:27

    You can use subprocess:

    >>> import subprocess
    >>> subprocess.call('python something.py', shell = True)
    

    Or you can use os:

    >>> import os
    >>> os.system('python something.py')
    

    Here is an example (turn on your speakers):

    >>> import os
    >>> os.system('say Hello')
    
    0 讨论(0)
  • 2020-12-19 05:35
    p = subprocess.Popen(". /path/to/env.sh", shell = True, stdout=subprocess.PIPE).communicate()
    subprocess.call("python something.py", shell = True).communicate()
    
    0 讨论(0)
  • 2020-12-19 05:37

    As I understand you want to run a command and then pass it other commands:

    from subprocess import Popen, PIPE
    
    p = Popen("/path/to/env.sh", stdin=PIPE)   # set environment, start new shell
    p.communicate("python something.py\nexit") # pass commands to the opened shell
    
    0 讨论(0)
提交回复
热议问题