0

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.

Joshua Schlichting
3,4807 gold badges33 silver badges60 bronze badges
asked Apr 15, 2020 at 15:14

2 Answers 2

1

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
answered Apr 15, 2020 at 15:20
Sign up to request clarification or add additional context in comments.

2 Comments

actually, My aim is to provide multi line code copy+paste facility for that i can not use exec() as it will give direct output . but worthy answer.
Will individual statements be in their own set of quotes for this multi line copy+paste?
0
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}")
answered Apr 26, 2020 at 8:01

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.