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?

sam wolfe
  • 103
  • 9
  • Duplicate of https://stackoverflow.com/questions/89228/how-do-i-execute-a-program-or-call-a-system-command – Sembei Norimaki Nov 10 '22 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? – Vin Nov 10 '22 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. – sam wolfe Nov 10 '22 at 10:28

1 Answers1

1

In script1.py:

print ('hello')

in script2.py:

import script1

Running script2 yields:

hello
Vin
  • 929
  • 1
  • 7
  • 14
  • 2
    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. – Sembei Norimaki Nov 10 '22 at 10:33
  • What if I want to run `script1` multiple times? I tried nesting `import script 1` in a `for`, but with no success. Any ideas? – sam wolfe Nov 14 '22 at 12:03
  • 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? – Vin Nov 14 '22 at 20:31