jay
jay

Reputation: 1524

Using local Python modules from python -c '...'

I'm having trouble getting the Python 3.5 CLI to run commands with the -c switch.

If I try python3 -c "print(5 + 9)" in the shell, the output is 14 as expected.

However, I have a file in the current working directory called gcd.py that looks like this:

def gcd(m, n):
    return m if n == 0 else gcd(n, m % n)

If I run python3 -m gcd -c "print(gcd(48, 18))" the shell just creates a new command prompt without outputting anything.

If I change the file to:

print('test')

def gcd(m, n):
    return m if n == 0 else gcd(n, m % n)

then the shell will output test, so the file is being loaded. Does anybody know what I'm doing wrong? Thanks.

Upvotes: 0

Views: 20

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121486

You can't use -m and -c together; either one or the other controls execution. Specifying them both makes Python ignore them.

Use an import statement in -c instead:

python3 -c "from gcd import gcd; print(gcd(48, 18))"

Note that -m treats the module as a script, it is not a 'import this module first' switch for -c.

Upvotes: 4

Related Questions