Nirmal Patel
Nirmal Patel

Reputation: 61

How can I execute command line arguments as if they were code?

i want to develop a program in which i can pass python code as command line argument and it run as command.

To explain it,

cmd>python temp.py print('nirmal')
print('patel')

Output should be

>>>print('nirmal')
nirmal
>>>print('patel')
patel

Tried code:

import sys
from subprocess import Popen,PIPE

data = sys.stdin.readlines()
#print(data)

process=Popen("python",shell=True)
process.wait()

output of above code This code runs python shell but how to input python code as argument ?

If you have any other alternative for same purpose please let me know.

Upvotes: 0

Views: 277

Answers (2)

Nirmal Patel
Nirmal Patel

Reputation: 61

import win32com.client
import sys
import sys
from subprocess import Popen,PIPE,call
import time
# process=Popen("pip list --outdated",stdout=PIPE,stdin=PIPE,shell=True,bufsize=1)
# data= process.stdout.readlines()

# for i in range(2,len(data)):
#   temp=data[i].decode("utf-8").split(' ')
#   print(temp[0])
#   command="runas /user:administrator 'pip install {0} --upgrade'".format(temp[0])
#   print(command)

shell = win32com.client.Dispatch("WScript.Shell")
# shell.AppActivate("Outlook")
shell.SendKeys('runas /user:administrator "pip install pip --upgrade"{ENTER}')
shell.SendKeys("password{ENTER}")
print(shell)
shell.SendKeys('runas /user:administrator "pip install pygame"{ENTER}')
shell.SendKeys("password{ENTER}")

Upvotes: 0

Joshua Schlichting
Joshua Schlichting

Reputation: 3450

I believe you could carry this out using exec().

import sys

for i in range(1, len(sys.argv)):
    exec(sys.argv[i])

NOTE: The range starts with 1, because sys.argv[0] will be the name of your script.

Tested results in a bash terminal:

josh@josh-desktop:~$ python3 test.py "x = 1 + 1" "print(str(x))"
2

Upvotes: 1

Related Questions