简体   繁体   中英

How to run linux (ubuntu) commands in python script?

I have a program folder for which paths are required:

export RBT_ROOT=/path/to/installation/
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$RBT_ROOT/lib
export PATH=$PATH:$RBT_ROOT/bin

Then the command is run:

rbcavity -was -d -r <PRMFILE>

rbcavity - is an exe program contained in the program's bin folder

PRMFILE - is the program contained in the current path (working folder not included in the program folder)

This works from the command line, but not from python. How can I run this from a python script (3.5)? I tried subprocess.run but it doesn't find the command rbcavity... I'm new to linux and don't quite know how it works.

I usually use OS library. I am using the following commands to run and start the Cassandra server. In the end to run this, I do python filename.py

import os
os.chdir('./dsc-cassandra-3.0.9/bin')
os.system('./cassandra start')

The line

subprocess.run(["export", "PATH=$PATH:$RBT_ROOT/bin"], shell=True)

only sets the PATH environment variable in the subprocess (and any of its child processes, if it had any). Therefore, it's unchanged in your Python program which is why your executable couldn't be found.

To set an environment variable in Python, use os.setenv . Ie,

rbt_root='/path/to/installation/'
path = os.getenv('PATH')
path += ':'+rbt_root+'bin'
os.setenv('PATH',path)

EDIT:

So, it turns out that os.setenv isn't very portable. Instead, use os.environ , which is dictionary-like. Eg,

os.environ['PATH'] = path

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