I'm doing it with the os.popen function in Python, but it doesn't work. Help mecrying

Asked 2 years ago, Updated 2 years ago, 68 views

import os
def run(command):
    file = open("tmp.py", 'w')
    file.write(command)
    file.close()
    res = os.popen("sudo python3 tmp.py -f").read()
    return res
res = run ("Hello")
print("Result"+res+"")

So, this is how we built the code together and ran it.

Traceback (most recent call last):
  File "tmp.py", line 1, in <module>
    Hello
NameError: name 'Hello' is not defined

It pops up in the terminal window Result That's all it says. I'd appreciate your help. I'm trying to run Python code on Python, so I'd appreciate your help.

python operating-system

2022-09-22 20:04

1 Answers

I'm writing "hello" on tmp.py...tmp.py doesn't even fit Python grammar, would it work?

And why do you have to do it with an external process when you run a Python script on Python?

file = open("tmp.py", 'w')
file.write("print('aaaaa')")
file.close()

import tmp

It's done like this. Of course, if you need to get the results, you can work on it as a function and call it.

file = open("tmp.py", 'w')
file.write("def show():return 'aaaaa'")
file.close()

import tmp
s = tmp.show()
print(s)

Nevertheless, if you want to make the questioner's code work, you can do it like the correction below.

import os
def run(command):
    file = open("tmp.py", 'w')
    file.write(command)
    file.close()
    res = os.popen("sudo python3 tmp.py -f").read()
    return res
res = run ("print('hello') # Modify
print("Result"+res+"")


2022-09-22 20:04

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.