How to use shell commands in Python, and how Python communicates with variables in the shell

Source: Internet
Author: User

1. There are several ways to use the shell command in Python, and I think it is better to use the commands module:

Import commands

A, B = commands.getstatusoutput ("Ls-al")

A is the exit state (int type), and B is the output of the shell command

Python--Shell:

1. Environment variables

Import OS
var=123 or var= ' 123 '
Os.environ[' var ']=str (Var) #environ的键值必须是字符串
Os.system (' echo $var ') or

A, B = commands.getstatusoutput ("$var")

2. String connection

Import OS
Path= '/root/a.txt '
VAR=[1]
var= ' Bash '
Os.system (' echo ' + path) #注意echo后有空格
Os.system (' echo ' + str (var[0]))
Os.system (' echo ' + var + '/root/c.sh ') #注意echo后和 a space before the/root

3. Through the pipeline

Import OS
Var= ' 123 '
Os.popen (' Wc-c ', ' W '). Write (Var)

4. Adoption of documents

Output = open ('/tmp/mytxt ', ' W ')
Output.write (S) #把字符串S写入文件
Output.writelines (L) #将列表L中所有的行字符串写到文件中
Output.close ()

5. Prepare the output by redirecting the target

BUF = open ('/root/a.txt ', ' W ')
Print >> buf, ' 123\n ', ' abc ' OR: Print >> open ('/root/a.txt ', ' W '), ' 123\n ', ' abc ' #写入或生成文件
Print >> open ('/root/a.txt ', ' a '), ' 123\n ', ' abc ' #追加

Shell-and Python:

1. Piping

Import OS
Var=os.popen (' echo-n 123 '). Read ()
Print Var

2.

Import commands
Var=commands.getoutput (' echo abc ') #输出结果
Var=commands.getstatusoutput (' echo abc ') #退出状态和输出结果

3. Documents

input = open ('/tmp/mytxt ', ' R ')
S = Input.read () #把整个文件读到一个字符串中
S = Input.readline () #读下一行 (over line end flag)
L = Input.readlines () #读取整个文件到一个行字符串的列表中

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.