Transfer variable method between shell and Python __python

Source: Internet
Author: User
method of passing variables between shell and Python(2013-02-12 18:02:47) reprint
Category: Shell_vim

Python-> Shell:

1. Environment variables

[Python] View plain copy import os var=123 or var= ' 123 ' os.environ[' var ']=str (Var) #environ的键值必须是字符串 Os.syst EM (' echo $var ')


2. String concatenation [Python] view plain copyImportOs 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后和/root with space before
3. Through the pipeline
[Python] View plain copyImportOs var= ' 123 ' Os.popen (' wc-c ', ' W '). Write (Var)
4. Adoption of the document
[Python] View plain copy output = open ('/tmp/mytxt ', ' W ') Output.write (S) #把字符串S写入文件 output.writelines (L) #将列表L中 All line strings are written to the file Output.close ()
5. Prepare the output through the redirection marker
[Python] View plain copy buf = open ('/root/a.txt ', ' W ')Print>> buf, ' 123\n ', ' abc ' or
[Python] View plain copyPrint>> open ('/root/a.txt ', ' W '), ' 123\n ', ' abc ' #写入或生成文件Print>> open ('/root/a.txt ', ' a '), ' 123\n ', ' abc ' #追加

Shell-> python:

1. Pipe [python]  View Plain copy import  os   var=os.popen (' echo -n  123 '). Read ( )    print  var  
2.
[python]  View Plain copy import  commands   var=commands.getoutput (' Echo  abc ')         #输出结果    var=commands.getstatusoutput (' echo  ABC ')   #退出状态和输出结果   

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.