1

There are mainly two questions that I would like to ask, thanks in advance.

(1) How can I open an external program in Linux? I know in Windows there is a command os.startfile() to open another program, the equivalent for Ubuntu is open(), but there's no response after I run the code, and the alternative one is subprocess.call(). This works well in Windows, but in Ubuntu it fails, could someone provide a standard templete I can use for? (Similarly like to double click the icon of a program)

(2) How can I realize functions like the code is able to open the terminal and write down several commands in terminal automatically using python?

TxWang
  • 57
  • 2
  • 11

2 Answers2

0

os.system can do this work. for example, you want to run 'ls' under a shell. want_run='ls';os.system('bash -c '+ want_run);

wen
  • 114
  • 1
  • 3
0

(1) You can use proc = subprocess.Popen(command, stdout=subprocess.PIPE) and afterwards run proc.stdout.read() to get the output of the command run. See the subprocess documentation https://docs.python.org/2/library/subprocess.html

(2) Please provide more info on this question(examples) for what you want to do.

BDru
  • 21
  • 3
  • Thanks, I've figure it out the first one. For the second question, I would like to call a bash file in python, which is aimed to write down several sentences in the terminal, how could I do that? – TxWang Jul 28 '17 at 03:22
  • @TianxiangWang You can execute the bash file with the same commands subprocess.Popen(["bash", "filename.sh"]) but it will open a new instance of bash and it will execute the script there, If you're interested just in the output, that is not the problem because you can use the process stdout, but if you're interested in the environment variables set by your script, you will have to set them manually(using python environ) in the python script based on the output. – BDru Jul 28 '17 at 06:50
  • I've already done that, thanks for your information. – TxWang Jul 30 '17 at 07:00