Способы запуска программы на python

Автор: Igor Kirsanov

Сборник различных способов запуска программ на python, информация скопирована с различных источников. Рекомендуемый способ запуска через subprocess

import sys
sys.argv = ['arg1', 'arg2']
execfile("C:/test.py") 


import os
os.system("C:/test.bat") 


import subprocess
filepath="C:/test.bat"
p = subprocess.Popen(filepath, shell=True, stdout = subprocess.PIPE)
stdout, stderr = p.communicate()

# By default subprocess.call doesn't use a shell to run our commands you so can't shell commands like cd    
subprocess.call("(cd ~/catkin_ws/src && catkin_make)", shell=True)
bashCommand = "cwm --rdf test.rdf --ntriples > test.nt"
import subprocess
process = subprocess.Popen(bashCommand.split(), stdout=subprocess.PIPE)
output, error = process.communicate()
import subprocess
subprocess.Popen("cwm --rdf test.rdf --ntriples > test.nt")

subprocess.call() creates a new process. The cd works in that process, but when the process exits it won't affect the current process. This is how processes are designed to work. If you need your script to change to a different directory you can use os.chdir which will change the directory for the current process.

import os 
os.getcwd()
os.system('pwd')
os.environ["HOME"]
os.chdir(os.path.expanduser('~') + '/.cache/thumbnails')
os.getcwd()
os.system('subl')

The Basics

import subprocess
(out,err) = subprocess.Popen(['echo','Hello World!'],stdout=subprocess.PIPE).communicate()
print out

Specifying Arguments

#date '+%Y-%m-%d %H:%M:%S'
import subprocess
command = ['date']
command.append('+%Y-%m-%d %H:%M:%S')
(out,err) = subprocess.Popen(command,stdout=subprocess.PIPE).communicate()
print out

Writing Standard Input

import subprocess
command = ['python']
process = subprocess.Popen(command,stdout=subprocess.PIPE,stdin=subprocess.PIPE)
(out,err) = process.communicate("""x = 5
y = 6
print str(x+y)""")
print out

Reading Standard Output

import subprocess
(out,err) = subprocess.Popen(['ls','-alsh'],stdout=subprocess.PIPE).communicate()
print out

Reading Standard Error

# grep -i 'what' this_file_is_no_here
import subprocess
command = ['grep']
command.append('-i')
command.append('what')
command.append('this_file_is_no_here')
(out,err) = subprocess.Popen(command,stderr=subprocess.PIPE).communicate()
print err # NOTE, i'm printing the error, not the output

Manual Pipes

# echo 'Hello World' | grep -i -o 'hello' -e 's/$/!/' | tr '[:lower:]' '[:upper:]'
import subprocess

# print 'Hello World' to stdout
command1 = ['echo']
command1.append('Hello World')
process1 = subprocess.Popen(command1,stdout=subprocess.PIPE)

# Find 'hello' in the input and print that match to stdout
command2 = ['grep']
command2.append('-o')
command2.append('-i')
command2.append('hello')
process2 = subprocess.Popen(command2,stdin=process1.stdout,stdout=subprocess.PIPE)

# Make any lowercase letter in the input uppercase in the output
command3 = ['tr']
command3.append('[:lower:]')
command3.append('[:upper:]')
process3 = subprocess.Popen(command3,stdin=process2.stdout,stdout=subprocess.PIPE)

# Get the stdout and stderr text
(out,err) = process3.communicate()

print out

Setting the working directory

# cd /tmp/example/a/b/c
# cat da_file_1 da_file_2
import subprocess

working_directory = '/tmp/example/a/b/c'

command = ['cat']
command.append('da_file_1')
command.append('da_file_2')

process = subprocess.Popen(command,stdout=subprocess.PIPE,cwd=working_directory)

(out,err) = process.communicate()

print out