0

Imagine I have Python script, called 'script1.py', which simplies prints "Hello". I want to define a second script, 'script2.py' that runs 'script1.py'. 'script2.py' would return something like 'run('script1.py')'. In PowerShell, I then want to write something like

python3 script2.py

and return "Hello". Any easy way of doing this?

Using clipboard, one could simply whatever string I would like and paste it on PowerShell. However, this seems unnecessarily complicated. Any ideas on how to improve this?

3
  • Duplicate of stackoverflow.com/questions/89228/… Commented Nov 10, 2022 at 10:04
  • @SembeiNorimaki I didn't gather that from the OP's question - I understood that they want to be able to run the content of script1.py by running script2.py - but I might have misunderstood. OP - can you clarify? Commented Nov 10, 2022 at 10:08
  • @Vineet In all honesty, subprocess might solve it, but I was looking for something similar and more straightforward. Apologies if this remains vague, but I am fairly new to python. Commented Nov 10, 2022 at 10:28

1 Answer 1

1

In script1.py:

print ('hello')

in script2.py:

import script1

Running script2 yields:

hello
Sign up to request clarification or add additional context in comments.

3 Comments

yes, that would work if the script is not inside a if __name__ == "__main__". Being just a script you might be able to run it like this, but libraries usually don't execute their code to imports.
What if I want to run script1 multiple times? I tried nesting import script 1 in a for, but with no success. Any ideas?
In the example you've provided, the way to do that would be to write a function in script1.py, something like myfun = lambda: print ('hello'). Then, in script2.py, write from script1 import myfun, and then call myfun as often as you like inside script2.py. Do you have a specific use-case you'd like help with?

Your Answer

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.