0

I am new in python, i just open .py file and write this command inside the file "sudo vbetool dpms off". But while run the file, it shows invalid syntax. How to write this command to python file.

Viswa
  • 169
  • 1
  • 4
  • 11

3 Answers3

2

Use the standard library subprocess

import subprocess
passwd='mypassword'
subprocess.call('echo %s|sudo -S vbetool dpms off' % passwd, shell=True)
iMom0
  • 12,493
  • 3
  • 49
  • 61
  • but it ask sudo password. i need to run this code without password. if it works like that, it is very useful to me. Please provide me the solution – Viswa Jun 06 '12 at 04:02
  • it seems duplicated to http://stackoverflow.com/questions/5191878/change-to-sudo-user-within-a-python-script – iMom0 Jun 06 '12 at 04:04
  • @Viswa: You should learn to accept and vote on answers that has been helpful to you :) – pyfunc Jun 06 '12 at 05:39
  • Its work properly, but i am not suppose to defined my password in script. Instead of that,if system automatically retrieved password means its very convenient to me. Is there any chance to do like that. – Viswa Jun 07 '12 at 09:49
0

Use sudo -S which is used to read password from stdin rather than terminal.Store it in a file,say passwd and then do:

import os
os.system("sudo -S vbetool dpms off < passwd")
rjv
  • 6,058
  • 5
  • 27
  • 49
0

Or

You could use pexpect library which is commonly used to automate programs that require user inputs.

import pexpect

child = pexpect.spawn('sudo vbetool dpms off')
child.expect('Password:')
child.sendline(password)
child.expect(pexpect.EOF, timeout=None)
output_data =  child.before

Here, you just provide the matching prompt that you are expecting and then you send the password. After that you can collect the output and process it.

This is more generic and is useful when you have programs that does not accept piping of password.

you can install this module with

easy_install pexpect
or
pip install pexpect
pyfunc
  • 65,343
  • 15
  • 148
  • 136