Several ways to pass python and shell variables to each other
- 2020-04-02 13:11:59
- OfStack
Python - > Shell:
1. Environment variables
import os
var=123 or var='123'
os.environ['var']=str(var) #environ Must be a string
os.system('echo $var')
import os
var=123 or var='123'
os.environ['var']=str(var) #environ Must be a string
os.system('echo $var')
2. String concatenation
import os
path='/root/a.txt'
var=[1]
var='bash'
os.system('echo ' + path) # Pay attention to echo After the blank space
os.system('echo ' + str(var[0]))
os.system('echo ' + var + ' /root/c.sh') # Pay attention to echo And after /root There is a space before
import os
path='/root/a.txt'
var=[1]
var='bash'
os.system('echo ' + path) # Pay attention to echo After the blank space
os.system('echo ' + str(var[0]))
os.system('echo ' + var + ' /root/c.sh') # Pay attention to echo And after /root There is a space before
3. Through the pipe
import os
var='123'
os.popen('wc -c', 'w').write(var)
The same code at the page code block index 4
4. Go through the paperwork
output = open('/tmp/mytxt', 'w')
output.write(S) # Put the string S Written to the file
output.writelines(L) # Will list L All line strings are written to the file
output.close()
output = open('/tmp/mytxt', 'w')
output.write(S) # Put the string S Written to the file
output.writelines(L) # Will list L All line strings are written to the file
output.close()
5. Redirects the standard standby output
buf = open('/root/a.txt', 'w')
print >> buf, '123n', 'abc'
The same code at the page code block index 8
or
print >> open('/root/a.txt', 'w'), '123n', 'abc' # Write to or generate a file
print >> open('/root/a.txt', 'a'), '123n', 'abc' # additional
print >> open('/root/a.txt', 'w'), '123n', 'abc' # Write to or generate a file
print >> open('/root/a.txt', 'a'), '123n', 'abc' # additional
Shell - > Python:
1. The pipe
import os
var=os.popen('echo -n 123').read( )
print var
The same code at the page code block index 12
2.
import commands
var=commands.getoutput('echo abc') # The output
var=commands.getstatusoutput('echo abc') # Exit status and output results
import commands
var=commands.getoutput('echo abc') # The output
var=commands.getstatusoutput('echo abc') # Exit status and output results
3. The file
input = open('/tmp/mytxt', 'r')
S = input.read( ) # Read the entire file into a string
S = input.readline( ) # Read the next line (past the line end mark)
L = input.readlines( ) # Reads the entire file into a list of line strings
input = open('/tmp/mytxt', 'r')
S = input.read( ) # Read the entire file into a string
S = input.readline( ) # Read the next line (past the line end mark)
L = input.readlines( ) # Reads the entire file into a list of line strings