简体   繁体   中英

How do I run a script in PyCharm that incorporates another script from the same project? (both scripts are in PyCharm)

I have an executable script in PyCharm that given some inputs defines certain variables. I also have another script that is in the same project, this second script uses the previously defined variables to preform tasks and returns information.

Does PyCharm have a way to do this easily or does it involve importing the file formally using an import statement at the top of the first script? If it involves import, then how would I call the second script inside the first?

My goal is to run the second script inside of the first script. Ideally in a more elegant way than pasting the whole second script into the first.

I don't think PyCharm has this feature because it wouldn't really be Python. What you can do is the following:

In first_script.py :

from second_script import my_function

# define certain variables with given some input
x = input()
y = input()
# ...

# call 'my_function', which is defined in 'second_script.py'
result = my_function(x, y)

And in the file second_script.py :

# define a function to process the variables and return something
def my_function(x, y):

  # process the variables
  z = x + y

  # and return the result
  return z

Both files first_script.py and second_script.py should be in the same directory. Then you have to configure PyCharm so that it executes first_script.py .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM