Source command linux python

Linux shell source command equivalent in python

Too much work for the return. Going to keep a small shell script to get all the env vars that we need and forget reading them into python.

Similar question

if os.path.exists ("/etc/rc.platform"): os.system("/etc/rc.platform") 

Since source is a shell builtin, you need to set shell=True when you invoke subprocess.call

>>> import os >>> import subprocess >>> if os.path.isfile("/etc/rc.platform"): . subprocess.call("source /etc/rc.platform", shell=True) 

I’m not sure what you’re trying to do here, but I still wanted to mention this: /etc/rc.platform might export some shell functions to be used by other scripts in rc.d . Since these are shell functions, they would be exported only to the shell instance invoked by subprocess.call() and if you invoke another subprocess.call() , these functions would not be available since you’re spawning a fresh new shell to invoke the new script.

(Here’s a demonstration of the solution crayzeewulf described in his comment.)

If /etc/rc.platform only contains environment variables, you can read them and set them as env vars for your Python process.

$ cat /etc/rc.platform FOO=bar BAZ=123 

Read and set environment variables:

>>> import os >>> with open('/etc/rc.platform') as f: . for line in f: . k, v = line.split('=') . os.environ[k] = v.strip() . >>> os.environ['FOO'] 'bar' >>> os.environ['BAZ'] '123' 

A somewhat hackish solution is to parse the env output:

newenv = <> for line in os.popen('. /etc/rc.platform >&/dev/null; env'): try: k,v = line.strip().split('=',1) except: continue # bad line format, skip it newenv[k] = v os.environ.update(newenv) 

Edit: fixed split argument, thanks to @l4mpi

  • Starting multiple instances of a python script at once from linux command line
  • Python execute complex shell command
  • How do I call a python script on the command line like I would call a common shell command, such as cp?
  • python execute shell command with wildchar in path
  • Python run shell command over specific folder
  • Why does this valid shell command throw an error in python via subprocess?
  • Python or linux command line detect directory name in .tar.gz
  • need equivalent python command for p4 describe
  • What is the python ‘requests’ api equivalent to my shell scripts curl command?
  • Python and shell command
  • Paramiko not executing command or shell — Python
  • Using command line arguments in python rather than shell
  • Python equivalent for write in file like in shell
  • python shell command — why won’t it work?
  • Why are Git log command outputs different when launched from Windows shell and from Python subprocess?
  • Why SHA sum is different when calculated by python and linux command line program?
  • Execute a shell command with python variables
  • Execute shell command from Python Script
  • Reading from linux command line with Python
  • Using linux ‘screen’ command from python
  • Is it possible to execute a python script from a bash login shell with a one-line command from a non-login shell?
  • how to set proxy value and run linux command in python
  • Linux Command for Perl in Python
  • How can I create one linux shell command out of two commands that behaves like standard piping?
  • How to make python and linux shell interaction?
  • which command equivalent in Python
  • chain the function as shell pipe command in python
  • Launch ipython shell from python script that uses command line option parsing
  • Append results from a shell command to a list in Python
  • Append results from a shell command to a list in Python
  • Append results from a shell command to a list in Python
  • Install python on Linux from source with custom paths
  • How to get the command & arguments that was executed in shell with python
  • How to use linux command in python with python functions (sys.argv)
  • Execute shell command using Python subprocess
  • How to run linux terminal command in python in new terminal
  • How to run command within an interactive shell via python (boto for AWS)
  • How to call external input and output file names to run Python Programs at Linux Command Prompt
  • python return list from linux command output
  • Suppress verbose output of shell command in python
Читайте также:  Сервер локального времени linux

More Query from same tag

  • SSLError: («bad handshake: SysCallError(54, ‘ECONNRESET’)»,)
  • How can I see if a list contains another list in Python?
  • pandas in python showing full content of a data frame
  • Why is Entry.get() one key behind?
  • Python — Python 3.1 can’t seem to handle UTF-16 encoded files?
  • Where is the implementation of cpython’s list type?
  • Is there any way to copy all parameters of one Pytorch model to another specially Batch Normalization mean and std?
  • Get substring from a string with specific pattern
  • How to load JSON config file in cement python app?
  • Compare «similar» numbers in Python
  • pip install Command errored out with exit status 1
  • Which dynamic language can easily use libraries from other languages?
  • matplotlib, rectangular plot in polar axes
  • translate ‘aa’ to ‘a’ and ‘ab’ to ‘b’ in python
  • Review my Django Model — Need lots of suggestions
  • Requests giving errors while importing Python 3.4.2
  • pyOpenGL GLUT window function doesn’t close properly
  • Update data in a Tkinter-GUI with data from a second Thread
  • SQL returning extra data
  • My chess-board validation program works, but gives an incorrect result
  • Pygame rescaling game-resolution + coordinates
  • How to see if there is one microphone active using python?
  • Running a script on VPython 6.05 returns ‘Just-in-time debugging, errors’
  • Link comparison operators the way it works on algebra
  • How to «add a folder to PYTHONPATH»?
  • Returning the indices of elements in a list
  • Log a string without ending newline
  • Python and subprocess input piping
  • create a dynamic list of list from a list of list using random
  • Use decorators to retrieve jsondata if file exists, otherwise run method and then store output as json?
  • Using a python script which reads a 77gb file into memory to scan for keywords, the code works but my computer doesn’t have enough ram
  • Finding all combinations of paths from a graph with a given distance from the origin
  • Missing intellisense, autocompletion in for loop
  • Input to reshape is a tensor with 40804 values, but the requested shape has 10201
  • Non greedy match of .* with ^
Читайте также:  Линукс добавление статического маршрута

Источник

Linux shell source command equivalent in python [duplicate]

Converting a shell script to python and trying to find the best way to perform the following. I need this as it contains environment variables I need read.

if [ -e "/etc/rc.platform" ]; then . "/etc/rc.platform" fi 

I have the ‘if’ converted but not sure how to handle the . «/etc/rc.platform» as source is a shell command. So far I have the following

if os.path.isfile("/etc/rc.platform"): print "exists"  

I’ve looked at subprocess and execfile without success. The python script will need to access the environment variables set by rc.platform

You will have to parse /etc/rc.platform , extract environment variable names and values, and update os.environ accordingly.

@crazyeewulf — It is not just about environment variables, there could also be bash functions that could be exported by the script. How do you plan to use them from the python script, unless you somehow try to reuse the same shell for all the scripts which are invoked.

If you are trying to re-write the script in python, then you will very likely want to rewrite /etc/rc.platform in python. If it is merely making variable assignment, you can make it a config file. In the general case, what you are trying to do is difficult.

@Tuxdude you are correct for a general case. But OP mentioned in the question that «I need this as it contains environment variables I need read.» So I expected that OP probably does not care about anything other than environment variables from this file.

5 Answers 5

A somewhat hackish solution is to parse the env output:

newenv = <> for line in os.popen('. /etc/rc.platform >&/dev/null; env'): try: k,v = line.strip().split('=',1) except: continue # bad line format, skip it newenv[k] = v os.environ.update(newenv) 

Edit: fixed split argument, thanks to @l4mpi

Читайте также:  Command line linux debian

(Here’s a demonstration of the solution crayzeewulf described in his comment.)

If /etc/rc.platform only contains environment variables, you can read them and set them as env vars for your Python process.

$ cat /etc/rc.platform FOO=bar BAZ=123 

Read and set environment variables:

>>> import os >>> with open('/etc/rc.platform') as f: . for line in f: . k, v = line.split('=') . os.environ[k] = v.strip() . >>> os.environ['FOO'] 'bar' >>> os.environ['BAZ'] '123' 

This won’t work if the variables reference other variables in their declaration, e.g. X=»$Y/foo» . Also, the script could use other shell commands (like awk, grep, etc) or builtin shell variables, which would obviously not be evaluated.

Good points. I guess the consensus here is that there’s no easy way for this to work, except in the very simplest case that I used as an example.

I needed something similar once and ended up spawning a subshell, sourcing the script and then parsing the output of env . maybe I’ll write up an answer after dinner.

Too much work for the return. Going to keep a small shell script to get all the env vars that we need and forget reading them into python.

if os.path.exists ("/etc/rc.platform"): os.system("/etc/rc.platform") 

This will not have the same effect as the shell script quoted by OP. os.system runs the command in a subshell and, hence, the parent process will not see any environment variables added/modified by /etc/rc.platform .

You cannot source sh or bash script within a python process, which doesn’t know how to interpret bash language. Hence you need a subshell to run bash and interpret the script. Since it is done in a subshell, the python process won’t be able to get the new env values.

Since source is a shell builtin, you need to set shell=True when you invoke subprocess.call

>>> import os >>> import subprocess >>> if os.path.isfile("/etc/rc.platform"): . subprocess.call("source /etc/rc.platform", shell=True) 

I’m not sure what you’re trying to do here, but I still wanted to mention this: /etc/rc.platform might export some shell functions to be used by other scripts in rc.d . Since these are shell functions, they would be exported only to the shell instance invoked by subprocess.call() and if you invoke another subprocess.call() , these functions would not be available since you’re spawning a fresh new shell to invoke the new script.

Источник

Оцените статью
Adblock
detector